text:
Q: Detect an icon in a chip label - react jest testing I am working on a react/material UI app. Within one of my components, I create a bunch of Chips by cycling through some maps (which is where the index1, index2, and value below come from). When a Chip is clicked, then a StarRateIcon is added to the label to indicate which Chip was last clicked - the state stores the id of the most recently clicked Chip. If a Chip is clicked again, the StarRateIcon goes away again. The following code highlights the relevant parts of what I am doing:
import React from 'react';
import Chip from '@material-ui/core/Chip';
import StarRateIcon from '@material-ui/icons/StarRate';

export default function Example(){
    const [clickedKey, setClickedKey] = React.useState(null);

    return(
        ...
        <Chip
            data-testid={`chip-${index1}-${index2}`}
            label={
                <span>
                    {value}
                    {clickedKey === `chip-${index1}-${index2}` ? <StarRateIcon /> : null}
                </span>
            }
            onClick={() => {
                setClickedKey(filterKey !== `chip-${index1}-${index2}` ? `chip-${index1}-${index2}` : null
            }}
        />
        ...
    );
}

I then wish to test that when a given Chip is clicked, that the StarRateIcon is visible in that Chip. The project is using jest so I need to do so too.
So far, I have the following:
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import Example from '<path>/Example';

it('star icon is visible when chip is clicked', () {
    const { getByTestId } = render (
        <Example />
    );
    const chip = getByTestId('chip-0-0');
    fireEvent.click(chip);

    // TODO what next?
    // expect(chip).
});

but I can't then work out what to expect at the end. If I use
expect(chip).toHaveTextContent(`example ${<StarRateIcon />}`)

then it fails as the StarRateIcon is not included in the text content. This is how I would do it if there were no StarRateIcon to consider, and indeed it works for all the chips which have not been clicked and are not displaying the StarRateIcon.
I also tried
expect(chip).toBe(`example ${<StarRateIcon />}`)

but that also didn't work.
I've done a bit of hunting and playing around with some of the other functions available on expect but none of them seem to flag up the existence of the StarRateIcon.
I'm very new to front end development and testing - can someone point me towards an acceptable way to accomplish this test please?

A: Material ui icons have icon name as data-testid. This should work
expect(getByTestId('DeckSharpIcon')).toBeVisible();

<svg class="MuiSvgIcon-root MuiSvgIcon-fontSizeMedium css-1xkvp8t-MuiSvgIcon-root" focusable="false" aria-hidden="true" viewBox="0 0 24 24" data-testid="DeckSharpIcon"><path d="M22 9 12 2 2 9h9v13h2V9z"></path><path d="m4.14 12-1.96.37.82 4.37V22h2l.02-4H7v4h2v-6H4.9zm14.96 4H15v6h2v-4h1.98l.02 4h2v-5.26l.82-4.37-1.96-.37z"></path></svg>

if using FontAwesomeIcon:
<FontAwesomeIcon icon={faExclamationTriangle} data-testid="icon" />

expect(getByTestId('icon')).toHaveClass('svg-inline--fa fa-triangle-exclamation fa-3x');


text:
Q: How to make all methods from static class available in another static class in c# I would like add additional c# methods to a external static class that can't be modified. i.e create a wrapper class for convenience containing the methods of the external static class + my own static methods.
I first wanted to inherit my own class from the external static class but I discover that static classes are sealed and can't be inherited form.
What would be the best way to do this?
Thanks a lot for you help

A: Proxy the calls, per Llama's indication
public static class YourClass{

  public SomeType TheirMethod(..){
    return TheirClass.TheirMethod(...);
  }

...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting coefficients for explanatory variables not in the formula I have:
model6 = get_model(formula="log(Y_star)~X_1_star*X_3_star", df=df)
Model summary gives me:
Coefficients:
                    Estimate Std. Error t value Pr(>|t|)
(Intercept)       -1.049e+01  3.724e-01 -28.182  < 2e-16 ***
X_1_star           3.082e-08  7.517e-09   4.100 8.44e-05 ***
X_3_star           3.482e-07  8.708e-08   3.999 0.000122 ***
X_1_star:X_3_star -6.716e-15  7.822e-16  -8.587 1.22e-13 ***

Why is it giving me coefficients for X_1_star and X_3_star separately when they are not in the formula?
My formula is not Y = b_0 + b_1*X_1_star + b_2*X_3_star + b_3*X_1_star*X_3_star

A: According to ?formula

The * operator denotes factor crossing: a*b interpreted as a+b+a:b

Based on the comment, if we want only interaction, then use a different symbol

The terms themselves consist of variable and factor names separated by : operators. Such a term is interpreted as the interaction of all the variables and factors appearing in the term.


text:
Q: How to parse date in laravel? Below is the code inserted:
{{ Carbon\Carbon::parse('@'.$item->time)->format('d-m-Y H-i-s-e') }}

It is not parsing and giving some error.

A: {{ Carbon::createFromFormat('d-m-Y H-i-s-e', $item->time)->toDateTimeString(); }}

A: It's the same question I asked 2 months earlier and already I find the best solution here is a link: Show date in HTML using Laravel


text:
Q: GetReservation returning Viewership is restricted for the PNR I'm currently using the sabre web service TravelItineraryReadLLSRQ (version 2.2.0) and I can successfully retrieve all on the PNR data. Now I'm trying to implement GetReservation but I'm getting the error below.
Not finding any further detail from the dev sabre portal - has anybody seen this and know what the 'fix' is?
"Viewership is restricted for the PNR, caused by [Viewership is restricted for the PNR (Unsupported security check), code: 700102, severity: MODERATE]"
<GetReservationRS xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Errors xmlns="http://webservices.sabre.com/pnrbuilder/v1_18">
    <Error>
      700102
      <Message>Viewership is restricted for the PNR, caused by [Viewership is restricted for the PNR (Unsupported security check), code: 700102, severity: MODERATE]</Message>
      <Severity>MODERATE</Severity>
    </Error>
  </Errors>
</GetReservationRS>

A: You may want to try using "Stateful" since "Stateless" is only intended for airline customers. You can use Stateful together with a locator or without it, makes no difference.
You may also may want to be aware that the service can be called with the Full, Default and Simple View Names. Only Simple will return more updated data which you can obtain by using the required subject areas in the payload. Full and Default will ignore the subject areas you use.


text:
Q: Android while getting HTTP response to file how to know it wasn't fully loaded? I'm using this approach to store a big-sized response from server to parse it later (in AsyncTask):
final HttpClient client = new DefaultHttpClient(new BasicHttpParams());
final HttpGet mHttpGetRequest = new HttpGet(strUrl);
mHttpGetRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
FileOutputStream fos = null;
try {
    final HttpResponse response = client.execute(mHttpGetRequest);
    final StatusLine statusLine = response.getStatusLine();
    lastHttpErrorCode = statusLine.getStatusCode();
    lastHttpErrorMsg = statusLine.getReasonPhrase();
    if (lastHttpErrorCode == 200) {
        HttpEntity entity = response.getEntity();
        fos = new FileOutputStream(reponseFile);
        entity.writeTo(fos);
        entity.consumeContent();
        fos.flush();
    }
} catch (ClientProtocolException e) {
    e.printStackTrace();
    lastHttpErrorMsg = e.toString();
    return null;
}
catch (final ParseException e) {
    e.printStackTrace();
    lastHttpErrorMsg = e.toString();
    return null;
}
catch (final UnknownHostException e) {
    e.printStackTrace();
    lastHttpErrorMsg = e.toString();
    return null;
}
catch (IOException e) {
    e.printStackTrace();
    lastHttpErrorMsg = e.toString();
} finally{
    if (fos!=null)
        try{
            fos.close();
        } catch (IOException e){}
}

now how could I ensure the response was completely received and thus saved to file? Assume client's device lost Internet connection while the code was wring response to a file. So the app received only some part of real response and wrote it the file without any err/exception. Its just like stream is finished/closed and AsyncTask fired onPostExecute() cuz job is done - response written to the file. But the point is - response wasn't received completely. And I'm pretty sure it happens cuz I got parsing exceptions like "tag not closed", "unexpected end of file" etc. So I need to detect somehow this situation to prevent code from parsing partial response but can't see how. Since its not about file downloading I cant request its size. So can't know the response's size before receiving it.
 Is it possible to detect such situation at all and how to do it? Or has it has to raise IOException in such cases?

A: What if you try to get the stream and parse it?
InputStream inputStream = entity.getContent();
FileOutputStream output = new FileOutputStream(path);
String path = "file.txt";
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
    output.write(buffer, 0, len);
}

In this way you get the stream sequentially. I don't think there are toher ways to do this.
Try and let me know. :)

A: This seems weird since it should throws timeout response code if you are connecting and disconnected. But with your current case, what I think the best you can do is adding try-catch to the open file code, and if there is exception, bring a pop up says download file incomplete or something, remove that file and ask user to try again. (Sorry I don't have enough reputation to reply)

A: try to use onFinsh(); save to file


text:
Q: What's wrong with IE's modes and JQuery  $.tmpl()  rendering   I'm finding that JQuery's  $.tmpl() rendering differs greatly accross browsers. Predominantly IE versions. When the code below is placed in an update panel, its throws errors with the .appendTo("#divList"); method.
What's a fix for this - code example below
Mozilla: SUCCESS
IE Browser mode (IE9 Compat View), Document mode (IE9 standards): SUCCESS
IE Browser mode (IE9), Document mode (IE9 standards): SUCCESS
IE Browser mode (IE8), Document mode (IE9 standards): SUCCESS
IE Browser mode (IE7), Document mode (IE9 standards): SUCCESS
IE Browser mode (*), Document mode (IE8 standards): FAIL   (nothing rendered)
IE Browser mode (*), Document mode (IE7 standards): FAIL
IE Browser mode (*), Document mode (Quirks mode): FAIL

 <meta http-equiv="X-UA-Compatible" content="IE=8;FF=3;OtherUA=4" />

<form id="form1" runat="server">

            <input type="text" id="txDibaba" />

</form>

Does it make sense to force IE9 mode?

A: I'm still not sure what you're asking but your code is busted in this case, not IE.
var a = [
    { actor: 'hanks', film: 'yo mama' },
    { actor: 'banks', film: 'men can swim' },
    { actor: 'will', film: 'men can swim' },
    { actor: 'jlo', film: 'ooogh aah' },
    { actor: 'jlo', film: 'bright yellow shadows' }, //<-- get rid of that ,
];


text:
Q: UnsatisifiedLinkError with ojdbc14.jar I am trying to run some JUnit tests that connect to an Oracle database and whether a connection attempt is made. The following error is thrown:

oracle/jdbc/driver/T2CConnection.t2cGetCharSet([CI[CI[CII[SLoracle/jdbc/driver/GetCharSetError;)S
at oracle.jdbc.driver.T2CConnection.getCharSetIds(T2CConnection.java:2801)
at oracle.jdbc.driver.T2CConnection.logon(T2CConnection.java:300)
at oracle.jdbc.driver.PhysicalConnection.(PhysicalConnection.java:344)
at oracle.jdbc.driver.T2CConnection.(T2CConnection.java:136)
at oracle.jdbc.driver.T2CDriverExtension.getConnection(T2CDriverExtension.java:79)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:545)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:194)
at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPhysicalConnection(OracleConnectionPoolDataSource.java:109)
at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPooledConnection(OracleConnectionPoolDataSource.java:77)
at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPooledConnection(OracleConnectionPoolDataSource.java:59)
at oracle.jdbc.pool.OracleConnectionCacheImpl.getNewPoolOrXAConnection(OracleConnectionCacheImpl.java:414)
at oracle.jdbc.pool.OracleConnectionCacheImpl.setMinLimit(OracleConnectionCacheImpl.java:739)

Has anyone had this error before?
I never used to get this error until recently. However, this error does not occur on a colleague's computer running the same JUnit and using the same ojbdc14.jar file. So some sort of environmental issue should be causing this.
Can you help?

A: I got the same error in Webesphere environment when using oci dirver, it was due to version mismatch of jar ojdbc14.jar, jar from ORACLE_HOME/jdbc/lib and the the jar  in the classpath of JDBCProvider defined in admin console were diffrent.

A: Do you have the Oracle client installed?  I think you are using the "oci" instead of pure java drivers which would require the client install to pick up the native shared libs.

A: Make sure you have -Djava.library.path=<your-oracle-home>\bin as a parameter to the runtime

A: It seems to me that you are intending to use JDBC Type 2 driver (thick client) that require Oracle client library to be installed on your box. Or switch to thin driver if possible by simply changing the URL.


text:
Q: Date time format doesn't match when using strptime I have a string variable start_d that I need to convert to date and add 6 days to it. I've done:
end_d = datetime.datetime.strptime(start_d,'$d/%m/%Y')+datetime.timedelta(days=6)

But for some reason I get an error: ValueError: time data '26/08/2019' does not match format '$d/%m/%Y'
Not sure what I did wrong here.


text:
Q: Bad SQLite query performance with outer joins I have an SQLite database as part of an iOS app which works fine for the most part but certain small changes to a query can result in it taking 1000x longer to complete. Here's the 2 tables I have involved:
create table "journey_item" ("id" SERIAL NOT NULL PRIMARY KEY,
"position" INTEGER NOT NULL,
"last_update" BIGINT NOT NULL,
"rank" DOUBLE PRECISION NOT NULL,
"skipped" BOOLEAN NOT NULL,
"item_id" INTEGER NOT NULL,
"journey_id" INTEGER NOT NULL);

create table "content_items" ("id" SERIAL NOT NULL PRIMARY KEY,
"full_id" VARCHAR(32) NOT NULL,
"title" VARCHAR(508),
"timestamp" BIGINT NOT NULL,
"item_size" INTEGER NOT NULL,
"http_link" VARCHAR(254),
"local_url" VARCHAR(254),
"creator_id" INTEGER NOT NULL,
"from_id" INTEGER,"location_id" INTEGER);

Tables have indexes on primary and foreign keys.
And here are 2 queries which give a good example of my problem
SELECT * FROM content_items ci
INNER JOIN journey_item ji ON ji.item_id = ci.id WHERE ji.journey_id = 1

SELECT * FROM content_items ci
LEFT OUTER JOIN journey_item ji ON ji.item_id = ci.id WHERE ji.journey_id = 1

The first query takes 167 ms to complete while the second takes 3.5 minutes and I don't know why the outer join would make such a huge difference.
Edit:
Without the WHERE part the second query only takes 267 ms

A: The two queries should have the same result set (the where clause turns the left join into an inner join)`.  However, SQLite probably doesn't recognize this.
If you have an index on journey_item(journey_id, item_id), then this would be used for the inner join version.  However, the second version is probably scanning the first table for the join.  An index on journey_item(item_id) would help, but probably still not match the performance of the first query.


text:
Q: Classifying quadratic forms and their corresponding symmetrical matrices In my textbook it is written that a quadratic form $$Q(x) = x^{T}Ax$$is positive definite if and only if the eigenvalues of the symmetrical matrix A are all positive, negative definite if and only if the eigenvalues are all negative and indefintie if the eigenvalues are both negative and positive.
Is there any connection to the eigenvalues of the matrix A if the quadratic form is positive semidefinite or negative semidefinite?


text:
Q: why do I get sample is too sparse to find TD using beanplot? I am trying to draw a beanplot with the following code:
library(beanplot)

beanplot(df, col="#cccccc", names="plot-1", yaxt="n", overallline="median", ll=0.00001)

I get the following error:
Error in bw.SJ(x, method = "dpi") : sample is too sparse to find TD

dput(df) data here: https://pastebin.com/fyCSmX6t


text:
Q: MySQL doesn't update records from two databases I am updating the records of one table from one db into another.
Now when I run the query it is working but it shows that zero record have been updated.
However, there are more than 2000 records which are matched. I want to update the table limeappl_store_test:
UPDATE
  limeappl_store_test.oc_product_option_value,
  limeappl_storesync.sys_product_import
SET
  limeappl_store_test.oc_product_option_value.quantity = limeappl_storesync.sys_product_import.qty
WHERE
  limeappl_store_test.oc_product_option_value.ob_sku = limeappl_storesync.sys_product_import.item

A: You need to join
UPDATE limeappl_store_test.oc_product_option_value
JOIN limeappl_storesync.sys_product_import
  ON limeappl_store_test.oc_product_option_value.ob_sku = limeappl_storesync.sys_product_import.item
SET limeappl_store_test.oc_product_option_value.quantity = limeappl_storesync.sys_product_import.qty


text:
Q: Number of pairs with product less than a given number. How can we find out the number of positive integer pairs with product less than a specific value. Can someone help me with this.

A: I know one way. Let $a$ and $b$ be two positive numbers. Now let $max(a,b)=b$ so $ab<b^2$. Let $b^2=c$. Now $ab<c$.
Suppose we got a positive number $A$ and we wish two find two positive numbers $\alpha$ and $\beta$ s.t. $\alpha \beta < A$. Then from the first paragraph it is clear that  the one sufficient but not necessary condition is that
max($\alpha$,$\beta$)<$\sqrt{A}$.
Let me again clarify that max($\alpha$,$\beta$)<$\sqrt{A}$ is not a necessary condition, but it is a sufficient condition.


text:
Q: getting null values while iterating though list EntityMapper<Datahub.Test_Consumer, Models.ConsumerBio> entObject = new EntityMapper<Datahub.Test_Consumer, Models.ConsumerBio>();
EntityMapper<Datahub.Test_Address, Models.ConsumerAddress> entObjectAdd = new EntityMapper<Datahub.Test_Address, Models.ConsumerAddress>();
EntityMapper<Datahub.Test_CardDetails, Models.ConsumerCardDetails> entObjectcard = new EntityMapper<Datahub.Test_CardDetails, Models.ConsumerCardDetails>();

List<Models.ConsumerBio> lstModConsumer = new List<Models.ConsumerBio>();
List<Models.ConsumerAddress> lstobjConAdd = new List<Models.ConsumerAddress>();
List<Models.ConsumerCardDetails> lstobjConcard = new List<Models.ConsumerCardDetails>();

List<Datahub.Test_Consumer> lstDBConsumer = Datahub.DataLayer.GetAllConsumerList();
//  Models.ConsumerFamilyMember objConFMembers = new Models.ConsumerFamilyMember();

foreach (var item in lstDBConsumer)
{
    foreach (var itemadd in item.Test_Address)
    {
        lstobjConAdd.Add(entObjectAdd.translate(itemadd));
    }

    foreach (var itemcard in item.Test_CardDetails)
    {
        lstobjConcard.Add(entObjectcard.translate(itemcard));
    }

    lstModConsumer.Add(entObject.translate(item));
}

So, in above lstDBConsumer object I am getting all db values , but while iterating and assigning values to  lstModConsumer , I am getting all null values except my DOB filed. PLease tell me solution for this?

A: If you are accessing child properties outside of your database context (which it appears you are) then you need to explicitly include them at the time of selection from the database.
Using an easy example from MS to show an include:
var blogs = new List<Blogs>();
var posts = new List<Posts>();
using (var context = new BloggingContext())
{
    blogs = context.Blogs.Include(blog => blog.Posts).ToList();
}
foreach(var p in blogs.Posts)
{
  posts.add(p);
}

IF however you are making assignment while still in the context of the DB connection, you can simply call the property. Enumeration happens automatically in that case as it still has context to the database to retrieve the properties.
var posts = new List<Posts>();
using (var context = new BloggingContext())
{
    var blogs = context.Blogs.Include(blog => blog.Posts).ToList();
    foreach(var p in blogs.Posts)
    {
       posts.add(p);
    }
}

Entity Framework does not automatically load navigation properties (ie you wont automatically get the child objects of your object) due to a concept called Lazy Loading which is enabled by default.
Imaging you have a massive relational database and it automatically pulled all related objects when you did a simple query. Your very simple query could have huge implications if it auto loaded all relations. Could be a potential nightmare. Now there is a way to turn off lazy loading by that is out of the context of this question. Please refer to the following link for some more light reading and more detailed explanation: https://learn.microsoft.com/en-us/ef/core/querying/related-data
In kind of a real world example to model, Imagine you had an interaction with two friends, John and Jane.
You talk with John on the phone and ask him what his plans are in the morning. He is attending a meeting at 9:30.
You then hangup and call Jane and tell her about John's plans for the day. You tell Jane about the 9:30 meeting and then she asks "Who all will be in the meeting?"
You have no clue because you didn't asks John when you talked to him. You KNOW that meetings have attendees but you have no idea who they are because you didn't ask John when you talked to him. You also know that meetings have agendas, locations, call in numbers, ect. It would be pretty inefficient to get all the explicit details of the meeting if you did not care about every detail. John would probably stop answering your phone calls if you operated this way every time you interacted with him.
BUT in a different scenario you had asked John who will be there (aka included the properties then you would have the answer) because you know that Jane will want to know when you talk to her later that day.
OR
If you were on a conference call with John and Jane and the question was asked (still within the database context when we wanted to find additional info) then the info would be readily available because John is on the call.
Hope this makes sense.


text:
Q: How to identify Shopify App page with no template Throughout my liquid files, I see lots of conditional statements based on the current template, like this:
{% if template contains "product" %}
  (do something)
{% endif %}

But I have an app installed that created it's own page:
MyStoreName.com/apps/store-locator

- which uses no template.
I need to add some code to my theme.liquid file which only executes on this app page.  Is there any other way to identify the page?

A: Does the page have a title that Shopify can spit out using {{ page_title }}? If so, you should be able to do
{% if page_title == 'store-locator' %}
    {% code goes here %}
{% endif %}


text:
Q: Can I recursively apply transformations to a Spark dataframe in scala? Noodling around with Spark, using union to build up a suitably large test dataset. This works OK:

val df = spark.read.json("/opt/spark/examples/src/main/resources/people.json")
df.union(df).union(df).count()

But I'd like to do something like this:

val df = spark.read.json("/opt/spark/examples/src/main/resources/people.json")
for (a <- 1 until 10){
  df = df.union(df)
}

that barfs with error

<console>:27: error: reassignment to val
         df = df.union(df)
            ^

I know this technique would work using python, but this is my first time using scala so I'm unsure of the syntax.
How can I recursively union a dataframe with itself n times?

A: If you use val on the dataset it becomes an immutable variable. That means you can't do any reassignments. If you change your definition to var df your code should work.
A functional approach without mutable data is:
val df = List(1,2,3,4,5).toDF
val bigDf = ( for (a <- 1 until 10) yield df ) reduce (_ union _)

The for loop will create a IndexedSeq of the specified length containing your DataFrame and the reduce function will take the first DataFrame union it with the second and will start again using the result.
Even shorter without the for loop:
val df = List(1,2,3,4,5).toDF
val bigDf = 1 until 10 map (_ => df) reduce (_ union _)

A: You could also do this with tail recursion using an arbitrary range:
@tailrec
def bigUnion(rng: Range, df: DataFrame): DataFrame = {
  if (rng.isEmpty) df
  else bigUnion(rng.tail, df.union(df))
}
val resultingBigDF = bigUnion(1.to(10), myDataFrame)

Please note this is untested code based on a similar things I had done.


text:
Q: How to allow sorting in DataGridView? I have data from base, using Entity Framework. I don't use data binding source. I use this:
var caly = from m in stan.magazyn
                       from g in stan.gdzie
                       from p in stan.pracownik
                       where m.Gdzie_Jest == g.ID_Miasta
                       where m.Kto_Wprowadzil == p.ID_Pracownika
                       orderby m.Marka
                       select new { m.ID, m.Marka, m.Model, m.IMEI, m.Kolor, m.Od_Kogo, Sklep = g.Nazwa, m.Data_Wprowadzenia, m.Cena_Kupna, Dodał = p.login, m.Info };
            dataGridView1.DataSource = caly.ToList();

If I click in header in datagridview, I want that data sort. But don't work. What I must do? I'm trayed using linq, but dont work, its the same.

A: You need to add a sort Method to the Datagrid and set an expression for your sort.  And then rebind the datagrid after your sort expression is set and the data should be sorted.  You can setup your datagrid to sort by the value for each column, and call this method when you want to sort again.
Do the following:
Create an event handler for the grid's SortCommand event. In the method:
1. Get the sort key (the value you set in the Sort expression) from the SortExpression property of the DataGridSortCommandEventArgs argument.
2. Sort the data.
3. Rebind the data from the data source.
Example:
private void dataGridView1_SortCommand(object source,
System.Web.UI.WebControls.dataGridView1SortCommandEventArgs e)
{
   dataGridView1.Sort = e.SortExpression;
   dataGridView1.DataBind();
}


text:
Q: Is a Chroot Jail for SSH *and* SFTP? I'm trying to setup a chroot jail, but I'm not sure how to make this work in SSH and SFTP. A quick question, will something like this work for both SSH and SFTP or just SSH? If it doesn't work for both, how can I setup a chroot jail (or an alternative) to do so?

A: If SSH does a chroot, then it will be effective for all processes started by SSH.


text:
Q: Android FacebookSdk Login Button: there's no button label I am facing troubles adding a FacebookLogin button in my layout.
It has a strange behaviour: as I add it, I can see the blue button, the logo, but no text is shown on the button.

Emulator screenshot - same behaviour on a Nexus 5 running Android 5.0.1
This is the code:
<com.facebook.login.widget.LoginButton
                android:id="@+id/facebook_sign_in_button"
                android:layout_width="match_parent"
                android:layout_height="64dp"
                android:layout_marginTop="16dp"
                android:text="@string/sign_in_facebook"
                android:width="0dp"
                android:height="0dp"/>

Modifying width/height/etc doesn't seem to change anything. Also tried to copy-paste Facebook's example on their docs - no luck.
Here's the activity theme
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>

    <item name="colorAccent">@color/primary</item>

    <item name="android:textColor">@color/text_primary</item>
    <item name="android:textColorPrimary">@color/text_primary</item>

    <item name="android:textColorHint">@color/login_hint</item>
    <item name="android:maxLines">1</item>
    <item name="android:singleLine">true</item>

    <item name="colorControlNormal">@color/primary</item>
    <item name="colorControlActivated">@color/primary</item>
    <item name="colorControlHighlight">@color/primary_dark</item>

    <item name="colorButtonNormal">@color/primary</item>

    <item name="android:textSize">@dimen/abc_text_size_medium_material</item>
</style>

(@color/primary is orange, @color/text is white)
I am using Facebook Sdk version 4.5.0.

A: Simply do this:
<com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         android:layout_marginTop="16dp"
        />


text:
Q: How to execute an order_by after using distinct? I would like to sort my result after I have grabbed unique results based on two fields. The problem I'm having is that I cannot use two order_by in Django. Django clears the previous order_by() whenever you use this function.

Each order_by() call will clear any previous ordering.

Example of models:
class Product(models.Model):
    price = models.FloatField()
    name = models.CharField(max_length=100)
    group = models.CharField(max_length=100)

I want to get the product which is in the same group and have the lowest. Then, I'd like to sort them by price. Something like this:
Product.objects.order_by('group','price').distinct('group').order_by('price')
Product.objects.order_by('group','price').distinct('group').order_by('-price')

The thing is that if just use in the first order by I get different products.
--
EDIT
Example of table:
id | name | group | price
0  | aaa  | aaa   | 10.0
1  | aaa  | aaa   | 1.0
2  | aaa  | aaa   | 2.0
3  | aaa  | aaa   | 1.0
4  | bbb  | bbb   | 2.0
5  | bbb  | bbb   | 2.1
6  | bbb  | bbb   | 10.0

Sorting by price:
1  | aaa  | aaa  | 1.0
4  | bbb  | bbb  | 2.0

Sorting by -price:
4  | bbb  | bbb  | 2.0
1  | aaa  | aaa  | 1.0

The problem I have is that when I sort using order_by the products returned are different.
In sql statement would be something like this:
SELECT *
FROM product
WHERE id IN (
  SELECT DISTINCT ON
  (group) id
  FROM product
  ORDER BY group ASC, price ASC
)
ORDER BY price DESC

I'm using PostgreSQL

A: Ok, here is what I did:
products = Product.objects.order_by('group','price').distinct('group')
result = Product.objects.filter(id__in=products).order_by('-price')

I don't think it's the most efficient way, but it is working...

A: I had the same problem and found another solution. After the first request to DB with sorted_by followed by distinct you can:
import operator

products = Product.objects.order_by('group','price').distinct('group')
result = sorted(products, key=operator.attrgetter('price'), reverse=True)

This solution is better because you are not making the second request to the database.

A: I like Alexander's idea of using sorted.  I put the sorted function into a subclass of models.QuerySet and then set my ProductManager accordingly.  This allows you to chain the sorted method onto your queryset.
Gotcha: This returns a list rather than a queryset, so you cannot use any queryset methods after sorting.
Related model field sort:  You can sort by a related model field by passing a key that spans the lookup with dot operator (key='price.other')
manager.py
class ProductQuerySet(models.QuerySet):
    def sorted(self, key, reverse=False):
        """ Returns a list (rather than queryset) of Djano model instances """
        return sorted(self, key=operator.attrgetter(key), reverse=reverse)

    def current(self):
        return self.order_by('group', 'price').distinct('group')

class ProductManagerBase(models.Manager):
   pass

ProductManager = ProductManagerBase.from_queryset(ProductQuerySet)

models.py
...
objects = ProductManager()

**query
qs = (Product
     .current()
     .sorted('price', reverse=True))


text:
Q: Erlang: Sorting arrays I am new with functional programming languages and I can't understand why in Erlang, if I take a BubbleSort, QuickSort or any other sorting algorithms and try to sort [8] it will return "\b". Or [12,10,11] will return "\n\v\f". Can someone  please help me?

A: It's because they mean the same thing: 8 in ASCII is "\b". See the "lists!" section here.

Erlang will print lists of numbers as numbers only when at least one
  of them could not also represent a letter!

So the erlang shell is trying to help you out by making its best guess about what you want to see. Occasionally, you get a string when you meant to see a list of integers which can be confusing. The following illustrates this point:
1> [104, 101, 108, 108, 111].
"hello"
2> [104, 101, 108, 108, 111, -1].
[104,101,108,108,111,-1]
3> [104, 101, 108, 108, 111] =:= "hello".
true

A: This is due to the fact that Erlang represents strings as lists of numbers. When printing such a list, the Erlang output function will look to see whether your list contains all numbers that correspond to ASCII character values. If so, then it prints your list as a string.
It sounds like your code is working correctly. Try sorting [12345, 29348, 978] with your existing code to see what happens.
See the reference manual section 2.11 String for information about this.

A: The main reason for this is because Erlang basically takes these as the corresponding ASCII values for the characters which are being printed.
I would like to post a piece of code which sorts in erlang:
    -module(solution).
    -import(lists,[delete/2,max/1]).
    -compile(export_all).
    selection_sort([],Sort)-> Sort;
    selection_sort(Ar,Sort)->
        M=max(Ar),
        Ad=delete(M,Ar),
        selection_sort(Ad,[M|Sort]).
    print_array([])->ok;
    print_array([H|T])->
        io:format("~p~n",[H]),
        print_array(T).

   main()->
        Ans=selection_sort([1,5,7,8,4,10],[]),
        print_array(Ans).

Hope THE Above code can solve your problem


text:
Q: StageWebViewDisk Breaks the File Upload on iPad (iOS?) I'm using Adobe Air for iPad/iPhone application.
I'm also using StageWebViewBridge (https://github.com/paleozogt/StageWebViewBridge) as the main web content displaying container.
My application works well for the Desktop version, but the StageWebViewBridge's StageWebViewDisk breaks HTML File Uploading feature:
<input id="user_avatar" name="user[avatar]" style="width:100%" type="file" />

i.e., whenever a file is browsed and selected from either Take Photo or Video or Choose Existing from the real iPad device, the above user_avatar input does NOT get updated at all.
I believe some paths are messed up by StageWebViewDisk.initialize(stage).
You can find the full source of StageWebViewDisk here:
https://github.com/paleozogt/StageWebViewBridge/blob/master/StageWebViewBridge/src/es/xperiments/media/StageWebViewDisk.as
And the following code snippet is very suspicious:
case isIPHONE :
    /* new iOS 5.0 Data Storage Guidelines
     * https://developer.apple.com/icloud/documentation/data-storage/
     * https://developer.apple.com/library/ios/#qa/qa1719/_index.html
     */
    _appCacheFile = new File(File.applicationDirectory.nativePath +"/\.\./Library/Caches");

    _applicationCacheDirectory = new File( _appCacheFile.nativePath ).url;
    _applicationRootPath = _applicationCacheDirectory + '/' + getWorkingDir();
    _applicationSourcesDirectory = new File( new File( "app:/" + _document_root ).nativePath ).url;
    _appDocsDirectory = File.documentsDirectory.url;

    /* new iOS 5.0 Data Storage Guidelines
     * https://developer.apple.com/icloud/documentation/data-storage/
     * https://developer.apple.com/library/ios/#qa/qa1719/_index.html
     */
    _applicationTempDir = new File(File.applicationDirectory.nativePath +"/\.\./tmp");

    // To acomplish the Apple  Data Storage Guidelines Rules delete our TMP files dir at exit
    NativeApplication.nativeApplication.addEventListener(Event.EXITING, deleteTempFolder,false,0,true );
    NativeApplication.nativeApplication.addEventListener(Event.DEACTIVATE, deleteTempFolder, false, 0, true);

    break;

I debugged a lot, and I finally found out that StageWebViewDisk.initialize(stage) is causing  issue.
The proof is that, when I don't use StageWebViewDisk.initialize(stage), instead, directly assign the stage to StageWebViewBridge._view.stage, it works very well.
I'm not familiar with the iOS app/cache directories.
Please advise me.

A: I finally figured it out:
_applicationTempDir = new File(File.applicationDirectory.nativePath +"/\.\./SWVBTmp");
// It seems "tmp" is being used by the iOS system (such as the html file upload), so we changed to "SWVBTmp";


text:
Q: AWS SNS not sending Subscription Confirmation I have setup AWS SNS setup with a topic say 'A'. I'm doing a subscribe to this SNS topic using Http (tried both manually using AWS console online and using Java Code). All I get is 'pending confirmation' in both cases. However SNS does not send the initial 'SubscriptionConfirmation' to the provided Url.
Note that my endpoint is ready to receive http POST notification. When I manually do a POST from my side I see my servlet processing those Json I send. For some reason I receive nothing from AWS SNS.
Note that my http end point that I used for subscribe is public facing so SNS should have no issue reaching it.
Any inputs is appreciated.
Here is my subscribe function.
public String subscribe(String arn,String url) {

    if(arn == null || arn.isEmpty())
        arn = topicArn;
    SubscribeRequest subRequest = new SubscribeRequest(arn,"http",url);
    SubscribeResult  result = snsClient.subscribe(subRequest);
    //get request id for SubscribeRequest from SNS metadata
    if(result != null){
        LOGGER.info("SubscribeResult - " + result.toString());
    }
    LOGGER.info("SubscribeRequest - " + snsClient.getCachedResponseMetadata(subRequest));
    return result.toString();
}

A: You are always going to get "pending confirmation" as the response for the subscriptionArn.   The confirmation process is asynchronously as a separate process.  To make this even more confusing if you call to get a list of current subscriptions they will show an slightly different subscriptionArn of "PendingConfirmation" so you can not even match it later.
As far as being able to connect, I would try hitting an end point outside of AWS first.   By default most AWS elements are very locked down and can not even connect to each other, so there is likely a security setting somewhere that needs to be changed to let SNS connect to your EC2.  Which would be why you can connect to the EC2 outside of AWS, but your SNS service can not.
Also check to make sure the SNS and EC2 you are using are in the same region.   It is a common cause of connection issues.
If you are using a host name to connect I would try using the direct IP to see if it gets through.

A: To troubleshoot, you should turn on the "Delivery status" reports in topic actions - https://docs.aws.amazon.com/sns/latest/dg/sns-msg-status.html. Then you will see why the confirmation message failed to be sent from AWS side.
On your EC2 instance side, on network level you must make sure that the port you are listening on is open from outside. There are several things: both making sure the port is open in firewall (Security groups settings), and making sure that the IP is reachable (i.e., make sure your VPC where the machine is located is publicly visible).

A: I faced the same issue, the region was the problem.
Make sure the SNS, CloudWatch and EC2 are in the same region.

A: For me disabling encryption on the topic allowed the emails to finally be delivered, albeit to the spam folder.


text:
Q: Fake a TTY on Windows Problem
My team would like to automate the process of logging people out of an application (IBM FileNet) using the security utility provided - sec_tool.
Most sec_tool commands can simply be piped in, making it easy to write a script with those commands. However, the logoff command does not.
Manual Process:
C:\Windows\system32>sec_tool

Type '?' for help

<SEC_tool>logoff user=test.user

Piping Attempt:
C:\Windows\system32>echo logoff user=test.user | sec_tool
  1 logoff user=test.user
Not a tty.

I am trying to find a way to automate this process by faking a tty. This manual task is taking time out of our daily duties and we would benefit greatly from scripting this process.


text:
Q: c# equivalent for c++ vector or deque I am almost certain this should be a duplicate but I searched for some time and could not find the answer. What should I use in C# to replace C++ vector and deque efficiently. That is I need a structure that supports direct indexing effieciently and also supports delete from one or both ends(depending on vector or deque case) again in an efficient manner.
In java I usually use ArrayList at least for vector but for C# I found this source that states:
ArrayList resizes dynamically. As elements are added, it grows in capacity to accommodate them. It is most often used in older C# programs.. So what is the new way to do this? And again what do I do for the deque case?

A: There's no built-in Deque container, but there are several implementations available.
Here's a good one from Stephen Cleary. This provides O(1) operations to index and also to insert at the beginning and append at the end.
The C# equivalent to Vector is List<T>. Indexed access is O(1), but insertion or removal is O(N) (other than Inserting at the end, which is O(1)).

A: Consider System.Collections.Generic.List and other from System.Collection.Generic they serve the same purpose as their C++ equivalents.
Additionally, there might be more containers for you. Look here.

A: For a C# vector, a good candidate is System.Collection.Generic.List as others mentioned.
The closest to the deque in C++ would be System.Collection.Generic.LinkedList which is a doubly linked list.

A: Though you cannot do an index operation, linkedlist is probably one of the closest in implementing dequeue first and dequeue last in constant time.
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.removefirst?view=netframework-4.8

A: Deque is not in C#, but we can archive functionality by Vector and List, Below is a sample program to archive Deque by List.
using System;
using System.Collections.Generic;

public class GFG{

// Function to generate the array by
// inserting array elements one by one
// followed by reversing the array
static void generateArray(int []arr, int n)
{

    // Doubly ended Queue
    List<int> ans = new List<int>();

    // Start adding functionality at both end
    // Iterate over the array
    // Even no at the front and odd no at the rear
    for(int i = 0; i < n; i++)
    {

        // Push array elements
        // alternately to the front
        // and back
        if (arr[i]%2==0)
            ans.Insert(0,arr[i]);
        else
            ans.Add(arr[i]);
    }

    printDeque(ans);
    // Output 8 6 4 2 6 5 1 3

    // Start removing functionality at both end
    // Let i want to remove first(8) and last(3) element from Deque

    ans.RemoveAt(0);
    printDeque(ans);
    // Output 6 4 2 6 5 1 3
    ans.RemoveAt(ans.Count-1);
    printDeque(ans);
    // Output 6 4 2 6 5 1

}
static void printDeque(List<int> q){
    // Print the elements
    // of the Deque
    foreach(int x in q)
    {
        Console.Write(x + " ");
    }
    Console.WriteLine();
}

// Driver Code
public static void Main(String[] args)
{

    int []arr = {5, 6, 1, 2, 3, 4,6, 8 };
    int n = arr.Length;
    generateArray(arr, n);
}
}

A: For me, these simple extension methods were enough.
using System.Linq;
using System.Collections.Generic;
-----
-----

        public static T consume<T>(this List<T> list, int index) {
            if (list.Count < index) return default(T);
            var item = list[index];
            list.RemoveAt(index);
            return item;
        }
        public static T pop<T>(this List<T> list) {
            return list.consume(list.Count - 1);
        }
        public static T dequeue<T>(this List<T> list) {
            return list.consume(0);
        }
        public static void push<T>(this List<T> list, T item) {
            list.Add(item);
        }
        public static void enqueue<T>(this List<T> list, T item) {
            list.Add(item);
        }


text:
Q: Setting Icon in tabLayout throws nullpointer exception I'm creating a simple project like instagram, it has 3 tabs in main activity. I want to add icons with text in tablayout tabs, but it throws exception.
My MainActivity
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;

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

    viewPager = (ViewPager) findViewById(R.id.viewPager);
    tabLayout = (TabLayout) findViewById(R.id.tabLayout);
    tabLayout.setupWithViewPager(viewPager);

    TabLayout.Tab tab = tabLayout.getTabAt(0);

    tab.setIcon(new IconicsDrawable(this).icon(FontAwesome.Icon.faw_home));

    viewPager.setAdapter(new CustomAdapter(getSupportFragmentManager(), getApplicationContext()));

}

private class CustomAdapter extends FragmentPagerAdapter {
    private String items[] = {"Home", "Upload", "Profile"};

    public CustomAdapter(FragmentManager supportFragmentManager, Context applicationContext) {
        super(supportFragmentManager);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new fragment1();
            case 1:
                return new fragment2();
            case 2:
                return new fragment3();
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return items.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return items[position];
    }
}
  }

This Code Throws nullpointer exception what should i do ?
Exception Text

09-29 14:33:53.004 29528-29528/com.example.eyepatch.shutter
  E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.example.eyepatch.shutter, PID: 29528
  java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.eyepatch.shutter/com.example.eyepatch.shutter.MainActivity}:
  java.lang.NullPointerException: Attempt to invoke virtual method
  'android.support.design.widget.TabLayout$Tab
  android.support.design.widget.TabLayout$Tab.setIcon(android.graphics.drawable.Drawable)'
  on a null object reference
  at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
  at android.app.ActivityThread.access$900(ActivityThread.java:157)
  at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
  at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:148)
  at android.app.ActivityThread.main(ActivityThread.java:5530)
  at java.lang.reflect.Method.invoke(Native Method)
  at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:733)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:623)
  Caused by: java.lang.NullPointerException: Attempt to invoke virtual
  method 'android.support.design.widget.TabLayout$Tab
  android.support.design.widget.TabLayout$Tab.setIcon(android.graphics.drawable.Drawable)'
  on a null object reference
  at
  com.example.eyepatch.shutter.MainActivity.onCreate(MainActivity.java:33)
  at android.app.Activity.performCreate(Activity.java:6272)
  at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
  at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2387)
  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
  at android.app.ActivityThread.access$900(ActivityThread.java:157)
  at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
  at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:148)
  at android.app.ActivityThread.main(ActivityThread.java:5530)
  at java.lang.reflect.Method.invoke(Native Method)
  at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:733)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:623)

A: You are supposed to first set the adapter to viewpager
Re-arrange the following lines:
tabLayout.setupWithViewPager(viewPager);
TabLayout.Tab tab = tabLayout.getTabAt(0);
tab.setIcon(new IconicsDrawable(this).icon(FontAwesome.Icon.faw_home));
viewPager.setAdapter(new CustomAdapter(getSupportFragmentManager(), getApplicationContext()));

as given below:
viewPager.setAdapter(new CustomAdapter(getSupportFragmentManager(), getApplicationContext()));
tabLayout.setupWithViewPager(viewPager);
TabLayout.Tab tab = tabLayout.getTabAt(0);
tab.setIcon(new IconicsDrawable(this).icon(FontAwesome.Icon.faw_home));

A: Checkout this link. It helped me a lot and i think this is what you need:

Android Material Design working with Tabs

https://www.androidhive.info/2015/09/android-material-design-working-with-tabs/


text:
Q: How to read file line by line and get specific chars or ints? I have the following input file:

3(3,3)
1(5,4)
2(7,7)
V
H

And I have the following code to print everything in it:
      char const * const fileName = argv[1]; /* should check that argc > 1 */
      FILE *file = fopen(fileName, "r"); /* should check the result */
      char line[256];

      while (fgets(line, sizeof(line), file)) {
         printf("%s", line);
      }

      fclose(file);

But I want to only retrieve the char or the int from each line and not the brackets. How can I write something to do that?

A: Just The 1st Character
If you really just want the first character, then *line will provide you with the first character from each line. It is equivalent to line[0] and you can use either interchangeably. A short example would be:
#include <stdio.h>

#define MAXC 1024   /* if you need a constant, #define one (or more) */

int main (int argc, char **argv) {

    char buf[MAXC];
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    while (fgets (buf, MAXC, fp))
        printf ("'%c'\n", *buf);

    if (fp != stdin)   /* close file if not stdin */
        fclose (fp);

Example Use/Output
$ ./bin/fgets_sscanf_first dat/multivals.txt
'3'
'1'
'2'
'V'
'H'

You can save and then test whether the first character is a digit with isdigit(*line) (or as above isdigit(*buf)). With a single digit, you can subtract '0' to get the numeric value. See ASCII Table
Separating All Values
You can use sscanf to separate one or all values in the line by attempting to parse all 3-values from the line and then checking the return to know whether you had a line with parenthesis (return of 3) or a single character (return of 1). You can use a format string of " %c(%d,%d" (the space before "%c" ensures leading whitespace is ignored). You can either use if/else or a simple switch statement to handle the different cases, e.g.
#include <stdio.h>

#define MAXC 1024   /* if you need a constant, #define one (or more) */

int main (int argc, char **argv) {

    char buf[MAXC];
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    while (fgets (buf, MAXC, fp)) {
        char c;
        int v1, v2;
        switch (sscanf (buf, " %c(%d,%d", &c, &v1, &v2)) {
            case 1 : printf ("single char/digit: '%c'\n", c);
                    break;
            case 3 : printf ("all values: %c  %d  %d\n", c, v1, v2);
                    break;
            default : fputs ("invalid line format\n", stderr);
        }
    }
    if (fp != stdin)   /* close file if not stdin */
        fclose (fp);
}

Example Use/Output
$ ./bin/fgets_sscanf_multival dat/multivals.txt
all values: 3  3  3
all values: 1  5  4
all values: 2  7  7
single char/digit: 'V'
single char/digit: 'H'

There are many, many ways to do this, and this is just one. Look over all your answers and let me know if you have further questions.

A: You just want to check on every character and number and accept only the chars and number:
const char *fileName = "C:\\file.txt";
FILE *file = fopen(fileName, "r");
int c = 0;
while ((c = fgetc(file)) != EOF) {
    if (isdigit(c) || isalpha(c) || c == '\n')
        printf("%c", c);
}
fclose(file);

The result:

A:
I want to only retrieve the char or the int from each line and not the brackets. How can I write something to do that?

After reading the line  of input into the string at line[], try parsing it various ways.  Use "%n" to record the offset of scanning and detect if scan completed.
This "%n" technique is useful to know that 1(5,4) included a trailing ) and ended there.
int index, x, y;
int n = 0;
sscanf(line, "%d (%d ,%d ) %n", &index, &x, &y, &n);
// Did scanning make it to the end and was there no extra junk at the end?
if (n > 0 && line[n] ==  '\0') {
  // Entire line scanned into index,x,y
  printf("index:%d, x:%d, y:%d\n", x, y, n);
} else
  char ch;
  n = 0;
  sscanf(line, " %c %n", &ch, &n);
  if (n > 0 && line[n] ==  '\0') {
    // Entire line scanned into ch
    printf("ch:%c\n", ch);
  } else {
    printf("'%s' failed to scan into either\n", line);
  }
}

A: sscanf does formatted input, same as printf does formatted output.
const char *line = "1(5,4)";
int one;
int five;
int four;
sscanf(line, "%d(%d,%d)", &one, &five, &four);

A: I think you can use fscanf(file, "%c", ch).
then use fgets to get the to the next line.

A: A quick solution can be just ignoring the characters you don't want. As here you just don't want to include the brackets you can use this. You can also check for if the character you're iterating is a digit or character and include it in the new string.
while (fgets(line, sizeof(line), file)) {
char modified[256];
int j = 0;

for (int i = 0; line[i] != '\0'; i++)
    if (line[i] != '(' && line[i] != ')')
        modified[j++] = line[i];
modified[j] = '\0';
printf("%s", modified);
}

A: If you want to discard everything in the line after and including the first (, then just do:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

FILE * xfopen(const char *path, const char *mode);

int
main(int argc, char **argv)
{
        FILE* file = argc > 1 ? xfopen(argv[1], "r") : stdin;
        char line[256];
        while( fgets(line, sizeof line, file) != NULL ) {
                char *c = strchr(line, '(');
                if( c != NULL )
                        *c = '\0';
                printf("%s%s", line, c ? "\n" : "");
        }
        fclose(file);
        return 0;
}

FILE *
xfopen(const char *path, const char *mode)
{
        FILE *fp = strcmp(path, "-") ? fopen(path, mode) : stdin;
        if( fp == NULL ) {
                perror(path);
                exit(EXIT_FAILURE);
        }
        return fp;
}

Using scanf is overly complicated, and there's no need to be copying strings around.


text:
Q: Excel macro enabled worksheet gives error upon saving I am currently working in developing a managing tool that is intended to be use by the whole office in the day to day management. This excel-based tool is a multiple sheet workbook in which several actions can be carried out automatically (using Private Sub Worksheet_Change) or through specific buttons.
In particular one of the purposes is to create automatically, once I enter an activity description, a validation list of the running projects (parametric) which are saved in another sheet. Even if the code seems to work smoothly, every time I save and close the worksheet the following error pop-up:
Excel error.
It seems similar to another problem that I face in another sheet ("Calendar") in which again the code has to perform a similar task changing the validation on the cell next to the one in which the project has been inserted.
Basically it seems that the problem is mainly caused by this parametric validation list but I am not able to found exactly where. Can you support?
Here attached you can find the code for the two sheets:
Week
Private Sub Worksheet_Change(ByVal Target As Range)
'On Error GoTo exitsub
Application.EnableEvents = False
Application.ScreenUpdating = False

Dim ws_proj_port As Worksheet
Dim ws_act_cat As Worksheet
Dim ws_curr_week As Worksheet
Dim ws_cal As Worksheet
Dim ws_graph As Chart
Dim proj_type As String
Dim act_proj_arr(100) As String
Dim act_proj_val As String
Dim lastrow_act As Integer
Dim hrs_done As Double
Dim hrs_day As Double
Dim hrs_week As Double
Dim hrs_marker As Double

Dim i As Integer
Dim j As Integer
Dim r As Integer

Set ws_curr_week = ActiveSheet
Set ws_proj_port = Sheets("Projects portfolio")
Set ws_act_cat = Sheets("Activity categories")
Set ws_cal = Sheets("Calendar")

proj_type = ""
proj_color = ""
proj_name = ""
act_cat = ""
act_cat_j = ""
proj_imp = ""

If Target.row > 2 And Target.row < 34 And Target.Column < 16 Then
    If Target.Column = 1 Then
        If Target.Value <> "" Then
            ws_curr_week.Cells(Target.row, Target.Column + 1).Value = "- to be selected -"

            '------- START project validation list creation
            ws_curr_week.Activate
            ws_curr_week.Cells(Target.row, Target.Column + 1).Validation.Delete
            ws_curr_week.Cells(Target.row, Target.Column + 1).Select
            With Selection.Validation
            .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=week_proj"
            .IgnoreBlank = True
            .InCellDropdown = True
            .InputTitle = ""
            .ErrorTitle = ""
            .InputMessage = ""
            .ErrorMessage = ""
            .ShowInput = True
            .ShowError = True
            End With
            '----- END project validation list creation
        Else
            ws_curr_week.Cells(Target.row, Target.Column + 1).ClearContents
            ws_curr_week.Cells(Target.row, Target.Column + 1).Validation.Delete
            ws_curr_week.Cells(Target.row, Target.Column + 2).ClearContents
            ws_curr_week.Cells(Target.row, Target.Column + 2).Validation.Delete
            ws_curr_week.Cells(Target.row, 7).ClearContents
        End If
    ElseIf Target.Column = 2 Then
        If Target.Value <> "" Then
        '------- START activity validation list creation
            ws_proj_port.Activate
            ws_proj_port.Range("A2").Select
            Selection.End(xlDown).Select
            r = ActiveCell.row
            proj_matrix = "A2:H" & r
            proj_name = ws_curr_week.Cells(Target.row, Target.Column).Value
            proj_type = Application.VLookup(proj_name, ws_proj_port.Range(proj_matrix), 2, False)
            proj_color = Application.VLookup(proj_name, ws_proj_port.Range(proj_matrix), 3, False)

            ws_act_cat.Activate
            ws_act_cat.Range("D2").Select
            Selection.End(xlDown).Select
            lastrow_act = ActiveCell.row
            j = 0
            i = 2

            If proj_type = "Linework" Then
                For i = 2 To lastrow_act
                    If ws_act_cat.Cells(i, 1).Value = proj_type And ws_act_cat.Cells(i, 2).Value = proj_name Then
                        act_proj_arr(j) = ws_act_cat.Cells(i, 4).Value
                        j = j + 1
                    End If
                Next i
            Else
                For i = 2 To lastrow_act
                    If ws_act_cat.Cells(i, 1).Value = proj_type Then
                        act_proj_arr(j) = ws_act_cat.Cells(i, 4).Value
                        j = j + 1
                    End If
                Next i
            End If

            act_proj_val = Join(act_proj_arr, ",")

            ws_curr_week.Activate
            ws_curr_week.Cells(Target.row, Target.Column + 1).Value = "- to be selected -"
            ws_curr_week.Cells(Target.row, Target.Column + 1).Validation.Delete
            ws_curr_week.Cells(Target.row, Target.Column + 1).Select
            With Selection.Validation
                .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=act_proj_val
                .IgnoreBlank = True
                .InCellDropdown = True
                .InputTitle = ""
                .ErrorTitle = ""
                .InputMessage = ""
                .ErrorMessage = ""
                .ShowInput = True
                .ShowError = True
            End With
            '------- END activity validation list creation

            'Set Importance Y/N
            ws_curr_week.Cells(Target.row, 7).Value = Application.VLookup(proj_name, ws_proj_port.Range(proj_matrix), 7, False)
        Else
            ws_curr_week.Cells(Target.row, 7).ClearContents
            ws_curr_week.Cells(Target.row, Target.Column + 1).ClearContents
            ws_curr_week.Cells(Target.row, Target.Column + 1).Validation.Delete
        End If
    ElseIf Target.Column = 10 Or Target.Column = 11 Then
        If Target.Value <> "" Then
            ws_curr_week.Cells(Target.row, 12).Value = Format(Date, "dd/mm", vbMonday, vbFirstJan1)
            ws_curr_week.Cells(Target.row, 13).Value = Application.Text(Date, "[$-809]dddd")
        Else
            ws_curr_week.Cells(Target.row, 12).ClearContents
            ws_curr_week.Cells(Target.row, 13).ClearContents
        End If
        calc_hrs hrs_done, hrs_day, hrs_week, hrs_marker
        create_graph hrs_done, hrs_day, hrs_week, hrs_marker
    ElseIf Target.Column = 4 And ws_curr_week.Range("P2") <> "Sunday" And ws_curr_week.Range("P2") <> "Saturday" And ws_curr_week.Range("P2") <> "Monday" Then
        calc_hrs hrs_done, hrs_day, hrs_week, hrs_marker
        create_graph hrs_done, hrs_day, hrs_week, hrs_marker
    End If
End If

Target.Cells.Select
exitsub:
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub

Calendar
Private Sub Worksheet_Change(ByVal Target As Range)
'On Error GoTo exitsub
Application.EnableEvents = False
Application.ScreenUpdating = False

Dim ws_proj_port As Worksheet
Dim ws_act_cat As Worksheet
Dim ws_cal As Worksheet
Dim ws_hid As Worksheet
Dim act_proj_arr(100) As String
Dim act_proj_val As String
Dim proj_name As String
Dim last_proj As Integer

Set ws_proj_port = Sheets("Projects portfolio")
Set ws_act_cat = Sheets("Activity categories")
Set ws_cal = Sheets("Calendar")
Set ws_hid = Sheets("Hidden")

If Target.Column > 2 And Target.Column < 14 And Target.row < 16 Then
    If Target.Column Mod 2 <> 0 Then
        If Target.Value = "-" Then
            ws_cal.Cells(Target.row, Target.Column + 1).Value = "-"

            ws_cal.Range(Cells(Target.row, Target.Column), Cells(Target.row, Target.Column + 1)).Select
            With Selection.Interior
                .Pattern = xlSolid
                .PatternColorIndex = xlAutomatic
                .ThemeColor = xlThemeColorAccent3
                .TintAndShade = -0.249977111117893
                .PatternTintAndShade = 0
            End With

            With Selection.Font
                .ThemeColor = xlThemeColorDark1
                .TintAndShade = 0
            End With

            With Selection
                .Font.Bold = True
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlCenter
            End With
            ws_cal.Cells(Target.row, Target.Column).Select

        ElseIf Target.Value = "Lunch" Then
            ws_cal.Cells(Target.row, Target.Column + 1).ClearContents
            ws_cal.Range(Cells(Target.row, Target.Column), Cells(Target.row, Target.Column + 1)).Select
            With Selection
                .Style = "Accent2"
                .Font.Bold = True
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlCenter
            End With

        ElseIf Target.Value <> "" Then
            '------- START formatting
            proj_name = ws_cal.Cells(Target.row, Target.Column).Value
            ws_proj_port.Activate
            ws_proj_port.Range("A2").Select
            Selection.End(xlDown).Select
            last_proj = ActiveCell.row
            proj_arr = ws_proj_port.Range("A1:A" & last_proj)
            proj_row = Application.Match(proj_name, proj_arr, 0)
            ws_proj_port.Activate
            ws_proj_port.Range("H" & proj_row).Select
            Selection.Copy

            ws_cal.Activate
            ws_cal.Range(Cells(Target.row, Target.Column), Cells(Target.row, Target.Column + 1)).PasteSpecial xlPasteFormats
            ws_cal.Range(Cells(Target.row, Target.Column), Cells(Target.row, Target.Column + 1)).Interior.Color = ws_proj_port.Range("H" & proj_row).Interior.Color
            ws_cal.Range(Cells(Target.row, Target.Column), Cells(Target.row, Target.Column + 1)).WrapText = True

            Application.CutCopyMode = False

            '------- END formatting

            '------- START activity validation list creation
                ws_proj_port.Activate
                ws_proj_port.Range("A2").Select
                Selection.End(xlDown).Select
                r = ActiveCell.row
                proj_matrix = "A2:H" & r
                proj_name = ws_cal.Cells(Target.row, Target.Column).Value
                proj_type = Application.VLookup(proj_name, ws_proj_port.Range(proj_matrix), 2, False)
                proj_color = Application.VLookup(proj_name, ws_proj_port.Range(proj_matrix), 3, False)

                ws_act_cat.Activate
                ws_act_cat.Range("D2").Select
                Selection.End(xlDown).Select
                lastrow_act = ActiveCell.row

                j = 0
                i = 2

                If proj_type = "Linework" Then
                    For i = 2 To lastrow_act
                        If ws_act_cat.Cells(i, 1).Value = proj_type And ws_act_cat.Cells(i, 2).Value = proj_name Then
                            act_proj_arr(j) = ws_act_cat.Cells(i, 4).Value
                            j = j + 1
                            Else
                        End If
                    Next i
                    Else
                    For i = 2 To lastrow_act
                        If ws_act_cat.Cells(i, 1).Value = proj_type Then
                            act_proj_arr(j) = ws_act_cat.Cells(i, 4).Value
                            j = j + 1
                            Else
                        End If
                    Next i
                End If

                act_proj_val = Join(act_proj_arr, ",")

                ws_cal.Activate
                ws_cal.Cells(Target.row, Target.Column + 1).Value = "- to be selected -"
                ws_cal.Cells(Target.row, Target.Column + 1).Validation.Delete
                ws_cal.Cells(Target.row, Target.Column + 1).Select
                With Selection.Validation
                .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=act_proj_val
                .IgnoreBlank = True
                .InCellDropdown = True
                .InputTitle = ""
                .ErrorTitle = ""
                .InputMessage = ""
                .ErrorMessage = ""
                .ShowInput = True
                .ShowError = True
                End With
                '------- END activity validation list creation

                Else
                ws_cal.Cells(Target.row, Target.Column).Select
                Call cell_cal_format
                ws_cal.Cells(Target.row, Target.Column + 1).ClearContents
                ws_cal.Cells(Target.row, Target.Column + 1).Validation.Delete
                ws_cal.Cells(Target.row, Target.Column + 1).Select
                Call cell_cal_format
                ws_cal.Cells(Target.row, Target.Column).Select
        End If
    End If
End If

exitsub:
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub

Sub cell_cal_format()
Selection.Style = "Normal"
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone

End Sub

Thanks in advance!
Alessio


text:
Q: Archimedean ordered field and non-expressible in first order logic In Chang and Keisler's model theory, they define that an ordered field $(F,+_{F},\cdot,0_{F},1_{F},\le)$ is Archimedean iff for any two positive elements $a$, $b$ in $F$ there is an $n$ such that $b\le na$.
(Here the notation $na$ is an abbreviation for the term $a+_{F}\ldots+_{F}a$, $n$ times.)
And they say that this definition is not expressible in first order logic.
My question is why it is impossible to express the definition in first order logic. In $\mathrm{ZF}$, we can define recursively a function $f$ such that $\mathrm{dom}(f)=\omega$, $f(0)=a$ and $f(n+1)=f(n)+_{F}a$. So the definition can be formalized in $\mathrm{ZF}$. I don't know what I'm missing..

A: As Alex Kruckman says, the intended meaning is that this definition can't be expressed in the first-order language of ordered fields. The problem is that the first-order language of ordered fields does not obviously allow you to quantify over all positive integers $n$; you can talk about
$$na = \underbrace{a + \dots + a}_{n \text{ times}}$$
for any fixed $n$, but the first-order language of ordered fields $F$ only allows you to quantify over $F$, and doesn't obviously supply you with a way of talking about $\mathbb{N} \subset F$.
I say "obviously" because a priori there could be a clever trick that does it, but in fact there can't be such a trick. This is because the class of models of a first-order theory must be closed under ultraproducts, but it's possible for an ultraproduct of archimedean fields to be non-archimedean. For example the ultrapower $\mathbb{R}^{\infty}/U$ of countably many copies of $\mathbb{R}$ (the nonstandard reals) is non-archimedean: we can take $a = (1, 1, 1, \dots)$ and $b = (1, 2, 3, \dots)$ and then there is no positive integer $n$ such that $b \le na$ (in other words, $b$ is infinitely large compared to $a$).
Ignorable additional comment: You can extend the first-order theory of ordered fields to a two-sorted theory consisting of one sort for the natural numbers $\mathbb{N}$ and another sort for the field $F$, together with, say, an embedding $\mathbb{N} \hookrightarrow F$; this would allow you to talk about the operation $(n, a) \mapsto na$ where $n \in \mathbb{N}$ and $a \in F$, and to quantify over $\mathbb{N}$. Now the problem is that it's impossible to write down axioms guaranteeing that the first sort is exactly $\mathbb{N}$ and not some larger nonstandard model of the natural numbers; for example, whatever axioms we write down, we can take an ultrapower of the pair $(\mathbb{N}, \mathbb{R})$ and we'll have infinitely large nonstandard natural numbers, so the ultrapower $\mathbb{R}^{\infty}/U$ will still be "archimedean" but with respect to the nonstandard natural numbers $\mathbb{N}^{\infty}/U$, not the standard ones. So this doesn't work either.


text:
Q: How to retrieve the old value of a column in a table after an update laravel I'm wondering if this is possible.In my project user can  update a column value of a table.But other users cant see the updated value upto 14 days.Upto 14 days old value will populate in every retrival operations.Is it possible to do in laravel?

A: You need to either use caching or add another column on the table called old_column, then in your Model you could include a getter/accessor to check the updated_at timestamp on the row then either return the new/old value.
    public function getColumnAttribute($value)
    {
        if($this->updated_at < Carbon::now()->subWeeks(2)) {
            return $this->old_column;
        }
        return $value;
    }

be aware that since you have not been clear on your column names, I've literally named them:
column and old_column, the function name on your model should be get{COLUMN NAME}Attribute
See: https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor
Note, if you want the user that edited the value to see the change, you must include user_id on the table. But at this point, you would not retain ownership of a change and would be better of making a diff style table to house all of these changes as a log.

A: There is only one way to do it, you need to store both values.
Take the example of price column.
We can define accessors in model
Have two columns price & old_price
public function getPriceAttribute($value)
{
    if($this->updated_at < Carbon::now()->subWeeks(2)) { // 14 days check
        return $this->old_price;
    }
    return $value;
}

And then you can user it as
$product->price;


text:
Q: Can't fix X in command line for Python I just started to learn Python and am using the Jupyter Notebook to write code. I'm unsure how to fix this problem. Every time I type into the command line 'x' it brings the x to the beginning of the command line.
for example:
If I want to type
x1=5
print(x1)

it becomes
x1=5
xprint(1

The moment I type in x it brings it to the front of the command line! I'm unsure how and why this is happening and how to fix it. This doesn't happen with any other letters such as y or z. It only happens when I type in x.


text:
Q: ASP.NET MVC5 display date in custom format I'm trying to format a DateTime Variable so that it's being displayed as MMMM dd, yyyy, e.g. June 10, 2011.
In my view I have:
@Html.Raw(modelItem => item.MyDateTimeProperty.ToString("MMMM dd, yyyy"))

Which throws me an exception as follows:
lambda expression cannot be converted to 'string' because 'string' is not
a delegate type

Of course, the item.MyDateTimeProperty data type is DateTime.
For reference I used the following example [1]
// The example displays the following output:
//    Today is June 10, 2011.
DateTime thisDate1 = new DateTime(2011, 6, 10);
Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");

What am I doing wrong?
EDIT
I see that stack247's answer is the most proper solution in an ideal environment. In my case, however, the controller returns an object which doesn't exist in my model classes. This is due I'm consuming an API to get the data. That's why Anrei's solution is best for me.
@Html.Raw(item.MyDateTimeProperty.ToString("MMMM dd, yyyy"))

[1] http://msdn.microsoft.com/en-US/library/8kb3ddd4%28v=vs.110%29.aspx

A: You can format date time in your View by adding annotation to your model:
[DisplayFormat(DataFormatString = "{0:MMMM dd, yyyy}")]
public DateTime ThisDate { get; set }

Then in your View:
@Html.DisplayFor(x => x.ThisDate)

A: Html.Raw actually expects a string as a parameter, and you are passing in a lambda. Not sure why though, you are not using lambda in any way here. So this is what error message is referring to.
Look like it should be just
@Html.Raw(item.MyDateTimeProperty.ToString("MMMM dd, yyyy"))

A: @Html.Raw() method accepts a string, I think you should use @Html.DisplayFor() instead.
@Html.DisplayFor(model => model.Date)

You can also check this question for info on applying formats I don't want error message as "The field <field> must be a date", if I am selecting date in "yyyy/MM/dd" format in en-AU locale


text:
Q: cobc: Invalid argument error when compiling I'm currently taking up  a course in COBOL and recently I have only been using an online compiler. When I decided to install the OpenCOBOL IDE. I keep getting the error "cobc: Invalid argument" whenever i try to compile. I tried multiple re-installs still to no avail. I also tried installing just the compiler itself and compiling my files using cmd, but still it gives that error. Any help? I really need to get it working.
OS: Windows 8.1 64-bit

A: You need an "-x" option to tell the compiler build an executable with the same name as the program source (but without the .cbl or a "-o progname" option to tell the compile to produce an executable named progname.


text:
Q: Is $\lambda_2(B\times\mathbb{R})$ on the sigma algebra $\sigma:=\{B \times \mathbb{R}:B\in\mathcal{B}\}$ sigma-finite? $\mu(B \times \mathbb{R}):=\lambda_2(B\times\mathbb{R})$ on the sigma algebra $\sigma:=\{B \times \mathbb{R}:B\in\mathcal{B}\}$. $\lambda_2$ denotes the 2-dimensional Lebesgue measure.
According to my script $\mu$ is not sigma finite.
Can anybody tell me why it is not sigma finite?
The problem I have with this task is that there is no $\Omega$ given.
Thanks in advance!

A: To cast away your problem, recall that $\Omega$ is just the biggest element of the $\sigma$-algebra, so in this case $\Omega = \Bbb R^2$. By definition of $\sigma$-finite measures, there should exist an increasing sequence of $A_n\subset \Omega$ such that $\lambda_2(A_n) < \infty$ and the union of $A_n$ is $\Omega$. In your case, do you have any set in your $\sigma$-algebra of non-zero finite measure?

A: Here $\Omega=\mathbb R\times\mathbb R$.
If $A\times\mathbb R$ is an elements of the $\sigma$-algebra with $\mu(A\times\mathbb R)<\infty$ then $\lambda_1(A)=0$.
Consequently if $(A_n\times\mathbb R)_n$ is a sequence of measurable sets with finite measure then: $$\lambda_1\left(\bigcup_{n=1}^{\infty}A_n\right)\leq\sum_{n=1}^{\infty}\lambda_1(A_n)=0\text{ hence }\bigcup_{n=1}^{\infty}A_n\neq\mathbb R$$
Then: $$\bigcup_{n=1}^{\infty}(A_n\times\mathbb R)=\left(\bigcup_{n=1}^{\infty}A_n\right)\times\mathbb R\neq\mathbb R\times\mathbb R$$
showing that $\mu$ is not $\sigma$-finite.


text:
Q: Link in paper-item inside paper-menu-button (Polymer-1.0) update 1: found this issue with pull request which seems to be addressing this issue in Polymer.
update 2: Decided to restructure my layout based on the Polymer Starter Kit which uses page.js instead of app-router, and seems to work well, although they don't use paper-item in paper-menu but instead use custom anchor elements.
Search every bit of documentation but I can't find this (although there is another issue on stackoverflow with almost the same title, not same thing)
TLDR: I need to have to whole paper-item clickable to the link. Not just the text itself. See image below for clarity and here is the live code.
.
I've got something like the code below. I'm using link tags in combination with app-router routing which works great. The only problem is: I would like to have have the entire paper-menu-item to be clickable with the link tag.
When I use below code, the right page is retrieved when clicking directly on the link tekst itself, but that doesn't create a "selected" state. When I click on the button (just off the text) then the button IS selected but the page isn't retrieved because I didn't click the link...
There must be an easy way to do this right? I mean, I could force this by overriding all the CSS but it seems to me a link in a paper-item in a paper-menu would be a very common thing which should do this automatically or with an attribute or someting?
<paper-menu class="list">
  <paper-item icon="home" label="Home" >Home</paper-item>
  <paper-item icon="polymer" label="Demo">Demo</paper-item>
</paper-menu>

I checked documentation on paper-item, paper-menu and others but those never use an example with a link.

A: IMO, the most clean way is to just drop the links altogether and just add on-tap event.
(You can also use dom-repeat for your menu)
<paper-menu class="list">
  <paper-item icon="home" label="Home" on-tap="menuSelected" mypath="/">Home</paper-item>
  <paper-item icon="polymer" label="Demo" on-tap="menuSelected" mypath="/demo">Demo</paper-item>
</paper-menu>

I'm assuming your are using  tags because of app-router.
From app-router doc:

go(path, options) -  You can call the router from Javascript to navigate imperatively.

Then you can simple write your own on-tab handler and use custom attribute (mypath) on each <paper-item>
Polymer({
    is: 'your-menu',
    menuSelected: function (e) {
        var mypath = e.currentTarget.getAttribute('mypath');
        document.querySelector('app-router').go(mypath);
    },
})();

A: Add class="flex" to each of your anchor tags.


text:
Q: Nested list to unique set based on entity equals I found the bottleneck of my Kruskal-implementation. I need to convert a
List<List<Edge<T extends Comparable<T>>>> adjacencyList;
// This looks like this: get(0) = [Edge:{Vertex V0, Vertex V1, T weight}, Edge:{Vertex V0, Vertex V2, T weight}, ...]
// and get(indexOf(Vertex V1)) = [{Vertex V1, Vertex V0}, ...]
// obviously indexOf(Vertex) does not comply with type Edge, but the idea is that the index of the Edge where the Vertex otherFirst is the getFrom() is retrieved.

to a unique list of edges (see equals method for reference of equality). I need to optimise this and potentially replace with a more efficient solution. The solution should look like this:
get(0) = Edge:{Vertex V0, Vertex V1, T weight}
// there is no element which is Edge:{Vertex V1, Vertex V0, T weight}

My current solution looks like this:
private List<Edge<T>> toAdjacencyList(final List<List<Edge<T>>> edges) {
    List<Edge<T>> flat = edges.parallelStream().flatMap(List::stream)
        .collect(Collectors.toList());
    final Set<Edge<T>> unique = new HashSet<>();
    unique.addAll(flat);
    return new ArrayList<>(unique);
}

*

*Running this against a 1000 vertex, 1000 edge input takes 5ms.

*Running this against a 1000 vertex, 10000 edge input takes 780ms.

*Against a 1000 vertex, 100 000 edge input takes X seconds. I do not know. (And this is what I need to work).

The actual Kruskal-algorithm after the data-caching takes much less than one second.
How do I optimise this, or alternatively, replace this with?
Note: two edges being equal means that Edge:{V1, V0, 10f} and Edge:{V0, V1, 10f} are the same. I am positive that this works.

A: I had incorrectly implemented the equals method, however, I had forgotten to include Vertex from and Vertex to in the hashCode, if anyone ever has a similar problem.


text:
Q: My app rejected with some issues I was trying to publish my app in app store I finished every process they rejected with some reasons, Apps are reviewed on an IPv6 network. Please ensure that your app supports IPv6 networks, as IPv6 compatibility is required. I'm not aware of this thing can anyone explain me what is this and how to solve this problem because in my mobile I tested app it's working properly.

A: Since this June, Apple expects Apps to run on IPV6 networks. Apple has started rejecting Apps which do no comply with this.
NSURLSession, NSURLConnection, AFNetworking 3.x+ all support IPV6
If you are using any other network libraries, please use below link to test IPV6 support http://www.brianjcoleman.com/tutorial-how-to-test-your-app-for-ipv6-compatibility/
Once you have made the relevant changes and tested for IPV6 supp


text:
Q: Como carregar imagem padrão caso o src="" não encontre? Existe alguma forma de carregar uma imagem padrão, usando apenas HTML, caso o primeiro src="" não encontre o arquivo?
 // Existe algum atributo para isso?

A: Outros fallbacks mais simples que pode experimentar, com javascript:

Um exemplo no jsfiddle do @Randrade: https://jsfiddle.net/wts9e4xb/1/

Sem error

Com error

Com CSS (requer tamanho fixo):

A: Encontrei essa solução...

<object data="https://img.com.br/no_existe.jpg" type="image/png">

</object>

Nessa pergunta


text:
Q: Changing default caption name in table environment I am using a polish latex package and I noticed something weird.
When I begin the table environment the caption normally (in English) begins with Table 1: {title}
In Polish, it begins with Tablica 1. This is really weird because Table does not translate into Tablica it translates into Tabela.
I would like to change the table environment to say Tabela instead of Tablica.
I have no idea how to do that. I read about \captionof but I'd like to continue using the table environment.
\begin{table}[ht]
    \centering\captionsetup{font=small}
    \caption{Przyporządkowanie obiektów modelu logicznego i fizycznego}
    \begin{tabular}{l l}
       \toprule
       \textbf{Obiekty modelu logicznego} & \textbf{Obiekty
       modelu fizycznego} \\
       \midrule
        Encja & Tabela \\[0.2cm]
        Atrybut encji & Kolumna tabeli \\[0.2cm]
        Identyfikator encji & Klucz główny tabeli \\[0.2cm]
        Związek & Klucz obcy i reguły integralności \\
        \bottomrule\addlinespace[0.5ex]
    \multicolumn{2}{r@{}}{\footnotesize Źródło: Czapla K., Bazy danych. Podstawy projektowania i języka SQL, 2015}
    \end{tabular}
    \label{table:1}
\end{table}

This code creates something like this.

Basically, I would like to change Tablica 1 to Tabela 1 while still using the environment so the changes would apply to all other tables
Edit:
I started to wonder if making my own new numbered environment isn't the solution for me. I would like to hear an opinion from more experienced users than myself


text:
Q: Apache Derby EmbeddedDataSource no longer available I was using a 10.8.x.x version of Apache Derby and utilizing the EmbeddedDataSource class. I can't seem to find a non interface replacement. I was able to find the classes located in org.apache.derby.iapi.jdbc. which contains an EmbeddeDataSource interface, but no actual implementation of the class. Was this moved somewhere or is there an alternative class I can use? I haven't been able to find anything. Thanks!

A: Are you trying to upgrade Derby from 10.8.x.x to 10.15.x.x or higher?
In that case you need to additionally add the artifact derbytools to the artifacts derby and derbyshared that you probably already have on the classpath.
With release 10.15.1.3, Derby has been modularized and the classes have been rearranged a bit. EmbeddedDataSource is now in derbytools.jar: https://db.apache.org/derby/releases/release-10.15.1.3.html


text:
Q: When I refresh page, you can see a transition action? I have a little dilemma here. When I refresh the page in chrome I can see a transition action made by transition-duration on images and on the button on the bottom of the web page. The weird thing is that it does not happening on Firefox.On Mozilla it works without transition when you refresh the page. It works well only when you hover it. How can I fix it for chrome???

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
 margin: 0;
 padding: 0;
 border: 0;
 font-size: 100%;
 font: inherit;
 vertical-align: baseline;
}

/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
 display: block;
}
body {
 line-height: 1;
}

ol, ul {
 list-style: none;
}
blockquote, q {
 quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
 content: '';
 content: none;
}
table {
 border-collapse: collapse;
 border-spacing: 0;
}
/* Ending of resets */

.container
{
 width:1200px;
 height:1630px;
 background-color:grey;
 margin-left:auto;
 margin-right:auto;
 margin-bottom:10px;
}
.topmenu
{
 width:1200px;
 height:30px;
 background-color:skyblue;
 margin-left:auto;
 margin-right:auto;
}
.topmenu ul
{
 margin-left:100px;
}
.topmenu li
{
 float:left;
 margin-left:30px;
 margin-top:4px;
 font-size:17px;
 color:black;
}
.topmenu a
{
 color:black;
}
.logo2
{
 position:relative;
 font-size:35px;
 margin-top:20px;
 margin-left:150px;

}
.logo2 a
{
 text-decoration:none;
 color:black;
}
.content
{
 width:950px;
 height:350px;
 margin:30px auto;
}
.square1
{
 float:left;
 width:300px;
 height:300px;
 border-bottom:40px solid darkgrey;
}
.square1 img
{
 -webkit-filter:blur(5px);
 filter:blur(5px);
 transition-duration:1s;
 cursor:pointer;
}
.square1 img:hover
{
 -webkit-filter:blur(0);
 filter:blur(0);
}
.square2
{
 float:left;
 width:300px;
 height:300px;
 margin-left:25px;
 border-bottom:40px solid darkgrey;
}
.square2 img
{
 -webkit-filter:brightness(200%);
 filter:brightness(200%);
 transition-duration:1s;
 cursor:pointer;
}
.square2 img:hover
{
 -webkit-filter:brightness(100%);
 filter:brightness(100%);
}
.square3
{
 float:left;
 width:300px;
 height:300px;
 margin-left:25px;
 border-bottom:40px solid darkgrey;
}
.square3 img
{
 -webkit-filter:contrast(200%);
 filter:contrast(200%);
 transition-duration:1s;
 cursor:pointer;
}
.square3 img:hover
{
 -webkit-filter:contrast(100%);
 filter:contrast(100%);
}
.square4
{
 float:left;
 width:300px;
 height:300px;
 border-bottom:40px solid darkgrey;
}
.square4 img
{
 -webkit-filter:drop-shadow(8px 8px 10px orange);
 filter:drop-shadow(8px 8px 10px orange);
 transition-duration:1s;
 cursor:pointer;
}
.square4 img:hover
{
 -webkit-filter:drop-shadow(12px 12px 14px green);
 filter:drop-shadow(12px 12px 14px green);
}
.square5
{
 float:left;
 width:300px;
 height:300px;
 margin-left:25px;
 border-bottom:40px solid darkgrey;
}
.square5 img
{
 -webkit-filter:grayscale(100%);
 filter:grayscale(100%);
 transition-duration:1s;
 cursor:pointer;
}
.square5 img:hover
{
 -webkit-filter:grayscale(0);
 filter:grayscale(0);
}
.square6
{
 float:left;
 width:300px;
 height:300px;
 margin-left:25px;
 border-bottom:40px solid darkgrey;
}
.square6 img
{
 -webkit-filter:hue-rotate(90deg);
 filter:hue-rotate(90deg);
 transition-duration:1s;
 cursor:pointer;
}
.square6 img:hover
{
 -webkit-filter:hue-rotate(360deg);
 filter:hue-rotate(360deg);
}
.square7
{
 float:left;
 width:300px;
 height:300px;
 border-bottom:40px solid darkgrey;
}
.square7 img
{
 -webkit-filter:invert(100%);
 filter:invert(100%);
 transition-duration:1s;
 cursor:pointer;
}
.square7 img:hover
{
 -webkit-filter:invert(0);
 filter:invert(0);
}
.square8
{
 float:left;
 width:300px;
 height:300px;
 margin-left:25px;
 border-bottom:40px solid darkgrey;
}
.square8 img
{
 -webkit-filter:saturate(8);
 filter:saturate(8);
 transition-duration:1s;
 cursor:pointer;
}
.square8 img:hover
{
 -webkit-filter:saturate(2);
 filter:saturate(2);
}
.square9
{
 float:left;
 width:300px;
 height:300px;
 margin-left:25px;
 border-bottom:40px solid darkgrey;
}
.square9 img
{
 -webkit-filter:sepia(100%);
 filter:sepia(100%);
 transition-duration:1s;
 cursor:pointer;
}
.square9 img:hover
{
 -webkit-filter:sepia(0);
 filter:sepia(0);
}
.square10
{
 float:left;
 width:300px;
 height:300px;
 border-bottom:40px solid darkgrey;
}
.square10 img
{
 -webkit-filter:opacity(30%);
 filter:opacity(30%);
 transition-duration:1s;
 cursor:pointer;
}
.square10 img:hover
{
 -webkit-filter:opacity(100%);
 filter:opacity(100%);
}
.square11
{
 float:left;
 width:300px;
 height:300px;
 margin-left:25px;
 border-bottom:40px solid darkgrey;
}
.square11 img
{
 -webkit-filter:contrast(150%) brightness(200%);
 filter:contrast(150%) brightness(200%);
 transition-duration:1s;
 cursor:pointer;
}
.square11 img:hover
{
 -webkit-filter:contrast(100%) brightness(100%);
 filter:contrast(100%) brightness(100%);
}
.square12
{
 float:left;
 width:300px;
 height:300px;
 margin-left:25px;
 border-bottom:40px solid darkgrey;
}

.loadmore
{
 position:relative;
 margin:50px auto;
 width:100px;
 height:100px;
 border-radius:30px;
 background-color:orange;
 text-align:center;
 transition-duration:1s;
}
.loadmore:hover
{
 background-color:skyblue;
}
.loadmore a
{
 color:black;
 text-decoration:none;
}
.loadmore h1
{
 padding-top:37px;
 font-size:20px;
 font-weight:bold;
}
.footermenu
{
 width:600px;
 height:30px;
 background-color:yellow;
 margin:10px auto;
}

.footermenu li
{
 width:150px;
 height:30px;
 float:left;
 text-align:center;
 margin-top:5px;
 font-size:18px;
}
.footermenu a
{
 color:black;
 text-decoration:none;
}
form
{
 float:right;
 margin-right:140px;
 margin-top:-25px;
 z-index:999;
}
 label
 {
  z-index:999;
 }
input
{
 width:150px;
 z-index:999;
}
<!doctype html>

<title>Just Web</title>
 <meta name="description" content="" />
 <meta name="keywords" content="" />
 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 <meta name="viewport" content="width=device-width; scale=1" />
 <link href="tristastyle.css" rel="stylesheet" type="text/css" />
 <link rel="icon" href="images/favicon.ico">

Home

Project

menu

protosite

  <form>
    search
    <input type="text" id="fname" name="fname">
  </form>

Load more

Policy

FAQ

About

Contact

A: Try adding this to your classes:
-moz-filter:opacity (as much as you want)
If this makes the Firefox transition like chrome, and you don't want that, then remove the -webkit-filter:


text:
Q: Same partition key's data distribution in DynamoDB From what I'm understanding, DynamoDB tries to put items with the same partition key into the same partition. My question is how does the hashing work when the partition is full and gets split into 2 different partitions?
For example, a table has a partition key A, and DynamoDB put all items with partition key A into the same partition P, then P is full, dynamo will split P into P1 and P2, now a new item I with a partition key A is inserted by the client, How does dynamo decide which partition (i.e. P1 and P2) to insert I?

A:
All items with the same partition key are stored together, and for composite partition keys, are ordered by the sort key value. DynamoDB splits partitions by sort key if the collection size grows bigger than 10 GB.

Source: https://aws.amazon.com/blogs/database/choosing-the-right-dynamodb-partition-key/
So in that case they will use the sort key to decide in which partition the elements are stored.
However, I don't know how they deal with the case in which there is no sort key.
I also guess that the time to access a partition will not be constant anymore, because it will be needed to find the proper partition in logarithmic time respect to the number of partitions for this partition key. Since if you use the sort key with the partition key to compute a 'merged' hash key, you won't be able to keep the elements sorted (elements with contiguous sort keys would be in different partitions).

A: Partition Key is used mainly to specify where to store physically the data, this is done using consistent hashing function to distribute your data into different partitions or physical storage. To read the value using partition key, it is going to hash it using the same hashing function to get the correct partition then fetch the data from that partition. While sort key is used to index that data inside each partition.
Partition keys should be designed in away that maintains evenly distribution of your workload instead of having some partitions fully overflown or loaded while having others idle.
You can read more about this here:
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.Partitions.html
https://cloudacademy.com/blog/dynamodb-replication-and-partitioning-part-4/

A: For what i understand, one table cannot have more than one item with same partition key (assume no sort key as part of primary key)
I tried to save same partition key into DynamoDB and it failed


text:
Q: using item property inside an event procedure I have a quick question. How can i check an item's properties within an event procedure? Here is a snippet of what I'm trying to do:
Private Sub application_ItemLoad(ByVal Item As Object)
Dim myolitem As Object
Set myolitem = Item
    If myolitem.Class = olMail Then
        If myolitem.UnRead Then
            UserForm2.Show vbModal
        End If
    End If
End Sub

Thank you in advance for your help.

A: You code looks good, I don't see anything strange there.
Hope you will find the Getting Started with VBA in Outlook 2010 article helpful.

A: Some events (e.g. AfterWrite, ItemLoad) only allow a limited number of properties to be accessed. In your particular case, these are Class and MessageClass - see ApplicationEvents_11_Event.ItemLoad event.
I don't know if MAPIOBJECT is accessible in ItemLoad (I know for sure it is accessible in the AfterWrite event), you can (in theory) access the properties using Extended MAPI (C++ or Delphi) or Redemption (I am its author).