text:
Q: Group Theory Proof Prove that in any group G, $x^2=x$ has exactly $1$ solution.
For the proof, I know that the identity element $e$ is a solution because $e*e=e$. But how would I prove that that is the only solution?

A: Well $G$ is a group so there is $y\in G$ so that $yx=e$. So $xx=x\implies x=ex=yxx=yx=e$

A: Hint: Note that if $x^2 = x$ and $x$ is an element in a group, then $x$ has an inverse.

A: Hint There exists some $x^{-1}$ so that $x^{-1}*x=e$.


text:
Q: How to list files in amazon s3 bucket with in the folder using knox and nodejs I want to list file in my s3 bucket with in the folder, my bucket structure is
         /> folder_1
a_bucket -> folder_2
         \> folder_3

I want list files in folder_1 only

A: My problem got solved
s3client.list({ "prefix": "folder_1/" + filePrefix }, function (err, data) {
/* `data` will look roughly like:

  {
    Prefix: 'my-prefix',
    IsTruncated: true,
    MaxKeys: 1000,
    Contents: [
      {
        Key: 'whatever'
        LastModified: new Date(2012, 11, 25, 0, 0, 0),
        ETag: 'whatever',
        Size: 123,
        Owner: 'you',
        StorageClass: 'whatever'
      },
      ⋮
    ]
  }

  */
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: JQuery: how to make a list of words in html element ? Given a HTML DOM element with b elements such :

  My text have some words or groups of words in bold. How to do a variable list with these texts ?

Given we attack this with JS or JQuery.
How to get the list of all bold words, something like such :
var list = [ "text", "have some ", "words", "groups of words", "in","bold", "list" ,...];

I tried .text() and .html() but it doesn't work, see http://jsfiddle.net/LF5dX/1/
JSfiddle demo appreciate since more relevant for all future readers / users.

A: You can use .map() along with .text() and .get()
var list = $('div b').map(function(){
    return $.trim($(this).text());
}).get()

Demo: Fiddle

A: Try this,
var arr=[];
$('div b').each(function(){
    arr.push($(this).text());
});
console.log(arr);

Demo

A: EDIT: Oh, ok, I see OP has edited the answer, so this answer is no longer on-topic. Leaving it here though.
Not sure how you'd do it in jQuery, but here's how to do it in plain JavaScript:
var div = document.getElementsByTagName('div')[0];
var textContents = [].map.call(div.childNodes, function(node) {
    return node.textContent.trim();
});
console.log(textContents);

http://jsfiddle.net/RGaQp/1/


text:
Q: Calling require 'rubygems' in irb and rails console results => false. I'm trying to use 'awesome_print' gem in irb and rails console but when I call $ require 'rubygems' it results false. I tried reloading but didn't work.

A: The reason it returns false is that RubyGems is already loaded.
To use awesome print in plain irb, you'll just need to include the gem manually, like this:
require 'awesome_print'
Or in Rails, you can either chuck it in your Gemfile, or also use require 'awesome_print'


text:
Q: Exporting data with selected graphs in PHP good coding I have a page where the user can select a date range and around 40 checkboxes (checked by default). Each checkbox represents data that I capture and allow them to export. I want the checked checkboxes to be exported to my Excel file.
All the graphs I want to export are passed through via this variable in $_POST:
array (size=3)
  'from' => string '2019-01-24' (length=10)
  'to' => string '2019-02-24' (length=10)
  'graphs' =>
    array (size=5)
      'matches-graphs' =>
        array (size=3)
          0 => string 'amount_contact_per_day_org_vol' (length=30)
          1 => string 'amount_total_matches' (length=20)
          2 => string 'amount_clicks_phone' (length=19)
      'volunteers-graphs' =>
        array (size=3)
          0 => string 'amount_new_volunteers' (length=21)
          1 => string 'amount_volunteers' (length=17)
          2 => string 'amount_findable_volunteers' (length=26)
      'vacancies-graphs' =>
        array (size=6)
          0 => string 'amount_new_vacancies' (length=20)
          1 => string 'amount_active_vacancies' (length=23)
          2 => string 'amount_expired_vacancies' (length=24)
          3 => string 'amount_archived_vacancies' (length=25)
          4 => string 'amount_active_vacancies_per_interest' (length=36)
          5 => string 'vacancies_list_org' (length=18)
      'traffic-graphs' =>
        array (size=5)
          0 => string 'amount_views_per_vol_profile' (length=28)
          1 => string 'amount_views_per_vacancy' (length=24)
          2 => string 'amount_views_per_org_profile' (length=28)
          3 => string 'amount_logins_volunteers' (length=24)
          4 => string 'amount_logins_orgs' (length=18)
      'filters-graphs' =>
        array (size=3)
          0 => string 'filters_used_search_vol' (length=23)
          1 => string 'filters_used_search_org' (length=23)
          2 => string 'filters_used_search_vac' (length=23)

I then pass this $graphs array to a function where I want to export the graphs specified Excel. I am using phpoffice/phpspreadsheet library for this.
I want to pass through this array and for each item in there I want to write to the Excel file.
I was thinking with the following code, but there has to be a better way?
if (!empty($graphs)) {
        if (!empty($graphs['matches-graphs'])) {
            foreach ($graphs['matches-graphs'] as $graph) {
                if ($graph == 'amount_contact_per_day_org_vol') {
                    //Export data
                }
                if ($graph == 'amount_total_matches') {
                    //Export data
                }
                if ($graph == 'amount_clicks_phone') {
                    //Export data
                }
            }
        }
        if (!empty($graphs['volunteers-graphs'])) {
            foreach ($graphs['volunteers-graphs'] as $graph) {
                if ($graph == 'amount_new_volunteers') {
                    //Export data
                }
                if ($graph == 'amount_volunteers') {
                    //Export data
                }
                if ($graph == 'amount_findable_volunteers') {
                    //Export data
                }
            }
        }
        //etc for all categories
    }


text:
Q: Moment js gives unexpected dates I'm using moment.js to work with dates, but this gives me unexpected dates when using it.
const moment = require('moment');
console.log(moment().startOf('day').toDate());

console.log(moment().startOf('day').toDate());
<script src="https://momentjs.com/downloads/moment.min.js"></script>

This prints: 2020-10-13T21:00:00.000Z.
Why does it print 9PM? Should it print 12AM?

A: It is giving you midnight local time, but you're printing it out in zulu time. Try using toString instead, it will print the time out in local time.
Try moment().startOf('day').toString();


text:
Q: Vapor Swift How to delete files collected from fileIO I building a server that supports file uploading/deleting using Vapor. I am collecting files to be uploaded using something like this:
let path = req.application.directory.workingDirectory
req.fileio.writeFile(.init(data: fileData), at: path)

But I was not sure how to delete those files. I only see options to read/stream/collect/write from the documentation.
Any help would be great!

A: This is a function I use:
func deleteFile(_ filename: String) throws {
    let filepath = try workingDirectoryURL(with: ["folder/of/files", filename]).path
    try FileManager.default.removeItem(atPath: filepath)
}

Build the path from the project's base folder.


text:
Q: CSS "grid" layout with modern CSS (no JS) WANTED
I'd like to have a grid layout.
A bit like Pinterest, except the items have fixed height (so it should be a lot easier).
It should be responsive. The number of colums should be set according to the viewport size.
The DOM should be a simple list of childs inside a container. I don't want a wrapper element for each row. What I want is this:

a

b

c

d

e

f

g

h

i

The ordering of items matter, so the "b" item of the DOM should be on the right of the "a" item (and not under).

MY ATTEMPT
I have done this layout using flexbox but it feels quite hacky as I have to compute some margins with maths. Also I don't understand how to control the vertical space between my flexbox rows, as it seems to grow with the container height.
Here is my LESS mixin of the Codepen above:
.flexboxGridMixin(@columnNumber,@spacingPercent) {
  @contentPercent: 100% - @spacingPercent;
  @sideMargin: @spacingPercent/(@columnNumber*2);
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  > * {
    box-sizing: border-box;
    width: (100% - @spacingPercent)/@columnNumber;
    margin-left: @sideMargin;
    margin-right: @sideMargin;
  }
}

It seems doing math like that somehow defeat the initial purpose of flexbox no?
EXPECTED ANSWER
So, can someone explain me how to fix my flexbox layout? Or tell me what is the best, most elegant and modern way to solve this layout problem?
I don't want to use floats, probably not inline-block, nor JS based solution like Packery/Masonry
Please use modern CSS in your answers because I already know how to solve this with plain old CSS / JS. I target modern browsers only (to be defined)

Solution
Here is my final result, for those interested to reuse this layout.
Also a very nice visual Flexbox tutorial here: https://scotch.io/tutorials/a-visual-guide-to-css3-flexbox-properties

A:
I have done this layout using flexbox but it feels quite hacky as I have to compute some margins with maths.

Yes, I think you are using more code than necessary, and not taking advantage of several flexbox features. Your desired layout can be achieved simply and efficiently with flex properties.
HTML (removed unnecessary outer container in codepen)

a

b

c

d

e

f

g

h

i

j

k

CSS (I compiled your CSS for people who don't use preprocessors)
html, body { height: 100%; }

ul {
    display: flex;
    flex-wrap: wrap;
    height: 100%;
    list-style: none;
    padding: 0;
    align-content: flex-start; /* solves vertical margin problem (see note below) */
}

li {
    flex: 0 1 200px; /* don't grow, shrink proportionally, start at 200px width */
    background: pink;
    height: 100px;
    line-height: 100px; /* for demo only: center text vertically */
    text-align: center; /* for demo only: center text horizontally */
    box-sizing: border-box;
    margin: 15px;
}

DEMO: http://jsfiddle.net/mk8uksb2/
NOTE: In the original code, the space between rows was contracting or expanding relative to the viewport height because when a flexbox is created, a default rule is align-content: stretch. This means that the layout will expand to fill the size of the container. In the modified code, I override the default with align-content: flex-start, which packs the rows at the start of the container.
You were trying to meet several requirements for your grid. I think the modified code covers them all:

*

*I'd like to have a grid layout.

*... the items have fixed height.

*It should be responsive.

*The number of colums should be set according to the viewport size.

*The DOM should be a simple list of childs inside a container.

*I don't want a wrapper element for each row.

*The ordering of items matter, so the "b" item of the DOM should be on the right of the "a" item.


text:
Q: Velocity template localization I'm working on a task that's using Velocity to generate an email from a template.  One of my requirements is that the email message be localized, based on a Locale submitted by the user.  I've got this working for the most part, using Velocity's ResourceTool to pull in a MessageBundle.  The other requirement is that I can only have one template - I don't want one template per language or locale because this is difficult to maintain if changes are needed.
As a part of a MessageBundle, I can have what's referred to as "compound messages", which are messages that have variables that are replaced when the message is evaluated.  For example:
dear.name=Dear {0}:

My question is this: how do I get Velocity to replace the {0} value with a name that I pass in?
It's not acceptable to simply modify my Velocity template so that I simply replace the name at the template level - in some languages, the greeting word "Dear" comes after the name, so this would yield an incorrect output.

A: Found the answer: in my velocity template, I can use the Velocity directive:
#evaluate(${msg.dear.name})

And in my message bundle, my message looks like:
dear.name=Dear $name

If I set the name in the Velocity context, it gets replaced as I expect.


text:
Q: With a SCORM 2004 LMS and/or SCORM 2004 SCO's, can a teacher change the sequencing? I've been skimming over the numerous documents that describe SCORM 2004 and believe that the sequencing of activities is specified in the metadata of each SCO.  So, an SCO can define which other SCOs should be presented in case of passing or failing particular objectives that it presented.   Assuming that I'm correct, this suggests that the sequencing is rather static.
Our current LMS, which is not SCORM compliant also prescribes which activities a student should view if they pass or fail particular objectives.  It also allows a teacher to override prescriptions.
Does SCORM 2004 enable this sort of sequencing?

A:
the sequencing of activities is specified in the metadata of each SCO

No. The sequencing of activities is implemented through <sequencing> element in manifest file.

the sequencing is rather static

In SCORM 2004, the sequencing is completely dynamic; the sequencing implementation identifies the next activity based on both Tracking Model and Sequencing Definition Model of activities. In fact, the values of Tracking Model are dynamic but the values of Sequencing Definition Model are static. Actually, in SCORM 2004, the sequencing implementation collects the result of learner interactions with SCO (through CMI data model) and maps them to the Tracking Model and then evaluates the sequencing rules (defined for activities) based on the Tracking Model.


text:
Q: What happens if i try to split a string that cannot be split in python? I'm running the following code to read a graph from a file.File contains the adjacency list in the format: each line will contain:vertex neighbour1 neighbour2...
Here I'm trying to put it into a dictionary adjacent.now if a node does not have a neighbor what happens with the line.split()? there will be only the vertex in that line.
  f=open('graph','r')
  for line in f:
      values=line.split()
      for x in values[1:]:
           adjacent[values[0]].append(x)

A: You get a list of one element. Your next line will loop over an empty slice:
>>> 'one_vertex\n'.split()
['one_vertex']
>>> 'one_vertex\n'.split()[1:]
[]


text:
Q: ESAPI encryption and decryption I am using ESAPI Base64 encryption and decryption shown as is in:
http://www.programcreek.com/java-api-examples/index.php?api=org.owasp.esapi.codecs.Base64
This  is how my code looks:
import org.owasp.esapi.crypto.CipherText;
import org.owasp.esapi.crypto.PlainText;
import org.owasp.esapi.errors.EncryptionException;
import org.owasp.esapi.reference.crypto.JavaEncryptor;
import javax.crypto.EncryptedPrivateKeyInfo
import org.owasp.esapi.ESAPI
import org.owasp.esapi.ValidationErrorList
import org.owasp.esapi.Validator
import org.apache.commons.codec.binary.Base64;
class SampleMain {
public String decrypt2(String cryptedText){
    String clearText=null;
    try {
        CipherText cipherText=CipherText.fromPortableSerializedBytes(Base64.decodeBase64(cryptedText));
        clearText=ESAPI.encryptor().decrypt(cipherText).toString();
    }
    catch (  EncryptionException e) {
        System.out.println("EsapiEncryptor.decrypt: " + e.getMessage(),e);
    }
    return clearText.toString();
}

public String encrypt2(String clearText){
    String cryptedText=null;
    try {
        CipherText cipherText=ESAPI.encryptor().encrypt(new PlainText(clearText));
        cryptedText=Base64.encodeBase64(cipherText.asPortableSerializedByteArray());
    }
    catch (  EncryptionException e) {
        System.out.println("EsapiEncryptor.encrypt: " + e.getMessage(),e);
    }
    return cryptedText;
}

public static void main(String[] args) throws EncryptionException{

            String myplaintext = "MyPlaintext";
            SampleMain sample = new SampleMain();

            String enString = sample.encrypt2(myplaintext);
            System.out.println("-----------enString-----------: " + enString);

            String deString = sample.decrypt2(enString);
            System.out.println("-----------deString-----------: " + deString);

        }

}

But when I try to run this simple program i get the following exception:
Apr 01, 2017 12:43:30 PM org.owasp.esapi.reference.JavaLogFactory$JavaLogger log
WARNING: [SECURITY FAILURE Anonymous:null@unknown -> /DefaultName/IntrusionDetector] Likely tampering with KDF version on serialized ciphertext.KDF version read from serialized ciphertext (123190483) is out of range. Valid range for KDF version is [20110203, 99991231].
org.owasp.esapi.errors.EncryptionException: Version info from serialized ciphertext not in valid range.
    at org.owasp.esapi.crypto.CipherTextSerializer.convertToCipherText(CipherTextSerializer.java:299)
    at org.owasp.esapi.crypto.CipherTextSerializer.<init>(CipherTextSerializer.java:80)
    at org.owasp.esapi.crypto.CipherText.fromPortableSerializedBytes(CipherText.java:176)
    at org.owasp.esapi.crypto.CipherText$fromPortableSerializedBytes$0.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at gov.gsa.dss.test.SampleMain.decrypt2(SampleMain.groovy:30)
    at gov.gsa.dss.test.SampleMain$decrypt2$0.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at gov.gsa.dss.test.SampleMain.main(SampleMain.groovy:59)

Any ideas why I would be getting this error or such a simple program.    Thanks.

A: This works for me:
public String decrypt2(String encryptedText) {
    byte[] encryptedTextTextAsBytes = encryptedText.getBytes(StandardCharsets.UTF_8)
    CipherText cipherText = CipherText.fromPortableSerializedBytes(Base64.decodeBase64(encryptedTextTextAsBytes))
    ESAPI.encryptor().decrypt(cipherText).toString()
}

public String encrypt2(String clearText) {
    CipherText cipherText = ESAPI.encryptor().encrypt(new PlainText(clearText))
    new String(Base64.encodeBase64(cipherText.asPortableSerializedByteArray()), StandardCharsets.UTF_8)
}

You are passing a String to Base64.decodeBase64(), it might compile but I'm not sure of what Groovy does with that. You should pass a bytes[] (see how I obtain encryptedTextTextAsBytes). It might explain your error, it might not. I guess you did not post the exact code that produces the error you mention.


text:
Q: What is the use of DesiredCapabilities to include screenshot I know below code takes a screenshot of the page. But what is the different if i create a DesiredCapabilities instance and associate this capability to driver to take a screenshot? I am not getting why DesiredCapabilities are used for, though i have gone through some sites. Can someone explain in layman terms please? Why to set capabilities of platform, browserName, version?
WebDriver driver=new FirefoxDriver();
driver.get("http://www.google.com");

File srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile, new File("d:\\Screenshot.png"));
driver.close();

A: Capture screenshot works well with both selenium2 standard implementation and with remote webdriver.The RemoteWebDriver class does not implement the  TakesScreenshot interface so you have to create your own CustomRemoteWebDriver by extending RemoteWebDriver and implementing TakesScreenshot interface without doing it you cannot take screenshot with Remotedriver.
public class MyCustomRemoteWebDriver extends RemoteWebDriver implements TakesScreenshot {

.....

}

Another important feature of RemoteWebDriver is that exceptions often have an attached screenshot, encoded as a Base64 PNG.


text:
Q: Laravel how to secure blade from change in inspect element I have conditions in blade and working fine but little bit worry if somebody comes and use inspect element so he can add href and link and make button as example working if it was disabled, so what is the good way to secure my code
@if (auth()->user()->customer->package_id>0)

 Allready Purchased

@elseif(auth()->user()->customer->package_id==null)

Purchase

@endif


text:
Q: SQLXMLBULKLOAD XSD check for element value before load I am using SQLXMLBULKLOAD library to load a xml file using a xsd. Below is the section from XSD.
<xsd:element name="Information" sql:is-constant="1">
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element name="E_Code" type="xsd:string" sql:is-constant="1"/>
      <xsd:element name="E_Amount" type="xsd:string" minOccurs="0" sql:field="Amount_Paid"/>
      <xsd:element name="E_Quantity" nillable="true" minOccurs="0" sql:is-constant="1"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:element>.

The Element "Information" shown above can occur 10 times and i need to check if 'E_Code' = "xxxx" then only consider information block & E-Amount to bulk load otherwise proceed to the next information block for same condition check. Is it possible to do this in the schema file?
Please Help

A: XSD is a language for defining validity conditions on XML documents; it's not designed as a way to control the behavior of database loaders, and it would be surprising if you could control the behavior of a loader by changes to the XSD schema.


text:
Q: How to manage users from API on PHP Thanks for your help!! We have 2 more thing for need your Help.

*

*how to generate when function making new users

*please tell reference of UserStatusId
maybe 1001=active;
in portal, we can see active,disable,inactive and vpn only.
please tell us correct UserStatusId number.
Thanks in advance,
Naoki.

A: Take a look at this: https://forums.softlayer.com/forum/softlayer-developer-network/implementations/85004-how-to-manage-users-from-api-on-php
the statusID are:
1001 = Active; 1002 = Disable; 1003 = Inactive; 1021 = Delete ; 1022 = VPN Only
Regards


text:
Q: Example of convergence in probability, but expectation doesn't tend to 0 I'm self teaching probability, and came across this thread:
If the expectation tends to zero, show that $X_n \to X $ in probability.
I understand that the converse is not true, but am struggling to think of a counterexample.

A: Consider the RVs $X_n$ where $\mathbb{P}(X_n = n) = 1/n$ and $\mathbb{P}(X_n = 0) = 1-1/n$
Then $\mathbb{P}(|X_n -0|> \epsilon) = 1/n$ which goes to $0$ for big enough $n$ just fine.
But in $L1$/expectation we have that $\mathbb{E}[X_n] = 1$ for all $n$.
Note that this fails convergence in $Lp$ for all $p$, not just $1$.


text:
Q: Where is the center Pixel of an even filter (6x6) in Matlab (imfilter) and TensorFlow (tf.nn.conv2d)? For my master thesis i am currently porting a convolution operation from a Matlab Code to TensorFlow (Python API). The exception is that in Matlab an even filter_size was used (6x6).
By debugging the Output of the Matlab and my TensorFlow Code, i recognized that the function imfilter from Matlab acts way different than the tf.nn.conv2d operation in TensorFlow. I get way different mean and std values, same for the min and max values.
I can confirm that both, the values of my weights on Matlab and TF are the same and correct reshaped. The Bias is only a Scalar, so this isn't the problem either.
My presumption is that both functions imfilter (Matlab) and tf.nn.conv2d (TF) don't use the same center pixel for convolution, because the output of an odd kernel size is similar. So for an odd kernel size both functions operate similar.
Here is a snippet of the Matlab Code:
imfilter(input_data(:,:,j), conv_subfilter, 'same', 0, 'conv');

conv_subfilter is a 6x6x48 Filter Kernel and is convolving a Width x Heigth x 48 Image - the result is a Image with depth 1, for both, TF and Matlab
Here a snippet of my TF Code:
h_conv3_ip = convolution2d(max_pool_conv2, W_conv3_ip, b_conv3_ip, [1, 1, 1, 1], 'SAME', "h_conv3_ip")

def convolution2d(x, W, b, strides, padding, name):
    conv2d = tf.nn.conv2d(x, W, strides=strides, padding=padding, name=name)
    conv2d = tf.add(conv2d, b, name=name)
    return conv2d

Can someone tell me if the Kernel center is the problem or sth. else?
Thanks for help in advance!

A: I found out that the correct formula for calculating the center pixel is: floor(([m n] +1) /2).
I was testing it on a 10x10 patch, which was initialized with ones. The Filter 6x6 was initialized with ones too. In the upper left boarder i got a value of 16, both for the TF and Matlab convolution.
So there is no difference regarding the index of the center pixel.


text:
Q: SOAP in SWIFT import a Objective C Class Hi I'm gonna code my application on xCode in Swift, before i had problems with my WebService SOAP in Android, so I did some search and they're a lot of subjects about, but my WebService is particular, look in Android what I did:
    SSLConnection.allowAllSSL();

    SoapObject request = new SoapObject(NAMESPACE, "SendLead");
    request.addProperty("xml", xml);
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);
    HttpTransportBasicAuth httpTransport = new HttpTransportBasicAuth(URL, getResources().getString(R.string.login), getResources().getString(R.string.mdp));
    httpTransport.debug = true;
    httpTransport.call(SOAP_ACTION, envelope);
    SoapObject result = (SoapObject) envelope.bodyIn;
    Log.i(TAG, "Result Celsius: " + result);
    SoapObject SendLeadReturn = (SoapObject) result.getProperty("SendLeadReturn");
    String code = SendLeadReturn.getPropertyAsString("code");

So I have many constrains:

*

*https URL

*I have to keep my login to use the other functions of the wsdl (HttpTransportBasicAuth)

*I send and receive xml strings

How to do it, I think it's preferable to import a Objective C class, but which and how please ?


text:
Q: How to use ForkJoin for sequence of http requests Angular 4 I have a function which makes two http calls, the input of second http depends first http response and I need the two results to be returned at the same time. I have the below code which throws the error
SomeMethod(): Observable<any> {
    let firstResult;
    let secondResult;

    firstResult = http.get('////').map(data => {
        console.log('first response')
     secondResult = http.get('//// + {data.UserId}').map(response => {

        console.log('second response')
     })
    })

    return forkJoin([firstResult, secondResult]);
}

CallingMethod() {
    this.SomeMethod.subscribe(([firstResult, secondResult]) =>{
     /// Some logic
    })}

Getting error as undefined. Expected a observable, promise or array. After debugging got to know that first console output is printing, the second http call is never made and response is never seen.
How to return two nested calls responses together using forkJoin or any other mechanism?

A: Here is a StackBlitz of how to do this using concatMap. concatMap will execute sequentially, where as forkJoin will execute in parallel.
What you need to know
    const requests = [
      this.http.get('https://jsonplaceholder.typicode.com/todos/1'),
      this.http.get('https://jsonplaceholder.typicode.com/todos/2'),
      this.http.get('https://jsonplaceholder.typicode.com/todos/3'),
      this.http.get('https://jsonplaceholder.typicode.com/todos/4'),
      this.http.get('https://jsonplaceholder.typicode.com/todos/5'),
      this.http.get('https://jsonplaceholder.typicode.com/todos/6')
    ];

    from(requests).pipe(
      concatMap((request) => request.pipe(delay(2200)))
    ).subscribe((res) => {
      this.results$.next(this.results$.getValue().concat(res))
    })

*

*We create an array of requests (which are observables).

*Use the from operator to take your array and emit each array item

*Flatten those emissions with concatMap
I added a delay here as well to simulate slow loading.

A: Use Async & await to control multiple http requests.
async SomeMethod(): Promise <any> {

    let firstResult;
    let secondResult;
    firstResult = await http.get('////').toPromise();
    secondResult = await http.get('//// + {res1.UserId}').toPromise();

    return forkJoin(firstResult, secondResult);
}

 CallingMethod() {
    this.SomeMethod().then(result => {
       /// Some logic
    });
 }

A: The following code should work:
SomeMethod(): Observable < any > {
  let firstResult;
  let secondResult;

  return http.get('////').pipe(
    switchMap(res1 => http.get('//// + {res1.UserId}').pipe(
      map(res2 => [res1, res2])
    ))
  );
}

CallingMethod() {
  this.SomeMethod().subscribe(([firstResult, secondResult]) => {
    /// Some logic
  })
}

A: forkJoin takes arguments inline, not as an array (unless that's a change in rxjs between latest and what was bundled in Angular v4)
const req1 = this.http.get('https://jsonplaceholder.typicode.com/todos/1');
const req2 = this.http.get('https://jsonplaceholder.typicode.com/todos/2');

const results = forkJoin(req1, req2)

Output:
[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  }
]

StackBlitz is in v6 but its easy enough to back track if needed.


text:
Q: "Since she had given up smoking, ..." or "Since she gave up smoking, ..."?
Since she had given up smoking, she has been looking good.

or

Since she gave up smoking, she has been looking good.

Shouldn't it be "had given up"?

A: There is a relationship you have to keep between the tenses in the two clauses of since, when it means from the time when. If you don't have this relationship, we interpret since to mean because. See this website.
The relevant quote from this site:

When since introduces an action or event at a point of time in the past, we can use the past simple or present perfect after since and the present perfect in the main clause.

In this case, I think because I'm American, I greatly prefer the simple past in the first clause.
What this means is that the possible combinations of tenses are:

Since she gave up smoking, she has been looking good.
  Since she has given up smoking, she has been looking good.
  Since she had given up smoking, she had been looking good.

While the linked site doesn't mention the third possibility, it's grammatical and can be obtained from the either of the first two sentences by backshifting.
The since in both of these could also mean because, although it probably wouldn't be interpreted that way. If you want it to mean from the time when unambiguously, you have to use ever since.

A: You can't use HAD GIVEN UP as the action described in this part of the sentence doesn't happen BEFORE ANOTHER past action.
Compare:     She had given up smoking before she was 25.
It means she did something (gave up smoking) before some other event in the past (she was 25). One is earlier than the other.
Moreover, if "since" means " from the time when", we always use past simple after it.

A: You do not make it clear whether since is being used in the sense of as, or from the time when.
In either case the first sentence is NOT IDIOMATIC. But the second does work with from the time when, but does not work with as.
Recommended changes.
As she had given up smoking, she had been looking good.
From the time when she had given up smoking, she looked good.
As she gave up smoking, her finances improved.


text:
Q: Update Nested state in reactjs I have a component with state like. I am creating dynamic form, all is working fine but I want to reset the form value once submit button clicked.
for that i have a helper function called resetForm() , but unfortunately the logic is not working.
can anybody help with this..
state = {
    expenseForm: {
        date: {
            elementType: 'input',
            elementConfig: {
                type: 'date',
                placeholder: 'Enter Date..'
            },
            value: '',
            validation: {
                required: true,
                isDate: true
            },
            valid: false,
            touched: false
        },
        category: {
            elementType: 'select',
            elementConfig: {
                options: !this.props.loading ? transformCategory(this.props.categories): null
            },
            value: transformCategory(this.props.categories)[0].value,
            validation: {
                required: true,
                minLength: 4
            },
            valid: true,
            touched: false
        },
        description: {
            elementType: 'input',
            elementConfig: {
                type: 'text',
                placeholder: 'Enter Description..'
            },
            value: '',
            validation: {
                required: true,
                minLength: 6
            },
            valid: false,
            touched: false
        },
        amount: {
            elementType: 'input',
            elementConfig: {
                type: 'number',
                placeholder: 'Enter amount..'
            },
            value: '',
            validation: {
                required: true,
                minLength: 1
            },
            valid: false,
            touched: false
        }
    },
    formIsValid: false
}

React Component code link

A: You could have a function getInitialState that returns an object you can use as initial state for your component. When you need to reset the component state, you can use setState with the result of getInitialState again.
Example

function getInitialState() {
  return {
    email: "",
    password: ""
  };
}

class App extends React.Component {
  state = getInitialState();

  onChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  resetForm = () => {
    this.setState(getInitialState());
  };

  render() {
    const { email, password } = this.state;

    return (

          Email: <input name="email" value={email} onChange={this.onChange} />

          Password: <input name="password" type="password" value={password} onChange={this.onChange} />

        <button onClick={this.resetForm}> Reset </button>

    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));


text:
Q: Creating own Report in Odoo: t-field for date, Customer ID etc.? First of all I'm kinda new to Odoo and I'm trying to understand some Basic logic. I created my own Report based on the Basic Report of Odoo.
There are a lot of fields like t-field="o.date_invoice" or t-field="o.partner_id etc. which work really fine but where can I find all functions? Is there any list?
For Example I Need a Field for the order date and for the print date or for a Customer ID.

A: With a t-field attribute you can access and print fields from the actual model or from a related model, for example with the following element you can print the content of the phone column (field) of the actual record:
<span t-if="o.phone"
      t-field="o.phone" />

Explanation of t-field in the documentation:

The t-field directive can only be used when performing field access
  (a.b) on a "smart" record (result of the browse method). It is able to
  automatically format based on field type, and is integrated in the
  website's rich text edition.

Check this link for further information if you want to build reports and this one, where you can read about some the elements that you can use in Qweb
In addition, you can check here a list of some attributes that you can use in a Qweb template


text:
Q: Load xml row into 2D array So I have this xml
<document>
  <Month>
    <Depth>-0,25</Depth>
    <October>0,95</October>
    <November>-0,90</November>
    ...
  </Month>
  <Month>
    <Depth>-0,5</Depth>
    <October>0,47</October>
    <November>-0,17</November>
    ...
  </Month>
  ...
</document>

I've searched a bit and I saw some way to do it with linq but only with a 1D array, becasue what I would like to eventually end up with would be
Array[0,0] = -0.25
Array[0,1] = 0.95
Array[0,2] = -0.90
...

A: If you're happy with a jagged array (an array of arrays) then LINQ makes it fairly easy:
XDocument doc = XDocument.Load(...);
var array = doc.Root
               .Elements("Month")
               .Select(month => month.Elements().Select(x => (double) x).ToArray())
               .ToArray();

If you need a rectangular array, that's trickier.
Personally I would actually build a custom type with Depth, October and November properties, rather than relying on the order of the elements within Month, but that's a different matter.
Note that the above cast to double will (probably?) fail for the values you've got there - more conventional XML would use . instead of ,. However, if it does fail you can use double.Parse(x.Value, someAppropriateCulture) instead.


text:
Q: Programmatically Customizing UITableViewCell I want to programmatically create a custom UITableViewCell and implement it into a UITableViewController, but do not know how to. I searched the web and API, and couldn't find a solution to this. There are plenty of "storyboard"esk answers to this, but that is not what I am looking for. So, does anyone know how to do this, and on top of this, customize a UITableViewCell as if it were a UIView (in Objective-C)?
Update: Being more advanced now, than I was, I realize that this was a very bad question. Please ignore.

A: Check out this http://jslim.net/blog/2013/03/22/ios-create-uitableview-with-custom-cell-programmatically/
Hope this helps you.


text:
Q: How to determine the probability of an event, given that three events do not occur simultaneously.. Three events A, B and C do not occur simultaneously. We know that
$P(A\cap B)=P(B\cap C)=P(A\cap C)=\frac{1}{3}$
Please determine P(A).
Solution:
P(A) = 2/3

How would I go about to solve this question? I do not fully comprehend the meaning of the non-simultaneous occurrence in this question. Is it meant for pairs of 2 events happening at the same time, or is it meant that all events are disjoint?

A: Try drawing a Venn diagram. You'll realize that the events $A \cap B$, $B \cap C$, and $A \cap C$ are exhaustive and mutually exclusive, so it must be just the sum of the probabilities for the events involving $A$. To see this, notice that:
\begin{align*}
P(A) &\geq P((A \cap B) \cup (A \cap C)) & \text{since } (A \cap B) \cup (A \cap C) \subseteq A \\
&= P(A \cap B) + (A \cap C) & \text{since } P(A \cap B \cap C) = 0\\
&= 1/3 + 1/3 \\
&= 2/3
\end{align*}
and:
\begin{align*}
P(A) &= 1 - P(\overline A) \\
&\leq 1 - P(B \cap C)  \qquad \text{since } A \cap B \cap C = \emptyset \implies B \cap C  \subseteq \overline A \\
&= 1 - 1/3 \\
&= 2/3
\end{align*}
so $P(A) = 2/3$.

A: Given
$$P(A \cap B) = P(B \cap C) = P(A \cap C) = \frac{1}{3}$$
We can see
$$P(A \cap B) + P(B \cap C) + P(A \cap C) = 1$$
Now since
$$P(A \cap B \cap C) = 0$$
We know that exactly one of three events must occur:
Ether $(A \cap B)$ or $(A \cap C)$ or $(B \cap C)$. And no other outcome is possible.
Note: if $P(A \cap B \cap C) \neq 0$ then other possibilities may have existed because the sets would be joint and event $A$ on its own may have been possible for example but since we have proved that the sets are disjoint and since the combined probability adds to 1 no other outcomes are possible.
Thus
$$P(A) = P(A \cap B) \cup P(A \cap C) = \frac{1}{3}+\frac{1}{3} = \frac{2}{3}$$

A: The event that at least two of the three events $A,B,C$ occur is $AB \cup AC \cup BC$, and by the principle of inclusion/exclusion,
$$\begin{align}
P(AB \cup AC \cup BC) &= P(AB) + P(AC) + P(BC) -P(ABC)-P(ABC)-P(ABC) + P(ABC)\\
&= P(AB)+P(AC)+P(BC)-0-0-0+0\\
&= 1.
\end{align}$$
It follows that the probability of the
complementary event $-$ that at least two of the three events $A^c, B^c, C^c$
occur $-$ is $0$, and so the four subsets $AB^cC^c, A^cBC^c, A^cB^cC, A^cB^cC^c$ of the
complementary event also have probability $0$.
Next, note that $P(ABC^c) = P(AB) - P(ABC) =  P(AB)-0  = \frac{1}{3}$, and similarly,
$P(AB^cC) = P(A^cBC) = \frac{1}{3}$ also.   Hence,
$$\begin{align}P(A) &= P(ABC) + P(ABC^c) + P(AB^cC) + P(AB^cC^c)\\
&= 0 + \frac{1}{3} + \frac{1}{3} + 0\\
&= \frac{2}{3}.
\end{align}$$


text:
Q: select name from customers as @myvariable // dynamic AS in sql DECLARE @myvariable VARCHAR(100)
SET @myvariable = 'mytext'

SELECT Name FROM Customers AS @myvariable

How would one go about doing that?
Answer to Gareth:
This would allow me to retain the original name of the column when doing something like this:
declare @myvariable varchar(20)
set @myvariable='Name'

select case @myvariable when 'Name' then Name
                        when 'Id' then Id
       end
          as Name

from Customers

Right now, when the value of @myvariable changes, the colum name won't, but I need it to be the same as @myvariable.

A: Something like this could work
DECLARE @myvariable VARCHAR(100)
SET @myvariable = 'mytext'

DECLARE @sql NVARCHAR(200)

SET @sql = 'SELECT Name AS ' + QUOTENAME(@MyVariable)  + ' FROM Customers'

EXEC sp_executesql @sql

A: I think I understand what you are trying to ask, what you need to use is PL/SQL, my understanding of your question is you want to have a program that you want to enter in a variable name it output the results.
SET SERVEROUTPUT ON;

CREATE OR REPLACE PROCEDURE FindCustomer(customerName IN STRING) AS
BEGIN
     SELECT NAME INTO CUSTNAME FROM CUSTOMER WHERE NAME = customerName;
     DBMS_OUTPUT.PUT_LINE(CUSTNAME);
END FindCustomer;
/
PROMPT 'Input Customer\'s name';
ACCEPT temp;
EXECUTE FindCustomer(&temp);

I'm not completely sure if that is right seeing as I have not tested it but, that is a PL/SQL function that will in theory return you the Name of a customer that you input into the script via keyboard or whatever input. If you want to learn more about PL/SQL I suggest you go here


text:
Q: How to disable a textbox keyboard shorcuts in c#? I've just noticed that Textbox have a default shortcut so that whenever you press Ctrl + H, it starts with deleting letters as if you pressed BackSpace.
This can get quite annoying since I want to open a Form whenever Ctrl + H is pressed. Is there any way to stop the backspacing while still being able to use it to open the Windows Form?

A: CTRL-H is the ASCII BS (Backspace) character.
You can disable (or redefine) it, since CTRL+H and BackSpace are not exactly the same thing. There are a few examples listed on this question with other keys.
You need to add the KeyEventHandler in your Form1.Designer.cs like this:
this.textBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);

And in your Form1.cs add this function:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.H && e.Modifiers == Keys.Control)
    {
        //uncomment if ReadOnly is not working
        //e.SuppressKeyPress  = true;

        textbox1.ReadOnly = true;
        Form2 form2 = new Form2();
        form2.Show();
        textbox1.ReadOnly = false;
    }
}


text:
Q: merging CSV streams with node, trying to emit a header once and only once Using Node.js and NodeCSV.
I am looping over multiple CSV streams, and trying to merge them into a single CSV, with a header line as the first line. I am also filtering to get only records whose time column is later than a given time, though I am pretty sure this part isn't relevant to my problem.
The input CSVs have header lines, and some of them might not contain the expected columns, in which case they should pass through without emitting any records.
The code (modified for brevity, please excuse copy/paste/munge errors) is like this:
const csv = require('csv');
let header = true; // first record should emit a header line
const streams = [_array, _of, _read, _streams];
const lastIndex = streams.length - 1;
const sinceTime = Date.parse(someTime);
for (const [i, s] of streams.entries()) {
    s
        .pipe(csv.parse({columns: true}))
        .pipe(csv.transform(function (record) {
            const recordTime = Date.parse(record.time);
            if (recordTime > sinceTime) {
                return record;
            }
        }))
        .pipe(csv.stringify({
            columns: ['time', 'col'],
            header: header
        }))
        .pipe(output, {end: i === lastIndex});

    // this should only be cleared if the file actually emitted a header, but how do I know!?
    header = false;
}

The problem occurs when the first input file doesn't contain the time and col columns, let's say it's a csv with X and Y columns instead.
In this case, the file emits no records (as desired) but as a result it emits no header line, either.  But I don't know that, and happily set the header boolean to false.  Then my output contains no header line, which is not what I want.
If the first file is with the expected columns time and col, everything is great, and I get the header line from the first file.
How can I handle this case, and emit a header line even if the first file emits no records?
Update:
I thought of the following solution, which works, but it seems like there must be a better way.  I tried generating an empty CSV with a header before the loop, like this:
const csv = require('csv');
const streams = [_array, _of, _read, _streams];
const lastIndex = streams.length - 1;
const sinceTime = Date.parse(someTime);
const columns = ['time', 'col'];

// generate the header line with an empty CSV
csv
    .generate({length: 0})
    .pipe(csv.parse({columns: true}))
    .pipe(csv.stringify({
        columns: columns,
        header: true
    }))
    .pipe(output, {end: false});

for (const [i, s] of streams.entries()) {
    s
        .pipe(csv.parse({columns: true}))
        .pipe(csv.transform(function (record) {
            const recordTime = Date.parse(record.time);
            if (recordTime > sinceTime) {
                return record;
            }
        }))
        .pipe(csv.stringify({
            columns: columns,
            header: false
        }))
        .pipe(output, {end: i === lastIndex});
}

Ugly, but it's doing what I want it to do. Is there a cleaner way?


text:
Q: Android - Optimising multiple if-statements In my application, I have many IF statements that could be optimizing, but for the life of me can't work out a good possible solution without errors.
My current code:
    if (User_XP > -1){User_level.setText("1");Minimum_Level= Level1; Maximum_level = Level2;}
    if (User_XP > Level1){User_level.setText("1");Minimum_Level= Level1; Maximum_level = Level2;}
    if (User_XP > Level2){User_level.setText("2");Minimum_Level = Level2; Maximum_level = Level3;}
    if (User_XP > Level3){User_level.setText("3");Minimum_Level = Level3; Maximum_level = Level4;}
    if (User_XP > Level4){User_level.setText("4");Minimum_Level = Level4; Maximum_level = Level5;}
    if (User_XP > Level5){User_level.setText("5");Minimum_Level = Level5; Maximum_level = Level6;}
    if (User_XP > Level6){User_level.setText("6");Minimum_Level = Level6; Maximum_level = Level6;}
    if (User_XP > Level7){User_level.setText("7");Minimum_Level = Level7; Maximum_level = Level6;}
    if (User_XP > Level8){User_level.setText("8");Minimum_Level = Level8; Maximum_level = Level6;}
    if (User_XP > Level9){User_level.setText("9");Minimum_Level = Level9; Maximum_level = Level6;}

The idea of it is to work out a users level from a game, and from that create a percentage. But this area of coding is really not efficient as it can create multiple errors, anyone got any tips on a possible solution?
Please ask if more information is needed.

A: Perhaps store your level experience requirements in an array and use a loop.
int[] levels = new int[] { -1, Level1, Level2, Level3 };

int level;
for (level = 0; level < levels.length && userXp < levels[level]; level++) { }
int minLevel = levels[level];
int maxLevel = levels[level + 1];
userLevelText.setText(Integer.toString(minLevel));

A: Why not do something more generic?...
if (User_XP > Minimum_Level) {
    User_level.setText(Integer.toString(++Minimum_Level));
}

Of course if need the min/max instead of just doing a calculation..
if (User_XP > Minimum_Level) {
    User_level.setText(Integer.toString(++Minimum_Level));
    Maximum_Level = Minimum_Level + 1;
}

Then you could add in bounds checking before hand if you want to limit the absolute number if levels like if(Minimum_Level == 10) return; //Too much awesome!

A: It seems like
User_level.setText(String.valueOf(User_XP-1);Minimum_Level = User_level; Maximum_level = User_XP;
or something in that lines will do the job. The point is there seems to be some logic there, you should be able to eliminate the if statement all together.

A: In such cases I prefer making a static [not the java key word] propertiesfile/map/table and store the details in the properties,map or table. And then at run time read from the map and set the appropriate values or do things. This help is expansion without coding by simply adding values to


text:
Q: Rails custom routes I have created an extra route called 'add' in my Groups controller.
get 'groups/add', to: 'groups#add'
My goal is to have the following link http://localhost:3000/groups/4/add
I thought about doing this nested route
resources :groups do
  get 'groups/add', to: 'groups#add'
end

However when I run rake routes it is not listed. I have never really worked much with 'custom' routes before. I typically make due with the ones generated by a scaffold. How can I achieve this?

A: The following nested route has fixed my issue:
resources :groups do
  get 'add', on: :member
end


text:
Q: iTerm 2 vim t_Co=256 When I use vim app/controller/test.rb, opening the file takes 5 seconds. I have checked my .vimrc and I found out that if I delete the set t_Co=256, file opens quickly, but the code color highlighting doesn't work. How do I solve this problem?
This is my .vimrc file: [link].

A: t_Co=256

is useless. Instead, configure iTerm to advertise itself as a 256 colors capable terminal by setting its TERM to
xterm-256color

somewhere in the profile section of its options window.


text:
Q: Why aren't the Community user's accounts linked? When visiting the Community user's profile on any site, it doesn't have any other linked accounts. This makes navigating to Community's other profiles a bit difficult.
It looks like each profile is a separate user, and that's why they can't really be connected. Is that true? If so, what was the reason behind this decision?


text:
Q: Wi-Fi signal and client number I'm in a new collocation and residing in a room which is the farest to the router.
Oddly enough, it seems that the more person are using the Wi-Fi, the less stable is the connection. Does that make any sense ? Is it normal for Wi-Fi signal to get weaker when other people are using it ?
Anyway, I'd like to know if there may be a way to give my computer some priority over our local network ?
As of now for instance, I can't even connect to the Wi-Fi, whereas when nobody's connected, I have a huge bandwith. Messing with the QoS settings or something could fix that maybe ?

A: QOS with the router http://techpaul.wordpress.com/2011/05/17/restricting-roommates-internet-use-continued/  (2 articals there)
If you can put a program on the other peoples computers, a simple net limiter on each computer would work.
Setup a second wireless connect with a cheap USB wi-fi thing, and a cool program called Virtual Router.
Being at the far end of the signal , you might not even be negotiating the max speed of the connection to begin with, so if everyone gets the same time slice, you get less data still.
Balance out the distances and therefore strength of the signal, by putting the router more centrally located, or change the antenna type to a more directional style .
There is a cheap trick to use when wireLESS isnt strong enough, run a wire that the radio waves go down , it does not have to touch both antennas to get the signal closer to the other antenna. A bit crude but interesting.  the wire can be very small diameter.
Improve the max speed of the wi-fi to begin with , by using N router, and N capable client connections.
Achieve better cooperation with other users, and thier use of the connection.  Help THEM by showing them how to limit use by blocking adds, dumping flash junk, killing scripts, or even shutting off pictures. Multiple connections like sharing stuff would kill your bandwith, try and centralise these downloads on a wired system.
Very expencive bandwidth limiting software that is used by hotels and restraunts and all.  I did not yet find a cheap easy program that works like that for windows.


text:
Q: determining if two events are independent or not The set up for the question is:
A hand of five cards is dealt - randomly, one card at a time, and without replacement - from each of two standard decks of 52 cards.
the question:
Determine whether the events of "two hands have at least one card in common" and "the first hand is all hearts" are independent or not.
My thinking is that they are independent of each other. This is because if there is a hand full of hearts, at least one card may come up in common. Alternatively, if there is not a hand full of hands, this may also occur.
I'm not sure if I'm on the right track, or not, and if there is any way for me to prove this theory.

A: They are independent, since for a general hand of five, you can always relabel them by five  hearts. (In math language, to construct a permutation on the set {1,2,...,52}, such that five cards you have chosen are mapped into the 13-element subset representing hearts.) Hence knowing the first hand has 5 hearts does not give you any information.

A: Events $A$ and $B$ are independent iff $P(A|B)=P(A)$ (see e.g. wiki).
In words: whether you already know that $B$ is true or not makes no difference for the probability on $A$.
Now, suppose you already know there is a common card, then the probability the hand is all hearts has become zero. That is different from the normal chance of a hand full of hearts.
Therefore, the hands are not independent.


text:
Q: gBrowser.getBrowserAtIndex(i) sometimes fails on removeTab() Considering the following (simplified) example that works fine:
var tabs = window.gBrowser.tabs;
for (var i = 2, len = tabs.length; i < len; i++) {
  var uri = window.gBrowser.getBrowserAtIndex(i).currentURI.spec;
}

The following sometimes fails on the last tab with a message window.gBrowser.getBrowserAtIndex(...) is undefined
var tabs = window.gBrowser.tabs;
for (var i = 2, len = tabs.length; i < len; i++) {
  var uri = window.gBrowser.getBrowserAtIndex(i).currentURI.spec;
  window.gBrowser.removeTab(window.gBrowser.tabContainer.childNodes[i]);
}

I don't understand why it fails and why it only fails sometimes and not all the time.
Is there any other method that can be used instead of gBrowser.getBrowserAtIndex(i) to get the tabs' URL?

A: The root issue is that tabs is not an array but a NodeList, that is a live collection. When you call removeTab() the change is reflected in the NodeList (length, indices).
To avoid these side effects convert it to a true array
var tabsArr = [].slice.call(gBrowser.tabs);

A: It appears that you are closing tabs inside a loop where you have stored the initial number of tabs len = tabs.length and then comparing against the original number of tabs when the number of existing tabs may have changed due to your actions.
The construct:
for (let i = 2, len = tabs.length; i < len; i++) {...}
is more efficient under conditions where the length of tabs will not change.  However, in this case, you are changing the number of tabs and need to compare against tabs.length each time you are checking the terminating condition for this loop. So:
for (let i = 2, len = tabs.length; i < len; i++) {...}
In fact, the only reason your current loop does not always fail is that window.gBrowser.removeTab() is returning prior to the tab actually being deleted. You are in a race to see if you complete the loop prior to any tabs actually being removed.
However, that is not the only problem.  You are removing the tab on which you are currently indexed.  Under most conditions if the tab is removed, like most arrays, the remaining higher-index tabs are shifted down to be at the index you are already acting upon.  The only reason that the current loop does not routinely skip every other tab is that window.gBrowser.removeTab() returns prior to actually removing the tab you are currently indexed on.  You only actually skip a tab on the occasions where you are seeing the undefined error.
Your loop really should be something like:
for (let i = tabs.length - 1; i >=2; i--) {...}
This way you start at the end of the list and delete from there down.  This prevents both the undefined issue and the possibility of skipping a tab by eliminating the race condition of needing to complete the entire proces prior to any tab actually being removed.


text:
Q: Chaining Foreign Keys I have a few models that look like this:
class System(models.Model):
    '''Defines a system'''
    system_desc = models.CharField('System Name', max_length=50)

class SystemGroup(models.Model):
    '''Groups within a 'System' (ie. Customers, regions, divisions, etc. '''
    group_desc = models.CharField('Group Name',max_length=25)
    system = models.ForeignKey(System)

class QueryData(models.Model):
    '''Queries related to a 'System' (ie. Active users against System1, Orders today in system2, etc. '''
    qry_desc = models.CharField('Query Description', max_length=50)
    system = models.ForeignKey(System)

class UserDashboard(models.Model):
    '''User specific Dashboard '''
    user = models.ForeignKey(User)
    board_name = models.CharField('Dashboard Name', max_length=50)

class UserDashboardGroup(models.Model):
    '''Groups on the dashboard (ie. 'System 1's Key Indicators', 'System 2's Hot Sheet', etc. '''
    group_desc = models.CharField('Group Display Title', max_length=50)
    user = models.ForeignKey(User)
    dashboard = models.ForeignKey(UserDashboard)
    system = models.ForeignKey(System)
    system_group = models.ForeignKey(SystemGroup)

class UserGroupQuery(models.Model):
    '''Queries that run in a specific group on the dashboard (ie. Within 'System 1's Key Indicators, we run queries for active users today, orders in the last hour, etc. '''
    user = models.ForeignKey(User)
    dashboard = ChainedForeignKey(UserDashboard, chained_field='user', chained_model_field='user', show_all=False, auto_choose=True)
    user_dashboard_group = ChainedForeignKey(UserDashboardGroup, chained_field='dashboard', chained_model_field='dashboard')
    query = models.ForeignKey(QueryData)

I am having problems with the very last part of this. I want to restrict the 'query' that appears in a admin page based on the selected user_dashboard_group. I'm not sure how I can do this, based on my current models though. query and user_dashboard_group both have a foreign key to System, but not to each other. To get this though, I'd have to get the user_dashboard_group's system and then use that to filter the QueryData. How can I do this?
Edit
I'm adding in a picture to (hopefully) describe a little better what I want to do.
In step 1, the user inputs a name for this group of queries. This group is associated with a system (#2) and a predefined group within the system (#3) (think of #3 as a 'customer' or a 'region', etc and #1 and #3 are NOT the same thing, despite the similar naming). They then select 'Save and Continue editing' on this inline form and the drop down at step 4 becomes populated with information from the above form. Once step #4 has a selection made, I want #5 to populate with data only from the associated system. Since #2 contains this information, I am hoping it is fairly easy to do this, but I can't figure out the chaining.

I also realized that I didn't mention I was using django-smart-selects

A: I have never worked with django-smart-selects, but following the docs, I would expect
query = models.ChainedForeignKey(QueryData,**kwargs)

instead of
query = models.ForeignKey(QueryData)

since you want the options in query depend on the other selections. Is that understanding correct? If so, it was only about defining the right **kwargs.
For **kwargs, I would propose something like this
Update
chained_field='query', chained_model_field='user_dashboard_group__system__query_set__query'

assuming that the fields name is 'system in both cases.
I am pretty sure that this describes the relationship correctly. I am just not sure, if django-smart-selects supports that syntax.

A: Same way you would do it across one relation, except across two.
field__relation1__relation2


text:
Q: Why are the links and text disappearing from from this UL on my webpage? Full disclosure, this is an assignment from an advanced JS class I'm taking.  I've been trying to figure this out for a couple of weekends and it's driving me crazy!  I'm far more familiar with jQuery than I am straight JS (which is one of the reasons I'm taking this class).
The webpage is supposed to take input from the user to create a
 list of links with some other strings associated that are related to the link.  That part works just fine, what I can't figure out is why as soon as I'm done clicking on the Add Link button, the new link shows very briefly, then disappears!  If I click the button very quickly, I can get several of them to show up, but as soon as I stop, all of them disappear.
I tried making a fiddle out of this, but clicking on the Add Link button gave me a POST error (which may be a clue to it's behavior?).  If you cut & paste the code into an HTML file & run it, you'll see the behavior I'm describing.
I thought it had something to do with the init() function, so I tried running that at the bottom of the , but that didn't make any difference.  I also tried running it without an init, but couldn't figure out how to get the onclick listener initialized, even if it ran at the bottom of the .  I notice that even though I'm defining the favesList in global scope, it's still showing up as undefined after it should have been initialized with values (at least from my point of view).  However, it looks like it's going out of scope instead which doesn't make sense to me.  Console.log isn't providing me the reason why it's disappearing, or I haven't figured out a way to log the event.
I'm reasonably certain I'm missing a fundamental thing (like it's going out of scope for some reason?), so if someone could point out what that thing is I'd be grateful (I also don't need a definitive answer, just a nudge in the right direction, this is basically homework and I know I'm supposed to be figuring this out on my own, but I think a couple of Sundays of my time is giving it the college try).
Here's the code:
<!doctype html>

  <title>Advanced JavaScript Project: Favorites and Tags</title>
  <meta charset="utf-8">

Tag and save your favorites

    <form id="form">
     <fieldset>
      <legend>Add a new favorite:</legend>
      URL:
      <input id="url" type="url" placeholder="http://www.cnn.com" value="http://www.cnn.com">

      Title:
      <input id="title" type="text" value="CNN World News">

      Comment:
      <input id="comment" type="textarea" value="Thoughts?">

      Tags:
      <input id="tags" type="text" value="Enter keywords separated by commas">

      <input id="submit" type="submit" value="Add Link">
     </fieldset>
    </form>

List of favorites

A: You need to return false; as the last line in your AddFavorite() method, to stop the browser from processing the button and refreshing the page.


text:
Q: Unable to build app that use cocoa pods I recently reinstalled my Mac OS X Maverick distro and setted up my development environment. I was trying to follow the following tutorial to learn more about cocoa pods
 and I never could get the build to run successfully.
The tutorial is from this source: http://www.raywenderlich.com/64546/introduction-to-cocoapods-2
To resume, I've followed the next steps on terminal app:
1- run: sudo gem update --system (OK)
2- run: sudo gem install cocoapods (OK)
3- run: pod setup (OK - terminal returned this "Setting up CocoaPods master repo
Setup completed (read-only access)")
4- on the app path run: pod init (created Podfile)
5- run: open -a Xcode Podfile (modified iOS version OK and added pod 'AFNetworking', '2.2.1' between the "target 'Showtracker' do)
6- run: pod install (everything worked fine and the workspace and all files were created correctly)
After that I've opened the workspace file from finder and the workspace in Xcode showed exactly as it should with the 2 project files
When I've tried to build the app I've got the following error as the build result:

CompileC
  /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Objects-normal/i386/AFHTTPRequestOperation.o
  AFNetworking/AFNetworking/AFHTTPRequestOperation.m normal i386
  objective-c com.apple.compilers.llvm.clang.1_0.compiler
      cd /Users/mtopp/Documents/Workspace/ShowTracker/Pods
      export LANG=en_US.US-ASCII
      export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
      /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
  -x objective-c -arch i386 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=gnu99 -fmodules -fmodules-cache-path=/Users/mtopp/Library/Developer/Xcode/DerivedData/ModuleCache
  -Wno-trigraphs -fpascal-strings -O0 -Wno-missing-field-initializers -Wno-missing-prototypes -Wno-implicit-atomic-properties -Wno-receiver-is-weak -Wno-arc-repeated-use-of-weak -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wuninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wshorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wundeclared-selector -Wno-deprecated-implementations -DDEBUG=1 -DCOCOAPODS=1 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.1.sdk
  -fexceptions -fasm-blocks -fstrict-aliasing -Wprotocol -Wdeprecated-declarations -g -Wno-sign-conversion -fobjc-abi-version=2 -fobjc-legacy-dispatch -mios-simulator-version-min=7.0 -iquote /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Pods-ShowTracker-AFNetworking-generated-files.hmap -I/Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Pods-ShowTracker-AFNetworking-own-target-headers.hmap
  -I/Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Pods-ShowTracker-AFNetworking-all-target-headers.hmap
  -iquote /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Pods-ShowTracker-AFNetworking-project-headers.hmap -I/Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Products/Debug-iphonesimulator/include
  -I/Users/mtopp/Documents/Workspace/ShowTracker/Pods/BuildHeaders -I/Users/mtopp/Documents/Workspace/ShowTracker/Pods/BuildHeaders/AFNetworking
  -I/Users/mtopp/Documents/Workspace/ShowTracker/Pods/Headers -I/Users/mtopp/Documents/Workspace/ShowTracker/Pods/Headers/AFNetworking
  -I/Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/DerivedSources/i386
  -I/Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/DerivedSources
  -F/Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Products/Debug-iphonesimulator
  -fobjc-arc -w -Xanalyzer -analyzer-disable-checker -include /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/PrecompiledHeaders/Pods-ShowTracker-AFNetworking-prefix-aypnknzjycfqnmhhpckrwqzjddtp/Pods-ShowTracker-AFNetworking-prefix.pch -MMD -MT dependencies -MF /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Objects-normal/i386/AFHTTPRequestOperation.d
  --serialize-diagnostics /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Objects-normal/i386/AFHTTPRequestOperation.dia
  -c /Users/mtopp/Documents/Workspace/ShowTracker/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m
  -o /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Objects-normal/i386/AFHTTPRequestOperation.o
Stack dump:
  0.    Program arguments: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
  -cc1 -triple i386-apple-ios7.0.0 -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -main-file-name AFHTTPRequestOperation.m -mrelocation-model pic -pic-level 2 -mdisable-fp-elim -masm-verbose -target-cpu yonah -target-linker-version 236.3 -gdwarf-2 -coverage-file /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Objects-normal/i386/AFHTTPRequestOperation.o
  -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/5.1
  -dependency-file /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Objects-normal/i386/AFHTTPRequestOperation.d
  -MT dependencies -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.1.sdk
  -iquote /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Pods-ShowTracker-AFNetworking-generated-files.hmap -iquote /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Pods-ShowTracker-AFNetworking-project-headers.hmap -include-pch /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/PrecompiledHeaders/Pods-ShowTracker-AFNetworking-prefix-aypnknzjycfqnmhhpckrwqzjddtp/Pods-ShowTracker-AFNetworking-prefix.pch.pch
  -D DEBUG=1 -D COCOAPODS=1 -I /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Pods-ShowTracker-AFNetworking-own-target-headers.hmap
  -I /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Pods-ShowTracker-AFNetworking-all-target-headers.hmap
  -I /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Products/Debug-iphonesimulator/include
  -I /Users/mtopp/Documents/Workspace/ShowTracker/Pods/BuildHeaders -I /Users/mtopp/Documents/Workspace/ShowTracker/Pods/BuildHeaders/AFNetworking
  -I /Users/mtopp/Documents/Workspace/ShowTracker/Pods/Headers -I /Users/mtopp/Documents/Workspace/ShowTracker/Pods/Headers/AFNetworking
  -I /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/DerivedSources/i386
  -I /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/DerivedSources
  -F/Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Products/Debug-iphonesimulator
  -O0 -Wno-trigraphs -Wno-missing-field-initializers -Wno-missing-prototypes -Wno-implicit-atomic-properties -Wno-receiver-is-weak -Wno-arc-repeated-use-of-weak -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wuninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wshorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wundeclared-selector -Wno-deprecated-implementations -Wprotocol -Wdeprecated-declarations -Wno-sign-conversion -w -std=gnu99 -fdebug-compilation-dir /Users/mtopp/Documents/Workspace/ShowTracker/Pods -ferror-limit 19
  -fmacro-backtrace-limit 0 -fmessage-length 0 -stack-protector 1 -mstackrealign -fblocks -fmodules -fmodules-cache-path=/Users/mtopp/Library/Developer/Xcode/DerivedData/ModuleCache
  -fobjc-runtime=ios-7.0.0 -fencode-extended-block-signature -fobjc-arc -fobjc-exceptions -fexceptions -fpascal-strings -fdiagnostics-show-option -fdiagnostics-show-note-include-stack -fasm-blocks -vectorize-slp -serialize-diagnostic-file /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Objects-normal/i386/AFHTTPRequestOperation.dia
  -o /Users/mtopp/Library/Developer/Xcode/DerivedData/ShowTracker-eidspshbmfufcxeoawmixoxklvzq/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-ShowTracker-AFNetworking.build/Objects-normal/i386/AFHTTPRequestOperation.o
  -x objective-c /Users/mtopp/Documents/Workspace/ShowTracker/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m

*

* parser at end of file

*Code generation

*Running pass 'Function Pass Manager' on module '/Users/mtopp/Documents/Workspace/ShowTracker/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m'.

*Running pass 'X86 DAG->DAG Instruction Selection' on function '@"\01-[AFHTTPRequestOperation responseObject]"' clang: error: unable
  to execute command: Segmentation fault: 11 clang: error: clang
  frontend command failed due to signal (use -v to see invocation) Apple
  LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn) Target:
  i386-apple-darwin13.0.0 Thread model: posix clang: note: diagnostic
  msg: PLEASE submit a bug report to
  http://developer.apple.com/bugreporter/ and include the crash
  backtrace, preprocessed source, and associated run script. clang:
  note: diagnostic msg:

PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT: Preprocessed
  source(s) and associated run script(s) are located at: clang: note:
  diagnostic msg:
  /var/folders/z3/wmz14g7527l40snggf1b5qb40000gn/T/AFHTTPRequestOperation-4de2a1.m
  clang: note: diagnostic msg:
  /var/folders/z3/wmz14g7527l40snggf1b5qb40000gn/T/AFHTTPRequestOperation-4de2a1.sh
  clang: note: diagnostic msg:
**************** Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
  failed with exit code 254

I can't find the solution and the error is so general that I've read a lot of different problems.
I will appreciate any help or guidance you can provide


text:
Q: "unable to get setup.ini" error during Cygwin installation While installing cygwin I'm getting the following error
unable to get setup.ini

What is the reason?
I'm newly studying Unix. So Please guide me in this.

A: I think you just need go to [http://www.cygwin.com/] to download the latest setup.exe file.
actually, the error msg tells you that it can not find the setup.ini file, yes, the setup file changed the location.

A: I was getting the same problem, when I selected "Direct connection to internet", then I did change it to "Use Internet Explorer Proxy Settings" and it worked so good... try and let me know..

A: I had to switch from setup.exe to setup-x86.exe or setup-x86_64.exe.

A: Try -X on the command line to setup.exe, worked for me.
The "Use Internet Explorer Proxy Settings" did not work for me.

A: I was having this problem when running setup.exe from a network drive.  When I copied setup.exe to my local drive, it ran correctly.

A: The setup.exe installer lets you select one of several dozen download locations (mirrors).  The setup.ini file is downloaded from the mirror you select.  If that fails, the first thing I'd try is to pick a different mirror.
It's also possible that you need to change the proxy settings (direct connection vs. IE proxy settings), as others have mentioned.

A: What is the URL that follows that message ? Is there any ?
Doing a quick search on google I found that broken URLs causes that message.
See, for instance: http://prc-tools.sourceforge.net/install/cygwin.html

If you get the error message Unable to get setup.ini from http://prc-tools[...], check the URL you added and add it again if necessary. Most people who have encountered this message have eventually found that it was caused by a mere typo, such as the addition of a trailing space to the URL.)

Try to download the URL directly in a browser. If you get 404 error, then you found the problem, and you should pickup another mirror download site on cygwin.
Also, I would really recommend installing Ubuntu sideways with Windows, if you're going to really study *nix systems.


text:
Q: Extremely slow package management after upgrading from package.config to PackageReference We have a solution with 300+ projects. They are all .Net framework 4.7. As a preparation for migrating to .Net 5 we replaced the old style package.config with PackageReference and now everything became agonizingly slow. Both with VS 2019 and Rider. Sometimes and for some projects, working with nuget packages seems to work fine, then suddenly it becomes completely unresponsive. We might have to wait several minutes to remove or upgrade a single nuget package.
Does anyone have any experience with this?


text:
Q: can you tell me why this will only sort to the value of 10? Below is a snippet of code that takes all my data from my database and sorts them and shows them, it currently sorts them by # of votes all the way up to 10 votes, it seems almost as if it is sorting only off the first number,

    <?php echo $pages_site; ?>

<?php foreach($members as $member){
    $votes  =htmlentities($member['votes']);
    $id     =htmlentities($member['id']);
    $url    =htmlentities($member['first_name']);
    $sname  =htmlentities($member['last_name']);
    $status =htmlentities($member['status']);
    $desc   =htmlentities($member['bio']);
    $banner =htmlentities($member['image_location']);
?>

    <A href="<?php echo $url ?>"><?php echo $sname ?>
<? echo $desc ?>
<a href="<?php echo $url ?>"><img src="<? echo $banner ?>" style="max-width:500px;max-height:200px";>
    VOTES:<?php echo $votes ?>
<a href="vote.php?id=<?php echo $id ?>">VOTE!

<?
    }
?>

i've tried moving votes to the top of the db and tried changing the defult value of votes to 00 rather then 0 but that makes it show 01 rather then just 1, and i would prefer avoid that if possable


text:
Q: expected error not working using angular 12 i tried to generate the expected errors, so i created a delete function, use api and jsonplaceholder, which contains 100 posts, so i tried to delete posts whose id = 123 means that does not exist in the posts list from jsonplaceholder, I pass in the function to delete posts 123, when I click on button delete the post delete without generating an error message "the post that wants to delete does not exist".
posts.component.ts
deletePost(post:any){
      this.postService.deletePost(123)
         .subscribe((response:any) => {
           let index = this.posts.indexOf(post);
           this.posts.splice(index, 1);
         }, (error:Response) => {
           if(error.status === 404){
              alert("the post that wants to delete does not exist")
           }else{
            alert('error inattendue');
                 console.log(error)
           }
        });
  }

posts.service.ts
private url:any = 'https://jsonplaceholder.typicode.com/posts';

deletePost(post:any){
    return this.http.delete(this.url + '/' + post.id)
  }

A: I don't understand why you deleted it directly. For this reason, I recommend using toPromise instead of the subscribe function.
deletePost(post:any){
      this.postService.deletePost(123)
         .toPromise().
         .then((response:any) => {
           let index = this.posts.indexOf(post);
           this.posts.splice(index, 1);
         })
         .catch((error:Response) => {
           if(error.status === 404){
              alert("the post that wants to delete does not exist")
           }else{
            alert('error inattendue');
                 console.log(error)
           }
         })
  }


text:
Q: Django model, ImportError attempted relative import with no known parent package I'm making a small Django app, and i just want to make some tests over the QuerySet of my model. However, when running code outside the manage.py runserver environment, i get this error :
from .models import Article

Error:
ImportError: attempted relative import with no known parent package

As already said, this works perfectly when making views, i can import my Article model and create Articles from the admin dashboard.
My app structure looks like this:
app/
  admin.py
  apps.py
  models.py (this contains my Article model)
  views.py
  file_where_ihave_my_error.py
  __init__.py

A: Django accepts from .models import *model_name*, but when you try to run the file as any other Python app, you'd get such an error.
to solve it, you either need to user from models import *model_name*, or run Django server python manage.py runserver


text:
Q: Own Configuration of Spring Cloud LoadBalancerClient I want to do my own configuration for the Spring Cloud LoadBalancerClient (Package org.springframework.cloud.client.loadbalancer.LoadBalancerClient). However, the configuration is not applied, Round Robin is used by default.
Can anyone help me further?
public class CustomLoadBalancerConfiguration {

    @Bean
    ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
                                                            LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new RandomLoadBalancer(loadBalancerClientFactory
                .getLazyProvider(name, ServiceInstanceListSupplier.class),
                name);
    }

}

public class Client {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @LoadBalanced
    private RestTemplate restTemplate = new RestTemplate();

    private String getBaseUrl() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("eventService");
        System.out.println(serviceInstance);
        return serviceInstance.getUri().toString();
    }

    @GetMapping("/all")
    public String getAll() throws JsonProcessingException {
        String url = getBaseUrl()+"/xx";
        return restTemplate.getForObject(url, String.class);
    }

}

A: In Spring Cloud documentation (https://docs.spring.io/spring-cloud-commons/docs/3.0.3/reference/html/#custom-loadbalancer-configuration), when you create a Custom Load Balancer Configuration, you need to add the following configuration:
@Configuration
@LoadBalancerClient(value = "stores", configuration = CustomLoadBalancerConfiguration.class)
public class MyConfiguration {

    @Bean
    @LoadBalanced
    public WebClient.Builder loadBalancedWebClientBuilder() {
        return WebClient.builder();
    }
}

So it can be used.


text:
Q: How to make certain apps not be affected by your theme? I'm using the Arc theme for Ubuntu, and for most apps it is beautiful. My problem is that for some, it makes them unusable.
I just setup Enpass for password management. But the Arc theme makes it so hard to use, from a visual perspective.
So what can I do to fix this? I want to exclude specific apps from the theme entirely.
I'm on Ubuntu 16.04.1.


text:
Q: Javascript- send the clicked object as parameter in onClick function In function clickCircle, i want to use the li which is being clicked. So i want to receive it as a parameter.

But what should i send as an actual paramenter? ie in place of 'this'.

A: You can use this:
function clickCircle(obj) // the li element clicked in the current scope
{
    var element = obj;  // This is the DOM object being clicked
    var $this = $(obj); // This is the jQuery object being clicked

    // Use DOM object like
    element.style.color="#ff0000";

    // Use jQuery object like
    $this.css('color', 'red');
}

A: Try this instead

$('.circle').on('click', function(event) {
  event.target // your element
});

A: You should just use the first parameter as the element.
HTML

JS
clickCircle=function(element)
{
console.log(element)
console.log(element.tagName) // This will show LI
}

JSFiddle: http://jsfiddle.net/edi9999/WhVLm/

A: you can do it with jquery like this:
$(function () {
  $('li.circle').on('click', function () {
    clickCircle($(this));
  });
});

var clickCircle = function (param) {
  // your code here
  // param.css('color', 'red').html();
};

or with raw javascript:
HTML

JAVASCRIPT
var circle = document.getElementById('circle');

circle.addEventListener('click', function (e) {
  clickCircle(e.target);
});

var clickCircle = function (param) {
  // your code here
  // alert(param.nodeName.toLowerCase());
}


text:
Q: Trigger, o editar archivo sin permiso (no formulario) Google script He creado un panel mediante doGet (panel HTML), vinculado a una hoja de cálculo. La misma la utilizaran supervisores de la empresa en donde trabajo. Depende de que supervisor abra la página, le aparecerán en una lista desplegable solo los empleados de sus sector. (getEffectiveUser).
Al seleccionar un empleado de la lista desplegable, extrae del archivo algunos datos correspondiente al empleado
El inconveniente que tengo es que debo darle permiso a los supervisores para que editen el archivo (por más que lo hagan desde el panel HTML), y la idea es que esas personas no puedan ver el archivo. El archivo se puede compartir a la organización sin que las personas se den cuenta, pero cuando cuando cargan datos mediante el panel html, el archivo les aparece en el Drive en la parte de "Recientes".
Un formulario no me es útil ya que no extrae datos de una hoja de cálculos dinámicamente.
Probé con agregar un archivo de modo "interfase", pero el cambio se debe hacer manual para ejecutar un activador, y por tiempo, el mínimo es de 1 minuto y es demasiado, ya que debe ser automática la devolución de la carga de la hoja de cálculo al panel html.


text:
Q: React JS: How to send data from one Component to another Component onClick event I am designing a bike rental app. The main Area page displays the bikes available with the names, models and images of the bike in Cards. Now when we click on book we are redirected to the Checkout page. I need to send the name and model information of the bike selected to the Checkout page. How to do that?
BikesCard.js
import React, { Component } from 'react';
import {
  Card, CardImg, CardText, CardBody,
  CardTitle, CardSubtitle, Button
} from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

class BikesCard extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    console.log(this.props.bikes)
    this.props.propdata.history.push(`/Checkout`)
  }

  render() {
    return (

        <Card className="Card">
          <CardImg top width="100%" src={this.props.bikes.image} alt="Card image cap" />
          <CardBody>
            <CardTitle>{this.props.bikes.name}</CardTitle>
            <CardSubtitle>{this.props.bikes.model}</CardSubtitle>
            <CardText>{this.props.bikes.description}</CardText>
            <Button onClick={this.handleClick}>Book</Button>
          </CardBody>
        </Card>

    )
  }

}

export default BikesCard;

Checkout.js
import React, { Component } from 'react';
import { Card, CardImg, CardText, CardBody, CardTitle, CardSubtitle, Button } from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import NavBar from './NavBar.jsx';

class Checkout extends Component {
  constructor(props) {
    super(props);
    console.log(this.props.bikes);
    this.state = {

    };

    this.confirmClick = this.confirmClick.bind(this);
    this.goBackClick = this.goBackClick.bind(this);
  }

  confirmClick() {
    this.props.history.push("/myBookings");
  }

  goBackClick() {
    this.props.history.push("/home");
  }

  render() {

    let btnstyle = "10px 0%";
    return (

        <NavBar/>
          <Button onClick={this.confirmClick}>Confirm Booking</Button>
          <Button onClick={this.goBackClick}>Go Back</Button>

        // should display Card with the details of the bike which is selected. It should have two buttons i.e, confirm booking button and go back buttton

    );
  }
}
export default Checkout;

A: You can pass data with history.push like this:
this.props.propData.history.push({
 pathname: '/checkout',
 state: data_you_need_to_pass
});

And read it from /checkout like this:
const data = this.props.location.state;

You can read more here


text:
Q: Programming in C, Stephen Kochan - Chapter 11, Exercise 3 I'm teaching myself C with the book Programming in C by Stephen Kochan and I have come to the following exercise on pointers:

*Write a function called insertEntry to insert a new entry into a linked list. Have the procedure take as arguments a pointer to the list entry to be inserted (of type struct entry as defined in this chapter), and a pointer to an element in the list after which the new entry is to be inserted.

The struct entry structure is defined as follows:
struct  entry
{
    int x;
    struct entry  *ptr;
};

This is my code:
#include <stdio.h>

void insert_entry (struct entry  *new_entry, struct entry  *prev_entry);

struct entry
{
    int x;
    struct entry  *ptr;
};

int main (void)
{
    struct entry  n1, n2, n3, new_entry;
    struct entry  *list_ptr = &n1;

    n1.x = 1;
    n1.ptr = &n2;

    n2.x = 2;
    n2.ptr = &n3;

    n3.x = 4;
    n3.ptr = (struct entry *) 0;

    insert_entry (&new_entry, &n2);

    // Loop to display the list to check if insert_entry worked
    while ( list_ptr != (struct entry *) 0 ) {
        printf ("%i\n", list_ptr->x);
        list_ptr = list_ptr->ptr;
    }
}

void insert_entry (struct entry  *new_entry, struct entry  *prev_entry)
{
    new_entry->ptr = prev_entry->ptr;
    prev_entry->ptr = new_entry;

    // Assign a value to make it easier to check if the function worked
    new_entry->x = 3;
}

This code works just fine and gets the job done. But then there's exercise #3:

*The function developed in exercise 2 only inserts an element after an existing element in the list, thereby preventing you from inserting a new entry at the front of the list. How can you use this same function and yet overcome this problem? (Hint: Think about setting up a special structure to point to the beginning of the list.)

I have no idea how to continue. If I set up another structure I won't be able to pass it as an argument without changing the formal parameters of the insert_entry function takes. But I can't use the list_ptr pointer, because if I passed it as the second argument to the insert_entry function the statement new_entry->ptr = prev_entry->ptr; wouldn't make sense.
Other questions about this focus on exercise #2 but I wasn't able to find anything on this. Help would be eternally grateful. Thanks in advance.
*EDIT: This is what my code looks like now (thanks to u/ringzero):
#include <stdio.h>

void insert_entry (struct entry  *new_entry, struct entry  *prev_entry);

struct entry
{
    int x;
    struct entry  *ptr;
};

int main (void)
{
    struct entry  n_start, n1, n2, n3, new_entry;
    struct entry  *list_ptr = &n_start;

    n_start.ptr = &n1;

    n1.x = 1;
    n1.ptr = &n2;

    n2.x = 2;
    n2.ptr = &n3;

    n3.x = 3;
    n3.ptr = (struct entry *) 0;

    insert_entry (&new_entry, &n_start);

    // Loop to display the list to check if insert_entry worked
    while ( list_ptr != (struct entry *) 0 ) {
        printf ("%i\n", list_ptr->x);
        list_ptr = list_ptr->ptr;
    }
}

void insert_entry (struct entry  *new_entry, struct entry  *prev_entry)
{
    new_entry->ptr = prev_entry->ptr;
    prev_entry->ptr = new_entry;

    // Assign a value to make it easier to check if the function worked
    new_entry->x = 0;
}

n_start is supposed to be a dummy structure. The only problem with the code is that the loop displays the value of n_start.x. How can I make it so that it doesn't get displayed?

A: The author, Stephen Kochan, has a website: classroomm.com
There's a Forum there with a small section relating to his book "Programming in C, 3rd edition." It includes the answers to the odd-numbered end-of-chapter exercises. You could find it quite useful.
Here's the relevant information from that website as a slight hint how to answer the exercise:

You can solve this problem by setting up a "dummy" structure variable
      called listHead,
for example:
     struct entry  listHead;

and you can then set it pointing to the head of the list by assigning    the next member of listHead to point to the actual first
  entry of the    list:
       listHead.next = &entry1;

Now to insert a new entry called newEntry at the front of the list,    you can write:
       insertEntry (&new_entry, &list_head);

I won't post the code I wrote for the exercise -- you'll learn more if you wrangle with it yourself.


text: Q: Apache Tomcat Server not showing properly, just listing files my Apache Tomcat server on browser did not show the typical server management page, instead, it is showing the file directory. Could anyone advise what might be wrong?


text:
Q: CORS not working using CORS Filter where client and server is in same url I am trying to implement CORS where the client and server are in the same URL using CORS Filter.
Below is the code I have implemented
CORS Filter
package com.core.web.spring.cors;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CORSFilter implements Filter{

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        ((HttpServletResponse) res).addHeader("Access-Control-Allow-Origin", "http://192.168.0.103:1111");
        ((HttpServletResponse) res).addHeader("Access-Control-Allow-Methods",
                "GET, POST");
        ((HttpServletResponse) res).addHeader("Access-Control-Max-Age", "3600");
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }

    }

}

web.xml
<filter>
  <filter-name>cors</filter-name>
  <filter-class>com.core.web.spring.cors.CORSFilter</filter-class>
</filter>

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

I have set the Access-Control-Allow-Origin as http://192.168.0.103:1111. I am changing the origin to http://192.168.0.108:1111 from the postman tool. But instead of blocking the request, it is executing it. I am getting a successful response.
Below is the request header and response header
Request Header
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Connection: keep-alive
Content-Length: 1296
Content-Type: text/html; charset=UTF-8`enter code here`
Host: 192.168.0.103:1111
Origin: http://192.168.0.108:1111
Referer: http://192.168.0.103:1111/SampleTest/index.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
X-Requested-With: XMLHttpRequest

Response Header
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Origin: http://192.168.0.103:1111
Access-Control-Max-Age: 3600
Connection: keep-alive
Content-Length: 1210
Date: Sat, 03 Jul 2021 06:11:55 GMT
Server: WildFly/11
Strict-Transport-Security: max-age=7776000; includeSubdomains
X-Content-Type-Options: nosniff
X-FRAME-OPTIONS: SAMEORIGIN
X-Powered-By: Undertow/1

Can anyone help me with this?

A: Postman doesn't care about SOP (Same-Origin Policy), it's a dev tool, not a browser.
CORS (Cross-Origin Resource Sharing) and SOP (Same-Origin Policy) are server-side configurations that clients decide to enforce or not.
Related to clients
Most Browsers do enforce it to prevent issues related to CSRF attacks.
Most Development tools don't care about it. Postman being dev tool will not give much importance to CORS header, you will need something else to test.
There are chrome extensions that can help you test CORS on your browser.