text:
Q: i want to stop execution until this.conn.getUserByAlternateNumber finishes working and returns a value in this code i want to set value in where object before processing to next line , but just after this.conn.getUserByAlterNumber the execution is gone to  if (this.doctorFilter && this.doctorFilter.length) without waiting for response from the function and thus this.conn.getOrders isgetting a blank object in place of where and my filter is not working, how to stop the execution until this.conn.getUserByAlternateNumber returns value.
loadMore(offset: number): Promise<any> {
    let where: any = {};
    this.filters.forEach((item: any) => {
      if (item.key === 'alternateNumber') {
        this.conn.getUserByAlternateNumber(item.value)
          .then((user: any) => {
            where['contactName'] = user[0].attributes.PatientName;
            console.log(where,'>>>>>');
          });
      } else {
        (where[item.key] = item.value);
      }
    });
    if (this.doctorFilter && this.doctorFilter.length) {
      where.allocatedDoctor = this.doctorFilter;
    }
    console.log(where);
     return this.conn.getOrders({
      where,
      include: ['user', 'allocatedDoctor'],
      limit: this.ui.grid.pageSize,
      asc: this.OrderAsc,
      offset,
    })
      .then((items: any) => this.zone.run(() => Promise.resolve(items.map((i: any) => JSON.parse(JSON.stringify(i))))));
  }


text:
Q: IntelliJ IDEA 2019 + lombok + LibGDX. How to fix failed build of application using gradle runner I'm trying to run (or build jar) application using LibGDX, lombok, log4j2 via gradle runner, but it always failed. Looks like lombok dependency is absent in project. Could someone help me to uderstand what I'm doind wrong?
So, there are repro steps:

*

*Create LibGDX project using instruction https://github.com/libgdx/libgdx/wiki/Gradle-and-Intellij-IDEA. Runner that used for compiling is gradle.

Result:
After this step application is built successfully. All places works fine.

*Added couple of dependecies (multiproject):

project(":shared") {
    apply plugin: "java-library"

    dependencies {
        api "com.google.inject:guice:4.2.2"
        api "com.google.inject.extensions:guice-assistedinject:4.2.2"

        api "org.projectlombok:lombok:1.18.10
        annotationProcessor "org.projectlombok:lombok:1.18.10"

        api "org.apache.logging.log4j:log4j-api:2.12.1"
        api "org.apache.logging.log4j:log4j-core:2.12.1"
    }
}

Result: Any attempt to run or build application failed with errors:
error: cannot find symbol log.info (...)

or
error: cannot find symbol @RequiredArgsConstructor(onConstructor = @__(@Inject))

etc.
Environment and soft
I'm using Linux Mint 18.3, Intellij IDEA 2019.1. Annotation processor enabled, lombok plugin installed, gradle 5.4.1, java 8.
Also one thing. If I ran application via default runner (Intellij IDEA), all works fine.
I absolutely don't understand what wrong. If someone could help me, it will be cool.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ошибка в легком sql запросе Есть таблица table_1 в которой есть столбцы id - уникальный, ti,at,timestamp - varchar
Нужно Вычесть значение timestamp там, где at = out из того, где at=in.
У меня ошибка #1066 - Повторяющаяся таблица/псевдоним 'table_1' при выполнении этого кода. Где я ошибся в запросе?
select
    id,
    ti,
    SUM(CAST(table_out.timestamp AS int) - CAST(timestamp AS int))
from
    table_1

LEFT JOIN (table_1 ON at= 'OUT') as table_out on table_out.ti = ti
where
    at = 'IN'

A: Вероятно, запрос должен быть приблизительно таким:
SELECT ti, SEC_TO_TIME(TIMESTAMPDIFF(SECOND, t1.timestamp, t2.timestamp))
FROM table t1
JOIN table t2 USING (ti)
WHERE t1.at = 'IN'
  AND t2.at = 'OUT'


text:
Q: How do I add a scroll view without moving my other views? <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TableLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:layout_width="120dp"
                    android:layout_height="80dp"
                    android:layout_marginLeft="5dp"
                    android:gravity="center_vertical"
                    android:text="I like to go out more than staying home."
                    android:textSize="10.5dp" />

                <Spinner
                    android:id="@+id/spinner1"
                    android:layout_width="wrap_content"
                    android:layout_height="80dp"
                    android:gravity="center_vertical" />
            </TableRow>

            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:layout_width="120dp"
                    android:layout_height="80dp"
                    android:layout_marginLeft="5dp"
                    android:gravity="center_vertical"
                    android:text="Do you tend to over analyze everything, all the time?"
                    android:textSize="10.5dp" />

                <Spinner
                    android:id="@+id/spinner2"
                    android:layout_width="match_parent"
                    android:layout_height="80dp"
                    android:gravity="center_vertical" />
            </TableRow>

            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:layout_width="120dp"
                    android:layout_height="80dp"
                    android:layout_marginLeft="5dp"
                    android:gravity="center_vertical"
                    android:text="You've made most of your decisions based on how you feel."
                    android:textSize="10.5dp" />

                <Spinner
                    android:id="@+id/spinner3"
                    android:layout_width="match_parent"
                    android:layout_height="80dp"
                    android:gravity="center_vertical" />
            </TableRow>

            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:layout_width="120dp"
                    android:layout_height="80dp"
                    android:layout_marginLeft="5dp"
                    android:gravity="center_vertical"
                    android:text="You use past experiences to guide your decisions."
                    android:textSize="10.5dp" />

                <Spinner
                    android:id="@+id/spinner4"
                    android:layout_width="match_parent"
                    android:layout_height="80dp"
                    android:gravity="center_vertical" />
            </TableRow>
        </TableLayout>
    </ScrollView>

        <Button
            android:id="@+id/calculate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="Submit" />

        <TextView
            android:id="@+id/personalitytype"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Personality Type"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

</TableLayout>

A picture of my applicaton can viewed here : http://tinypic.com/r/2uy1t3d/5
Hello, I'd like to add a scroll view to my questions in my application.  This would include the TextViews and Spinners but not the Submit button on the bottom or the TextView below it.  I understand you'd have to mess with the weight, but i'm not getting good results.  Thanks

A: If you want the Button and TextViews below it to remain at the bottom, try putting everything in a RelativeLayout, wrapping your Buttons and TextViews in a LinearLayout and aligning it to the parent's bottom.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <TableLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:layout_width="120dp"
                android:layout_height="80dp"
                android:layout_marginLeft="5dp"
                android:gravity="center_vertical"
                android:text="I like to go out more than staying home."
                android:textSize="10.5dp" />

            <Spinner
                android:id="@+id/spinner1"
                android:layout_width="wrap_content"
                android:layout_height="80dp"
                android:gravity="center_vertical" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:layout_width="120dp"
                android:layout_height="80dp"
                android:layout_marginLeft="5dp"
                android:gravity="center_vertical"
                android:text="Do you tend to over analyze everything, all the time?"
                android:textSize="10.5dp" />

            <Spinner
                android:id="@+id/spinner2"
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:gravity="center_vertical" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:layout_width="120dp"
                android:layout_height="80dp"
                android:layout_marginLeft="5dp"
                android:gravity="center_vertical"
                android:text="You've made most of your decisions based on how you feel."
                android:textSize="10.5dp" />

            <Spinner
                android:id="@+id/spinner3"
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:gravity="center_vertical" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:layout_width="120dp"
                android:layout_height="80dp"
                android:layout_marginLeft="5dp"
                android:gravity="center_vertical"
                android:text="You use past experiences to guide your decisions."
                android:textSize="10.5dp" />

            <Spinner
                android:id="@+id/spinner4"
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:gravity="center_vertical" />
        </TableRow>
    </TableLayout>
</ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true">

        <Button
            android:id="@+id/calculate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="Submit" />

        <TextView
            android:id="@+id/personalitytype"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Personality Type"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />
    </LinearLayout>

</RelativeLayout>

Full disclaimer: Code not tested.


text:
Q: Getting a typed ArrayList from a JSON String in Java I convert an ArrayList into an JSON String and save it into a File. This works perfectly. But if I try do this in reverse, my application doesn't run (I get something like a ClassCastException)
Can somebody tell me what's wrong with my code?
BufferedReader br = new BufferedReader(
new FileReader("/sdcard/file.json"));

myArrayList = gson.fromJson(br, ArrayList.class);

A: Here's a SSCCE that executes and that demonstrates exactly how to get back a typed ArrayList:
public static void main(String args[]) {
    Gson gson = new Gson();

    List<Integer> outList = new ArrayList<Integer>();
    outList.add(1);
    outList.add(2);
    outList.add(3);

    String json = gson.toJson(outList);

    // This is how you tell gson about the generic type you want to get back:
    Type type = new TypeToken<ArrayList<Integer>>(){}.getType();
    ArrayList<Integer> inList = gson.fromJson(json, type);

    for (int i : inList) {
        System.out.println(i);
    }
}

Output:
1
2
3

The fact that this code doesn't explode proves that the ArrayList is in fact typed correctly.
I went to/from String not via a file to simplify the example down to the bare minimum.

A: From the docs, you don't supply ArrayList.class as parameter you specify the type the list contains by using a TypeToken and passing that to fromJSON:
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType(); //change this to whatever type you json contains
Collection<Integer> ints2 = gson.fromJson(br, collectionType);

A: ArrayList<Submission> submitArray = Array.asList(gson.fromJson(submitJson, (new Submission[]{}).getClass()));

A: You will have to create the ArrayList from the native array.
Do you realy need an ArrayList or just an implementation of the List interface?


text:
Q: Python Error 'list index out of range' When Using Split Function Im am trying to pull info from yahoo finance using urllib2 and then using the split function to display the Net Income. When I go to run the program in the Python 2.7.12 shell I have to print the command "yahooNetIncome('')" with the stock symbol in the single quotes. Whenever I do this it comes up with the error "failed in main loop list index out of range". Im rather new to python so I do not fully understand the problem. If someone could please help that would be greatly appreciated.
import time
import urllib2
from urllib2 import urlopen

stock = ['a', 'aa', 'aapl', 'abbv', 'abc', 'abt', 'ace', 'aci', 'acn', 'act', 'adbe', 'adi', 'adm', 'adp']

def yahooNetIncome(stock):
   try:
        sourceCode = urllib2.urlopen('https://finance.yahoo.com/quote/' + stock + '/financials').read()
        NI = sourceCode.split('')[1].split('')[0]
        print 'Net Income: ', NI
    except Exception, e:
        print 'failed in main loop', str(e)

A: You're getting bitten by a couple of things.
The out-of-range error you're getting is due to there being nothing in the list that you're trying to get the zeroth element of in your NI assignment line. That list is empty because the split() call is failing, and it's failing because the string you're feeding into it doesn't exist in the data pulled from the URL. This is the smaller issue.
You're probably wondering why that string isn't in there when you can see it pretty clearly with a browser inspector. Here's where you're getting bitten by the bigger issue: the page you're downloading dynamically changes its content via JavaScript. If you use a tool like Curl to dump it straight out to disk without executing JavaScript you'll see that the string you're searching on doesn't exist within the file. Worse, the string you're trying to fetch (the number that you want to assign NI to) doesn't exist either. The JavaScript must be run before it gets displayed. In your browser you're seeing a live display after the JavaScript has been run. When you're pulling in the page via Python (or Curl or any other tool that doesn't behave like a browser and run JavaScript the way the page expects) you won't get the data you're looking for.
Quite possibly this is being done by the site owner specifically to prevent the sort of thing you're trying to do.

A: Your list index out of range means that your call to the split() method didn't find anything to split on.  Therefore, there wouldn't be an index 1 (no splits, only one index), causing a list index out of range error to be thrown.


text:
Q: Fancybox does not recreate the source element after postback and trigger click When triggering a fancybox click event with RegisterStartupScript after postback, the source element does not get recreated when closing the fancybox.

*

*The user opens up the fancybox with a form and submit button as content.

*The user is able to open and close the fancybox multiple times as expected if not posting the form.

*When the user hits the submit button a fancybox trigger click scripts gets injected with RegisterStartupScript in order to show the form with a confirmation message directly after the form has successfully been sent. This works as expected.

*If the user then clicks the close button of the fancybox the source element is not recreated to it's original position in the DOM. So if the user tries to open the fancybox again the content is missing and the fancybox breaks.

I expect the source element to be recreated when closing the fancybox.
Example of code:
// Form submit button
FormSubmit.Command += new CommandEventHandler(submit_command);

// Click event
protected void submit_command(object sender, CommandEventArgs e)
{

    // Do stuff

    // Trigger click event on fancybox in order to reopen the form immediately after postback
    Page page = HttpContext.Current.Handler as Page;
    ScriptManager.RegisterStartupScript(page, page.GetType(), "reopen", "$('#OpenFancy').fancybox().trigger('click');", true);
}

So the fancybox is reopened as expected but when I close the fancybox and try to open it again the fancybox breaks because the source element has not been copied back to the default position in the DOM.


text:
Q: find duplicates in range SQL I have some sort of table containing lot of numeric data:
for instance, for one of the table I have such values
    CREATE TABLE `mdacardrange` (
  `rID` decimal(20,0) NOT NULL DEFAULT '0',
 ,
  `range_begin` varchar(254) DEFAULT NULL,
  `range_end` varchar(254) DEFAULT NULL,

  PRIMARY KEY (`rID`),

);

INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (1,'4567890000000000000','4567899999999999000');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (2,'5264800000000000000','5264809999999999000');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (3,'5193060000000000000','5193069999999999000');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (4,'5482150000000000000','5482159999999999000');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (5,'5416710000000000000','5416719999999999000');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (6,'5167340000000000000','5167349999999999000');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (7,'4043090000000000000','4043099999999999000');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (8,'4043110000000000000','4043119999999999000');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (9,'4226060000000000000','4226069999999999000');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (10,'4043100000000000000','4043109999999999000');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (11,'4063710000000000000','4063719999999999000');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (12,'4098050000000000000','4098059999999999000');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (15,'4779040000000000000','4779049999999999999');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (16,'5223050000000000000','5223059999999999999');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (17,'4703770000000000000','4703779999999999000');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (18,'5483930000000000000','5483939999999999000');
INSERT INTO `mdacardrange` (`rID`,`range_begin`,`range_end`) VALUES (19,'5341480000000000000','5341489999999999999');

My task is to compare this data ranges for duplicates. Unfortunately, i don't even know how to deal with such data, as i understand, somehow i need to calculate whole ranges for each row, and then compare, can somebody help me with such issue?

A: Your CREATE TABLE contains a few typos...
I think something like this should work:
SQL> select
         a.*, b.rID as overlapped_id
     from
         mdacardrange a inner join mdacardrange b on
             a.range_begin < b.range_end and
             a.range_end > b.range_begin and
             a.rID <> b.rID
     ;


text:
Q: Why doesn't CSS support constants? CSS has never supported constants or variables directly. Whenever I'm writing code like this:
span.class1 {
  color: #377fb6;
}

div.class2 {
  border: solid 1px #377fb6; /* Repeated color */
}

I wonder why such a seemingly simple feature has never made it into the standard. What could be hard about implementing a scheme whereby we could avoid repetition, something like this:
$theme_color1: #377fb6;

span.class1 {
  color: $theme_color1;
}

div.class2 {
  border: solid 1px $theme_color1;
}

I know there are workarounds, like using a class for each color or generating CSS code from templates, but my question is: given that CSS is so rich and complex, why weren't CSS constants ever introduced?

A: Zeta's answer is quite excellent—it certainly got my upvote—but I wanted to drop a note that a Working Draft for "CSS Variables" (constants with another name) was published just ten days ago:
http://dev.w3.org/csswg/css-variables/
I wouldn't get too worked up about it as yet, since I suspect it will undergo changes and it'll be a while before support is widespread.  Still, there's at least some movement in this direction.

A:
why weren't CSS constants ever introduced?

CSS is not a programming language that's why. You could use LESS or SCSS to have variables.

A: Current status [update in Dec 2015]
The W3C issued a draft about CSS variables just one month after this answer has been edited the last time. And this month has brought that draft up to a Candidate Recommendation. It will stay in review at least until June 2016. A test suite is available.
So, all in all, CSS will have variables, also called "custom properties":

A custom property is any property whose name starts with two dashes (U+002D HYPHEN-MINUS), like --foo. The <custom-property-name>
  production corresponds to this: it's defined as any valid identifier that starts with two dashes. Custom properties are solely for use by authors and users; CSS will never give them a meaning beyond what is presented here.
Example 1
Custom properties define variables, referenced with the var() notation, which can be used for many purposes. For example, a page that consistently uses a small set of colors in its design can store the colors in custom properties and use them with variables:
:root {
  --main-color: #06c;
  --accent-color: #006;
}
/* The rest of the CSS file */
#foo h1 {
  color: var(--main-color);
}

The naming provides a mnemonic for the colors, prevents difficult-to-spot typos in the color codes, and if the theme colors are ever changed, focuses the change on one simple spot (the custom property value) rather than requiring many edits across all stylesheets in the webpage.
Unlike other CSS properties, custom property names are case-sensitive.

This feature is only implemented in Firefox and Chrome at the moment, and it will (probably) take quite some time until it's implemented in current browsers.
Old answer from 2012
This is the original answer from March 2012. It pre-dates both the "official" W3C draft and the experimental browser implementations.
Why aren't CSS variables in CSS 1 or 2?
EDIT: This was already questioned to Håkon Wium Lie, the father of CSS (Opera Watchblog (Wayback machine)):

Bernie Zimmermann: Håkon, why doesn't CSS support constants? Being able to assign an RGB value to a constant, for instance, could make stylesheet maintenance a lot more manageable. Was it just an oversight?
Hakon: No, we thought about it. True, it would have saved some typing. However, there are also some downsides. First, the CSS syntax would have been more complex and more programming-like. Second, what would be the scope of the constant? The file? The document? Why? In the end we decided it wasn't worth it.

So it's not in the standard because they thought it wasn't worth it.
Workarounds
Constants or variables as you have defined are merely placeholders. Since such a placeholder makes only sense if it's used on the same declaration it's useless as grouping already provides this mechanism:

When several selectors share the same declarations, they may be grouped into a comma-separated list.CSS2:Grouping

So instead of using a color in ten selectors, it's often better to collect common declarations and put them together. Instead of
.header{
    color: red;
}
.section:nth-of-type(2n) > .ridi.culous > .article:hover{
    color: red;
}
.footer{
    color: blue;
    border: 1px solid blue;
}

use
/* Color definitions */
.header,
.section:nth-of-type(2n) > .ridi.culous > .article:hover{
    color: red;
}

.footer{
    color: blue;
}

/* border definitions */
.footer{
    border: 1px solid;
}

Also use inheritance whenever possible.
Note that you can declare almost some kind of variable if you're using abstract/simple classes like
.margin5em{
    margin: 5em;
}
.corporateIdentityBackgroundColor{
    background-color: #881200;
}
.corporateIdentityBackgroundImage{
    background-image: url(we/are/awesome/corporation);
}
.backgroundCenter{
    background-position: center center;
}
.backgroundNoRepeat{
    background-repeat: no-repeat;
}

This will enable you to use

Ridiculos long class names

Yesterday I found a new hobby: Creating class names that are longer then most common words.

See also:

*

*http://icant.co.uk/articles/cssconstants/

A: There's an argument for Colour Constants (we have a handful of predefined colour constants already anyway).  Variables however lead to If statements, If statements lead to Functions, Functions lead to Javascript (and doobies).
Though this article shows exactly how unnecessary a colour constant is in reality.  If you're planning on making a theme colour place all your theme colour declarations in one statement, or as has been mentioned make a class just for your theme colour.  The former does require splitting the selector definition however which doesn't smell nice, and the latter does seem extraneous when you already have a class applied to the tag.
I see no need for other Constants in a well designed sheet.  Numerous dimensional repetition indicates poor structure/design.


text:
Q: Enzyme, how to find a child of wrapper by attribute? I have the following React component in a Redux application.
<Modal>
<Modal.Header closeButton onClick={props.onHide}>
    <Modal.Title>A Sample Modal</Modal.Title>
</Modal.Header>
<Modal.Body>
</Modal.Body>

Now, in my test code, I have the following
const wrapper = mount(<modal/>);
const closeButton = wrapper.find("['closeButton']");
expect(closeButton.length).to.equal(1); // error - expected 0 to be 1

But the selector does not find the close button. Help?
update: I am using the React Modal library, and the contents of the HTML seem to change.

A: Just giving a prop without value to a component is equivalent to prop={true}. Thus you should be able to use an Enzyme object property selector to find the element like this:
const closeButton = wrapper.find({ closeButton: true });

A: I think ['closeButton'] is not a valid selector. It should be [closeButton] without the '
e.g. if you try document.querySelector("['closeButton']") the browser will complain. While document.querySelector("[closeButton]") is executed correctly.


text:
Q: Use a docker container as a proxy to use a VPN Because of this problem, I'm not able to use the VPN on my host machine and have access to the internet on the containers at the same time. To solve the problem, I want to run a container with access to the VPN and redirect requests from my host to this container.
Disclaimer : I'm not a network manager and I don't understand completly everything.
I was able to use the VPN inside a container by using stono/ike. My idea was to use socat to redirect requests. Here is the command is use :
docker run --rm -it --privileged -v ~/.ike/sites:/sites --userns host stono/ike typ username password # run the container
docker inspect <container-id> | grep IPAddress # To get the IP address of the container
sudo socat UDP-LISTEN:500,fork,reuseaddr UDP:172.17.0.2:500 # redirects the port 500
sudo socat UDP-LISTEN:4500,fork,reuseaddr UDP:172.17.0.2:4500 # redirects the port 4500

All commands succed but I still not able to have access to the VPN with my host machine.
So, what can I do? Am I on the good way and what's the solution?


text:
Q: Deactivate automatic mark as read in Apple Mail 7.3 I just changed from Windows to OS X Mavericks with Apple Mail App 7.3. The first thing I'm wondering about is that I cannot disable the automation to mark an email as read by default when I just clicked on it. Is there any way to do so?
I found TruePreview. But the tool does not support Mail 7.3 any more. Another solution would be to use a different mail client like Thunderbird. But there I miss the integration of the address book and the synchronisation with my iPhone and iPad.

A: I've been using Mail Act-On. It's overkill (does a lot more than just keep messages unread) and kind of pricey at $30 (with free trial), but since it's a paid app, they keep it up to date. Even when TruePreview was being maintained, it'd sometimes be weeks or months before it was updated to work with the latest version of OS X.

A: Use the standard keyboard shortcut, cmd+shift+u to toggle between "read" and "unread". You can also go to System Preferences → Keyboard to customise your own keyboard shortcut.


text:
Q: Creating the optimum index for my database I have a table in postgresql with the following information:
rawData (fileID integer references otherTable, lineNum integer, data1 double, ...)

When I am searching this table, I do so with the following query:
SELECT lineNum, data1, ...other data FROM rawData WHERE
fileID = ? AND data1 < ? ORDER BY lineNum;

In general, the data in this table is a number of entries for each fileID, and each fileID has lineNum from 0 to x, with lineNum never repeating for each fileID (but it does repeat for different fileID's).  Then data1 is effectively a random number that may or may not overlap.
In order to speed up the reading of this data, I am trying to create an index on it, but am having trouble figuring out the best way to index it.  Currently I am looking at one of the following two index methods, and am wondering which would be better for my search, or if there is another option that I haven't thought of that would be better than either of them.
index idea 1:
CREATE INDEX searchIndex ON rawData (fileID, data1, lineNum);

index idea 2:
CREATE INDEX searchIndex ON rawData (fileID, lineNum, data1);

Note that at this time, this and a search not constrained by data1 are the only searches that I run on this table, so I'm not too concerned about this index slowing down other searches.
Lastly, would I have to change my search query to use the index, or would it automatically use that index when I search the table?

A: You should look at using this instead:
CREATE INDEX searchIndex ON rawData (fileID, lineNum);

A few things:

*

*In particular, as per docs, Indexes with more than three columns are unlikely to be helpful unless the usage of the table is extremely stylized.

*Since your second search query requires filtering without the data1 column, keeping the second column lineNum should be sufficient (since you mention it would be quasi-random), and in the rare occurrence that there are repeats, table fetches should ensure correctness. But what this would mean is that the Index would be 1/3rd smaller in size, which is a big win (Think index small-enough to be in memory / index-only-scans etc.)

A: Either index can be used.  Which is faster will depend on many things, like how many rows are in the table, how many lineNum there are per fileID, how selective the data1 < ? clause is, what your hardware is, what our config settings are, which version of PostreSQL you are using, what physical order the table rows lie in, etc.
The only way to know for sure is to try it with your own data on your own system and see.
I'd just build an index on (fileID, lineNum, data1), or even just (fileID, lineNum), because that seems more natural, and then forget about it.  Most likely it will be fast enough.  Once there is a demonstrable performance problem, than you will have the test case at hand which is needed to come to a real conclusion.


text:
Q: The textbook's way of deriving a natural deduction proof of $\vdash((\phi\leftrightarrow\psi)\leftrightarrow\phi)$ feels wrong. The problem is
"Show that if we have a derivation $D$ of $\psi$ with no undischarged assumptions, then we can use it to construct, for any statement $\phi$, a derivation of $((\phi\leftrightarrow\psi)\leftrightarrow\phi)$ with no undischarged assumptions."
Here is my solution.

Below is the textbook's solution.

As you can see on the textbook solution, $\phi$ and $\psi$ cross over to another branch to introduce $\rightarrow$. The textbook didn't mention it was possible. Is the textbook solution a correct derivation of the proof?
Update 1 : I want to solve exercises with what the author explicitly allowed in the textbook. The author wrote:

A: There's no crossing over.   On one branch $\psi$ is true from the derivation (D).   On the other branch, $\phi$ is assumed, then later discharged.
It is just making use of an unusual form of conditional introduction; if something is true, then anything will imply it is true.   $p\vdash (q\to p)$
Where as the usual form is the deduction theorem: $(p\vdash q)\vdash p\to q$
$$\begin{array}{l|l:l}
1 & \psi & D\vdash \psi
\\
2 & \phi\to \psi & 1, {\to}\mathsf I
\\ \hdashline
3 & \quad \phi & \textsf{Assume }\phi
\\
4 & \quad \psi\to \phi & 3,{\to}\mathsf I
\\
5 & \quad \phi\leftrightarrow \psi & 2, 4, {\leftrightarrow}\mathsf I
\\ \hline
6 & \phi \to (\phi\leftrightarrow \psi) & 5, {\to}\mathsf I~ (\textsf{DT Discharges Assumption of }\phi)
\end{array}$$
$$\require{enclose}\require{cancel}\enclose{circle}{A}\dfrac{\dfrac{\dfrac{\dfrac{D}{\psi}}{\phi\to\psi}{{\to}\mathsf I}\quad\dfrac{\cancel[color=red]{\color{blue}\phi}^{\enclose{circle}A}}{\psi\to\phi}{{\to}\mathsf I}}{\phi\leftrightarrow\psi}{{\leftrightarrow}\mathsf I}}{\color{blue}\phi\to(\phi\leftrightarrow\psi)}{{\to}\textsf{I (DT)}}$$

A: There is no error; an allowed way to use $\to$-intro is to discharge a "non-existent" assumption, i.e.:

$\psi \vdash \phi \to \psi$,

as in the two top-right branches.
This corresponds to the fact that $\psi \to (\phi \to \psi)$ is a tautology; thus, assuming $\psi$, by modus ponens $(\phi \to \psi)$ follows, for $\phi$ whatever.
See the textbbok's comment on the rule, page 17:

The rule is still correctly applied if we do not discharge all of them; in fact the rule is correctly applied even if $\phi$ is not an assumption of $D$ at all, so that there is nothing to discharge. Example 2.4.4 (page 19) will illustrate these points.


text:
Q: PySpark DataFrames - way to enumerate without converting to Pandas? I have a very big pyspark.sql.dataframe.DataFrame named df.
I need some way of enumerating records- thus, being able to access record with certain index. (or select group of records with indexes range)
In pandas, I could make just
indexes=[2,3,6,7]
df[indexes]

Here I want something similar, (and without converting dataframe to pandas)
The closest I can get to is:

*

*Enumerating all the objects in the original dataframe by:
indexes=np.arange(df.count())
df_indexed=df.withColumn('index', indexes)

*

*Searching for  values I need using where() function.

QUESTIONS:

*

*Why it doesn't work and how to make it working? How to add a row to a dataframe?

*Would it work later to make something like:
 indexes=[2,3,6,7]
 df1.where("index in indexes").collect()

*Any faster and simpler way to deal with it?

A: from pyspark.sql.functions import monotonically_increasing_id
df.withColumn("Atr4", monotonically_increasing_id())

If you only need incremental values (like an ID) and if there is no
  constraint that the numbers need to be consecutive, you could use
  monotonically_increasing_id(). The only guarantee when using this
  function is that the values will be increasing for each row, however,
  the values themself can differ each execution.

A: It doesn't work because:

*

*the second argument for withColumn should be a Column not a collection. np.array won't work here

*when you pass "index in indexes" as a SQL expression to where indexes is out of scope and it is not resolved as a valid identifier

PySpark >= 1.4.0
You can add row numbers using respective window function and query using Column.isin method or properly formated query string:
from pyspark.sql.functions import col, rowNumber
from pyspark.sql.window import Window

w = Window.orderBy()
indexed = df.withColumn("index", rowNumber().over(w))

# Using DSL
indexed.where(col("index").isin(set(indexes)))

# Using SQL expression
indexed.where("index in ({0})".format(",".join(str(x) for x in indexes)))

It looks like window functions called without PARTITION BY clause move all data to the single partition so above may be not the best solution after all.

Any faster and simpler way to deal with it?

Not really. Spark DataFrames don't support random row access.
PairedRDD can be accessed using lookup method which is relatively fast if data is partitioned using HashPartitioner. There is also indexed-rdd project which supports efficient lookups.
Edit:
Independent  of PySpark version you can try something like this:
from pyspark.sql import Row
from pyspark.sql.types import StructType, StructField, LongType

row = Row("char")
row_with_index = Row("char", "index")

df = sc.parallelize(row(chr(x)) for x in range(97, 112)).toDF()
df.show(5)

## +----+
## |char|
## +----+
## |   a|
## |   b|
## |   c|
## |   d|
## |   e|
## +----+
## only showing top 5 rows

# This part is not tested but should work and save some work later
schema  = StructType(
    df.schema.fields[:] + [StructField("index", LongType(), False)])

indexed = (df.rdd # Extract rdd
    .zipWithIndex() # Add index
    .map(lambda ri: row_with_index(*list(ri[0]) + [ri[1]])) # Map to rows
    .toDF(schema)) # It will work without schema but will be more expensive

# inSet in Spark < 1.3
indexed.where(col("index").isin(indexes))

A: If you want a number range that's guaranteed not to collide but does not require a .over(partitionBy()) then you can use monotonicallyIncreasingId().
from pyspark.sql.functions import monotonicallyIncreasingId
df.select(monotonicallyIncreasingId().alias("rowId"),"*")

Note though that the values are not particularly "neat". Each partition is given a value range and the output will not be contiguous. E.g. 0, 1, 2, 8589934592, 8589934593, 8589934594.
This was added to Spark on Apr 28, 2015 here: https://github.com/apache/spark/commit/d94cd1a733d5715792e6c4eac87f0d5c81aebbe2

A: You certainly can add an array for indexing, an array of your choice indeed:
In Scala, first we need to create an indexing Array:
val index_array=(1 to df.count.toInt).toArray

index_array: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

You can now append this column to your DF. First, For that, you need to open up our DF and get it as an array, then zip it with your index_array and then we convert the new array back into and RDD. The final step is to get it as a DF:
final_df = sc.parallelize((df.collect.map(
    x=>(x(0),x(1))) zip index_array).map(
    x=>(x._1._1.toString,x._1._2.toString,x._2))).
    toDF("column_name")

The indexing would be more clear after that.

A: monotonicallyIncreasingId() - this will assign row numbers in incresing order but not in sequence.
sample output with 2 columns:
|---------------------|------------------|
|      RowNo          |     Heading 2    |
|---------------------|------------------|
|          1          |         xy       |
|---------------------|------------------|
|          12         |         xz       |
|---------------------|------------------|
If you want assign row numbers use following trick.
Tested in spark-2.0.1 and greater versions.
df.createOrReplaceTempView("df")
dfRowId = spark.sql("select *, row_number() over (partition by 0) as rowNo from df")
sample output with 2 columns:

|---------------------|------------------|
|      RowNo          |     Heading 2    |
|---------------------|------------------|
|          1          |         xy       |
|---------------------|------------------|
|          2          |         xz       |
|---------------------|------------------|

Hope this helps.

A: Selecting a single row n of a Pyspark DataFrame, try:
df.where(df.id == n).show()

Given a Pyspark DataFrame:
df = spark.createDataFrame([(1, 143.5, 5.6, 28, 'M', 100000),\
                          (2, 167.2, 5.4, 45, 'M', None),\
                          (3, None , 5.2, None, None, None),\
                          ], ['id', 'weight', 'height', 'age', 'gender', 'income'])

Selecting the 3rd row, try:
df.where('id == 3').show()

Or:
df.where(df.id == 3).show()

Selecting multiple rows with rows' ids (the 2nd & the 3rd rows in this case), try:
id = {"2", "3"}
df.where(df.id.isin(id)).show()


text:
Q: "The target database schema provider could not be determined" With VSDBCMD but Only When /ConnectionString is Specified I have been developing a deployment script to deploy our database project to multiple database instances. I'm testing it by running it manually. It is a very simple script, and just runs VSDBCMD against a deployment manifest created to deploy our base, or template database. In order to deploy to different databases on the same server, the script uses the deployment manifest, but then also specifies the /p:DatabaseName and /p:TargetDatabase properties.
This has been working all day.
We are using SQL Server authentication for these databases, and I wanted to be able to specify the username and password as parameters to the script, so that they wouldn't have to be hardcoded. The only way I could see to do that was to use the /ConnectionString switch. That's what caused the failure. Even when I specify the exact same connection string as is stored in the deployment manifest, the script fails with the error "The target database schema provider could not be determined". The script:
function DeployDatabase([string] $manifestPath, [string] $password, [string] $instance, [string] $server, [string] $user)
{
    $vsdbcmdPath = "c:\Program Files (x86)\Microsoft Visual Studio 10.0\VSTSDB\Deploy"
    $vsdbcmd = "$vsdbcmdPath\vsdbcmd.exe"
    $outputScriptPath = "$instance.sql"
    $logPath = "$instance.log"
    $connectionString = "Data Source=$server;User ID=$user;"
    & $vsdbcmd /dd /dsp:SQL /manifest:$manifestPath /a:Deploy /p:DatabaseName=$instance /p:TargetDatabase=$instance /script:$outputScriptPath /cs:"$connectionString" |
        Out-File -FilePath $logPath
}

# Actual call is omitted to protect the $server, $user and $password

Simply omitting the /cs switch allows this to succeed again. Note from the connection string, above, that it's not even necessary to specify the password in the connection string in order to cause a failure.
The target database server is running SQL Server 2008 R2, and is up to date on patches.
I'd like to know how to avoid this error, or else I'd like to know a better way to specify the username and password when deploying, without requiring the password to be in the deployment  manifest in cleartext.

A: I am having the same issue. Did you try to set the instance name?
The SQL Instance name in the connection string could be wrong.
Also doublecheck if User Id and Password are set, if you are not using Integrated Security.


text:
Q: Why this proof cannot be extended to any complex operator? I will transcript this theorem, together with it proof, taken from Linear algebra done right, third edition of Axler.
Below $T_{\Bbb C}$ is the complexification of some operator $T$ in a finite-dimensional real vector space $V$. This mean that if $T\in\mathcal L(\Bbb R^n)$ then $T_{\Bbb C}\in\mathcal L(\Bbb C^n)$, where $\Bbb C^n\cong \Bbb R^n+i\Bbb R^n$.

Theorem: suppose $V$ is a real finite-dimensional vector space and $T\in\mathcal L(V)$, $\lambda\in\Bbb C$, $j$ is a non-negative integer and $u,v\in V$. Then $$(T_{\Bbb C}-\lambda I)^j(u+iv)=0\iff (T_{\Bbb C}-\bar\lambda I)^j(u-iv)=0$$
Proof: We will use induction on $j$. For $j=0$ the statement is equiavlent to say that if $u+iv=0$ then $u-iv=0$, what clearly holds. Thus assume that the statement holds for some $j-1$ with $j\ge 1$.
Now suppose that $(T_{\Bbb C}-\lambda I)^j(u+iv)=0$. Then $$(T_{\Bbb C}-\lambda I)^{j-1}\big((T_{\Bbb C}-\lambda I)(u+iv)\big)=0\tag1$$
Writing $\lambda=a+ib$ for $a,b\in\Bbb R$ we have $$(T_{\Bbb C}-\lambda I)(u+iv)=(Tu-av+bu)+i(Tu-av-bu)\tag2$$ and $$(T_{\Bbb C}-\bar\lambda I)(u+iv)=(Tu-av+bu)-i(Tu-av-bu)\tag3$$ The induction hypothesis, $(1)$ and $(2)$ imply that $$(T_{\Bbb C}-\bar\lambda I)^{j-1}\big((Tu-av+bu)-i(Tu-av-bu)\big)=0\tag4$$
Thus $(3)$ and $(4)$ imply that $(T_{\Bbb C}-\bar\lambda I)^j(u-iv)=0$ completing the proof in one direction. The other direction is proven replacing $\lambda$ by $\bar\lambda$ and $v$ by $-v$ and then using the first direction.$\square$

My question is the following: from the above can be seen that if $\lambda$ is an eigenvalue for $T_{\Bbb C}$ then $\bar\lambda$ is also an eigenvalue for $T_{\Bbb C}$, thus the non-real eigenvalues of $T_{\Bbb C}$ comes in pairs.
However it also can be seen easily (by example for the operator $iI\in\mathcal L(\Bbb C)$) that the non-real eigenvalues of an operator on a complex vector space doesnt necessarily comes paired with it conjugate. However from the above theorem and proof it seems that the same result can be applied to any complex operator.
Can someone enlighten me and show me why the above proof will fail for complex operators $T\in\mathcal L(\Bbb C^n)$? Im unable to see why the above proof only holds for complexified real operators. We cannot substitute in the above proof $T_{\Bbb C}$ for any other undefined complex operator in $\Bbb C^n$ and the induction still holds?


text:
Q: Decode seemingly malformed utf8 representation of Unicode pointer from Facebook data export Similar to in this post, is there a way to decode some of the seemingly malformed UTF-8 data returned from downloading a copy of my Facebook data?
Looking at a particular example, in one of my chats I have a sent message containing only the emoji . Opening the message_1.json file with vim and looking at the appropriate entry shows the text "\u00f0\u009f\u0092\u008e". However this differs from the view from my terminal (Mac OSX)
$ jq '.messages[0].content' message_1.json
"ð"  # stackoverflow seems to be truncating this string, there are 3 extra chars which show as spaces
$ jq '.messages[0].content' message_1.json > utf
$ cat utf
"ð"
$ od -h utf
0000000      c322    c2b0    c29f    c292    228e    000a
0000013
$ wc utf
       1       1      11 utf

This also differs the output from directly pasting the emoji into a file
$ echo '' > gem.txt
$ cat gem.txt

$ od -h gem.txt
0000000      9ff0    8e92    000a
0000005
$ wc gem.txt
       1       1       5 gem.txt

And I get seemingly different information when reading in these two files with python3
$ python3
Python 3.7.3 (default, Dec 13 2019, 19:58:14)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> with open('gem.txt', 'r') as f:
...   gem = f.read()
...
>>> gem
'\n'
>>> len(gem)
2
>>> ord(gem[0])
128142
>>>
>>>
>>> with open('utf', 'r') as f:
...   utf = f.read()
...
>>> utf
'"ð\x9f\x92\x8e"\n'
>>> len(utf)
7
>>> for char in utf:
...   print(ord(char))
...
34
240
159
146
142
34
10
>>>

I have a few questions based on this behavior:

*

*Is the data returned by Facebook encoded incorrectly? This page shows the proper Unicode pointer for the gem emoji to be U+1F48E, and the corresponding UTF-8 0xF0 0x9F 0x92 0x8E representation matches with the byte output from od

*Is there a way for me to parse the returned string from Facebook? It seems that the previous question recommends a regular expression to transform the text before doing so, is this required?

*The gem.txt had a length of 5 bytes, and subtracting the newline, 4 bytes to represent the emoji. This makes sense to me as its UTF-8 representation requires 4 bytes. Why does the utf document list 11 bytes (presumably 10 without the newline)?

A: It looks like the content of your JSON file indeed got mojibaked, ie. misinterpreted with the wrong encoding.
>>> import json
>>> # That's how it should look:
>>> print(json.dumps(''))
"\ud83d\udc8e"
>>> # That's what you got:
>>> mojibaked = ''.encode('utf8').decode('latin1')
>>> print(json.dumps(mojibaked))
"\u00f0\u009f\u0092\u008e"

Check if you can fix how the JSON file is created.
Latin-1 is the default in some tools/protocols.
The convenient thing is that you can always decode any stream of bytes as Latin-1 without exceptions.
It might corrupt your input though, as happens here.
If you can't fix the source, you might be able to recover by doing the encoding round-trip in reverse:
>>> mojibaked = json.loads('"\\u00f0\\u009f\\u0092\\u008e"')
>>> mojibaked
'ð\x9f\x92\x8e'
>>> mojibaked.encode('latin1').decode('utf8')
''


text:
Q: Embedding a Video in PowerPoint Youtube provided the following code for a video I would like to embed in a presentation:
<iframe width="560" height="315" src="//www.youtube.com/embed/L6gtOVDG68g" frameborder="0" allowfullscreen></iframe>
However, powerpoint keeps giving me the error that it "cannot insert a video from this embed code."  Is there an error in the code that youtube provided?

A: Usually to embed video from YouTube into a slide, it's best to download the YouTube Wizard plug in (here). After you do that there will be an "Insert YouTube video" command on your toolbar.
However, you'd probably be better off downloading the video and embedding it from inside PowerPoint and choosing Insert – > Movie – > Movie from file to put the video into the current slide. That way you don't need connection to the internet.


text:
Q: Как отправить форму несколько раз? Как отправить форму несколько раз с разными данными?
Есть форма:
<form id="form" action="send.php" method="post">
    <input id="name" name="name">
    <input id="phone" name="phone">
</form>

Есть массив, который содержит в себе разные name и phone.
Как сделать так, чтобы пока не закончились данные в массиве, на каждой итерации цикла, отправлялась форма с новыми данными?
form = document.getElementById('form')
for (var i = 0; i < newArr.length; i++) {
   document.getElementById('name').value=newArr[i].name
   document.getElementById('phone').value=newArr[i].phone
   form.submit()
}

A: <form id="form" action="send.php" method="post" target="myframe">
    <input id="name" name="name">
    <input id="phone" name="phone">
</form>
<iframe name="myframe" src="about:blank" style="display:none;"></iframe>


text:
Q: Split a string ignoring quoted sections Given a string like this:

a,"string, with",various,"values, and some",quoted

What is a good algorithm to split this based on commas while ignoring the commas inside the quoted sections?
The output should be an array:

[ "a", "string, with", "various", "values, and some", "quoted" ]

A: Python:
import csv
reader = csv.reader(open("some.csv"))
for row in reader:
    print row

A: Looks like you've got some good answers here.
For those of you looking to handle your own CSV file parsing, heed the advice from the experts and Don't roll your own CSV parser.
Your first thought is, "I need to handle commas inside of quotes."
Your next thought will be, "Oh, crap, I need to handle quotes inside of quotes. Escaped quotes. Double quotes. Single quotes..."
It's a road to madness. Don't write your own. Find a library with an extensive unit test coverage that hits all the hard parts and has gone through hell for you. For .NET, use the free FileHelpers library.

A: Of course using a CSV parser is better but just for the fun of it you could:
Loop on the string letter by letter.
    If current_letter == quote :
        toggle inside_quote variable.
    Else if (current_letter ==comma and not inside_quote) :
        push current_word into array and clear current_word.
    Else
        append the current_letter to current_word
When the loop is done push the current_word into array

A: If my language of choice didn't offer a way to do this without thinking then I would initially consider two options as the easy way out:

*

*Pre-parse and replace the commas within the string with another control character then split them, followed by a post-parse on the array to replace the control character used previously with the commas.

*Alternatively split them on the commas then post-parse the resulting array into another array checking for leading quotes on each array entry and concatenating the entries until I reached a terminating quote.
These are hacks however, and if this is a pure 'mental' exercise then I suspect they will prove unhelpful.  If this is a real world problem then it would help to know the language so that we could offer some specific advice.

A: The author here dropped in a blob of C# code that handles the scenario you're having a problem with:
CSV File Imports in .Net
Shouldn't be too difficult to translate.

A:
What if an odd number of quotes appear
  in the original string?

This looks uncannily like CSV parsing, which has some peculiarities to handling quoted fields. The field is only escaped if the field is delimited with double quotations, so:

field1, "field2, field3", field4, "field5, field6" field7

becomes

field1
field2, field3
field4
"field5
field6" field7

Notice if it doesn't both start and end with a quotation, then it's not a quoted field and the double quotes are simply treated as double quotes.
Insedently my code that someone linked to doesn't actually handle this correctly, if I recall correctly.

A: Here's a simple python implementation based on Pat's pseudocode:
def splitIgnoringSingleQuote(string, split_char, remove_quotes=False):
    string_split = []
    current_word = ""
    inside_quote = False
    for letter in string:
      if letter == "'":
        if not remove_quotes:
           current_word += letter
        if inside_quote:
          inside_quote = False
        else:
          inside_quote = True
      elif letter == split_char and not inside_quote:
        string_split.append(current_word)
        current_word = ""
      else:
        current_word += letter
    string_split.append(current_word)
    return string_split

A: I use this to parse strings, not sure if it helps here; but with some minor modifications perhaps?
function getstringbetween($string, $start, $end){
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0) return "";
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);
}

$fullstring = "this is my [tag]dog[/tag]";
$parsed = getstringbetween($fullstring, "[tag]", "[/tag]");

echo $parsed; // (result = dog)

/mp

A: Here's a simple algorithm:

*

*Determine if the string begins with a '"' character

*Split the string into an array delimited by the '"' character.

*Mark the quoted commas with a placeholder #COMMA#

*

*If the input starts with a '"', mark those items in the array where the index % 2 == 0

*Otherwise mark those items in the array where the index % 2 == 1

*Concatenate the items in the array to form a modified input string.

*Split the string into an array delimited by the ',' character.

*Replace all instances in the array of #COMMA# placeholders with the ',' character.

*The array is your output.

Heres the python implementation:
(fixed to handle '"a,b",c,"d,e,f,h","i,j,k"')
def parse_input(input):

    quote_mod = int(not input.startswith('"'))

    input = input.split('"')
    for item in input:
        if item == '':
            input.remove(item)
    for i in range(len(input)):
        if i % 2 == quoted_mod:
            input[i] = input[i].replace(",", "#COMMA#")

    input = "".join(input).split(",")
    for item in input:
        if item == '':
            input.remove(item)
    for i in range(len(input)):
        input[i] = input[i].replace("#COMMA#", ",")
    return input

# parse_input('a,"string, with",various,"values, and some",quoted')
#  -> ['a,string', ' with,various,values', ' and some,quoted']
# parse_input('"a,b",c,"d,e,f,h","i,j,k"')
#  -> ['a,b', 'c', 'd,e,f,h', 'i,j,k']

A: This is a standard CSV-style parse. A lot of people try to do this with regular expressions. You can get to about 90% with regexes, but you really need a real CSV parser to do it properly. I found a fast, excellent C# CSV parser on CodeProject a few months ago that I highly recommend!

A: Here's one in pseudocode (a.k.a. Python) in one pass :-P
def parsecsv(instr):
    i = 0
    j = 0

    outstrs = []

    # i is fixed until a match occurs, then it advances
    # up to j. j inches forward each time through:

    while i < len(instr):

        if j < len(instr) and instr[j] == '"':
            # skip the opening quote...
            j += 1
            # then iterate until we find a closing quote.
            while instr[j] != '"':
                j += 1
                if j == len(instr):
                    raise Exception("Unmatched double quote at end of input.")

        if j == len(instr) or instr[j] == ',':
            s = instr[i:j]  # get the substring we've found
            s = s.strip()    # remove extra whitespace

            # remove surrounding quotes if they're there
            if len(s) > 2 and s[0] == '"' and s[-1] == '"':
                s = s[1:-1]

            # add it to the result
            outstrs.append(s)

            # skip over the comma, move i up (to where
            # j will be at the end of the iteration)
            i = j+1

        j = j+1

    return outstrs

def testcase(instr, expected):
    outstr = parsecsv(instr)
    print outstr
    assert expected == outstr

# Doesn't handle things like '1, 2, "a, b, c" d, 2' or
# escaped quotes, but those can be added pretty easily.

testcase('a, b, "1, 2, 3", c', ['a', 'b', '1, 2, 3', 'c'])
testcase('a,b,"1, 2, 3" , c', ['a', 'b', '1, 2, 3', 'c'])

# odd number of quotes gives a "unmatched quote" exception
#testcase('a,b,"1, 2, 3" , "c', ['a', 'b', '1, 2, 3', 'c'])

A: I just couldn't resist to see if I could make it work in a Python one-liner:
arr = [i.replace("|", ",") for i in re.sub('"([^"]*)\,([^"]*)"',"\g<1>|\g<2>", str_to_test).split(",")]

Returns ['a', 'string, with', 'various', 'values, and some', 'quoted']
It works by first replacing the ',' inside quotes to another separator (|),
splitting the string on ',' and replacing the | separator again.

A: Since you said language agnostic, I wrote my algorithm in the language that's closest to pseudocode as posible:
def find_character_indices(s, ch):
    return [i for i, ltr in enumerate(s) if ltr == ch]

def split_text_preserving_quotes(content, include_quotes=False):
    quote_indices = find_character_indices(content, '"')

    output = content[:quote_indices[0]].split()

    for i in range(1, len(quote_indices)):
        if i % 2 == 1: # end of quoted sequence
            start = quote_indices[i - 1]
            end = quote_indices[i] + 1
            output.extend([content[start:end]])

        else:
            start = quote_indices[i - 1] + 1
            end = quote_indices[i]
            split_section = content[start:end].split()
            output.extend(split_section)

        output += content[quote_indices[-1] + 1:].split()

    return output


text:
Q: Invoking a functions based on string name in java I need a logic to replace the following code.
 void invokeMethod(String action){
    if ("echo".equals(action)) {
         //call echo
         echo();
    }
    else if ("dump".equals(action)) {
         // call dump
         dump();
    }
    ... goes on
}

switch case with string parameter won't work in java 1.6.
Can I do it a better way ?

A: I used a java hashmap with action as key and random integer as value. Whenever perticular action is asked to invoke, fetch the integer from the hashmap and use switch case now (In above problem, string comparison was very operation, replaced the same with integers).


text:
Q: Decrypt method throws undefined on Buffer node package with xxtea.js we have been using xxtea-node npm package for encryption and decryption, as we can see the plugin is depended on Buffer node package, but during the decryption process, it throws Undefined error as below.
Environment :
Node : V14.17.3,
NPM : 6.14.13,
Encryption plugin : xxtea-nodejs
Decyption method which throwing error :
function decrypt(data, key) {
    if (typeof data === 'string') data = new Buffer(data, 'base64'); //This line throws Undefined error
    if (typeof key === 'string') key = toBytes(key);
    if (data === undefined || data === null || data.length === 0) {
        return data;
    }
    return toUint8Array(decryptUint32Array(toUint32Array(data, false), toUint32Array(fixk(key), false)), true);
}

In the Decrypt method new Buffer line is throwing "ReferenceError: Buffer is not defined", but if I replace this line with the following line it works fine require('buffer/').Buffer.from()
Whats the difference between both and how to fix the first said issue?


text:
Q: What is the performance impact of having many unused CSS selectors/rules? How much time/space does removing unused CSS selectors save? Is there a way for me to measure that on different web browsers?

A: The only real impact will come from the css file size being slightly larger, resulting in longer download and parse times.
But for the most part, there are a few million other things with much bigger impact.


text:
Q: Random reboots macbook pro late 2008 I have a macbok pro late 2008 , running the latest OS apple will allow - el capitan.
I have 2 sticks of 2GB RAM. This is above the original specs but due to a firmware upgrade some years ago, it now works with 4GB of RAM
My mbp reboots no more than twice a day, usually averaging once a day or day and half.
I had a lemon of a battery before that swelled like crazy and bent the flimsy alumimum cover. I now have a replacement battery.
My theory is that the problem is down to one of 3 things but these are just theories I'm not mac expert. So I'm here to find out what likely is the real cause...

*

*contacts for the battery shorting out occasionally

*faulty battery

*RAM problems, unfortunately I never had any success before on any other computer with ram testers so i don't think running one is going to help here. They even say so on the internet, they can prove defective ram if they spot it, but if not - maybe it's defective, maybe not. That said swapping out the ram and testing each stick would mean I would need to run a week on each stick. Because it is basically guaranteed to fail in a week but a couple of days of uptime in inconclusive. I count uptime to include sleep mode.

Which brings me my "smoking gun" question... I believe this will pinpoint the problem once someone knowledgeable about macs and hardware reads this.
The reboot problem will occur even when in sleep mode. Or hibernating mode. Ok not sure about actual sleep but when you choose sleep and go to hibernating - i.e. it has to restore from disk later. Sometimes coming out of it will restore state, sometimes it will do a fresh bootup.
And of course it can reboot at any time during normal operation. Reboot might be too strong a word, i think it just turns off.
So what does that indicate? would that be ram problem or a battery problem?

A: Troubleshooting is often a process of elimination, so patience is often required. There's quite a few things you could do to try and narrow things down, because even from the info you've provided the cause could be RAM, your battery, or something else altogether.
For example, if it works fine in Safe Mode then it's more likely to be some sort of software issue/conflict.
To start with I'd do a NVRAM and SMC reset (in that order) as there's really no harm in trying that first. Before following the steps below, ensure you have no external hardware connected and that you're using the built-in keyboard.
Reset the NVRAM
Reset the NVRAM on your MBP as follows:

*

*Shut down your machine. Yes, a full shut down, not just logging out.

*Press the power button and then press the commandoptionpr keys. You have to make sure you press these keys before the gray screen appears or it won't work.

*Hold those keys down until your MBP reboots again and you here the startup chime a second time.

*Let go of the keys and let your MBP reboot normally.

Note: When you log back in you may need to readjust some of your system preferences (e.g. speaker volume, screen resolution, startup disk selection, time zone information, etc).
Reset the SMC
To reset the SMC on your model MBP, follow these steps:

*

*Shut down your MBP

*Disconnect the MagSafe plug (power cable) from the computer

*Remove the battery

*Press the power button for 5 seconds and release

*Put the battery back in

*Reconnect the MagSafe cord (or power cable)

*Turn your computer back on with the power button

After resetting both the NVRAM and SMC, use your computer to determine if the issue still persists. If it does, I'd test your hardware as with Apple Hardware Test.
Run Apple Hardware Test
Your model MBP uses Apple Hardware Test. To use this, follow these steps:

*

*Shut down your MacBook Pro

*Restart your MacBook Pro

*Press and hold the D key before the gray startup screen appears.

*After a while, Apple Hardware Test (AHT) will start.

*When prompted, select your language and click the right arrow.

*When the AHT console appears, you can choose to run Basic tests by clicking the Test button. However, I suggest you select the "Perform extended testing" checkbox before you click the Test button.

*Your test results will appear in the window in the bottom-right of the console.

Note 1: that the extended test will take some time. Take a note of the results and report back.
Note 2: If pressing and holding the D key at Step 3 doesn't work, start again at Step 1 and, at Step 3 press and hold both the OptionD keys instead. This will try and run diagnostics from the internet instead, so you will need to allow more time for it to complete.
If your MBP passes all hardware tests, then I'd try using it in Safe Mode.
Boot into Safe Mode
Follow these steps to boot your MBP into Safe Mode:

*

*Fully shut down your Mac

*Restart your Mac

*Immediately press the Shift key and keep it down

*Let go of the Shift key when you see the login window (NOTE: If you have FileVault enabled you may need to log in twice).

*Take a note of what happens (i.e. can you use it without it restarting)

*Exit Safe Mode by restart your Mac as normal and test again

If you find that your MBP works fine while in Safe Mode, but not when booted normally, then let me know and I'll explain the process of identifying the culprit (it's likely to be a login item, corrupted font, or kernel extension).

A: The mac usually reboots when encountering a problem. Like windows it restarts when the OS can't recover from it. Apple suggests that you keep your mac up to date to avoid anymore of these problems.
Apple suggests that also this occurs due to certain software.
Not saying that it's kernel panic that's causing your mac to spontaneously restart but it's a possibility.
I've encountered a kernel panic problem and I just went ahead and deleted somethings I've installed that looked like it was causing the panics since the problem occurred.


text:
Q: Dynamically interpolate extra rows in SQL query I am using SQL Server 2012. I have the following query:
SELECT p.PortfolioGroupID, p.PortfolioGroupCode, p.DisplayOrder, p.MemberCode, m.ContactCode, m.Custom01, 'Separator' As 'PDFType'
  FROM [APXFirm].[AdvApp].[vPortfolioGroupMemberFlattened] p
  LEFT OUTER JOIN [APXFirm].[AdvApp].[vPortfolioInterestedParty] m
  on p.memberid = m.PortfolioID
WHERE m.ContactCode is not null
and p.PortfolioGroupCode like '%_Package'
  order by m.ContactCode, p.MemberCode

Current Result Set
PortfolioGroupID    PortfolioGroupCode  DisplayOrder    MemberCode  ContactCode Custom01    PDFType
11224   Test1_Package   677 test1   recipient1_ind  DVAAnnual   Separator
11224   Test1_Package   730 test2   recipient1_ind  DVAAnnual   Separator
11221   Test2_Package   1825    test3   recipient2_ind  DVAAnnual   Separator
11221   Test2_Package   1826    test4   recipient2_ind  DVAAnnual   Separator
11221   Test2_Package   1827    test5   recipient2_ind  DVAAnnual   Separator

Desired Result Set
PortfolioGroupID    PortfolioGroupCode  DisplayOrder    MemberCode  ContactCode Custom01    PDFType
11224   Test1_Package   677 test1   recipient1_ind  DVAAnnual   Cover
11224   Test1_Package   677 test1   recipient1_ind  DVAAnnual   Separator
11224   Test1_Package   677 test1   recipient1_ind  DVAAnnual   Report
11224   Test1_Package   730 test2   recipient1_ind  DVAAnnual   Separator
11224   Test1_Package   730 test2   recipient1_ind  DVAAnnual   Report
11221   Test2_Package   1825    test3   recipient2_ind  DVAAnnual   Cover
11221   Test2_Package   1825    test3   recipient2_ind  DVAAnnual   Separator
11221   Test2_Package   1825    test3   recipient2_ind  DVAAnnual   Report
11221   Test2_Package   1826    test4   recipient2_ind  DVAAnnual   Separator
11221   Test2_Package   1826    test4   recipient2_ind  DVAAnnual   Report
11221   Test2_Package   1827    test5   recipient2_ind  DVAAnnual   Separator
11221   Test2_Package   1827    test5   recipient2_ind  DVAAnnual   Report

For every instance of a group indicated by a new PortfolioGroupID in the PortfolioGroupID column. (In this example there are 2 groups 11224 and 11221) I need one row added as the first row that has the word Cover before where I have placed the word separator. All other columns are identical to the row it is placed before.
For every row in the group I need to interpolate/alternate a row with the word Report after the row where I placed the word separator. All other columns are identical to the row it is placed after.
If for some reason it's easier to place the word Separator before Report I could change the hard-coded value of Separator to Report.
Is this possible?

A: The first step would be to add a RowNumber column to identify the first row for each PorfoilioGroupID:
SELECT  p.PortfolioGroupID,
        p.PortfolioGroupCode,
        p.DisplayOrder,
        p.MemberCode,
        m.ContactCode,
        m.Custom01,
        RowNumber = ROW_NUMBER() OVER(PARTITION BY P.PortfolioGroupID ORDER BY m.ContactCode, p.MemberCode)
FROM    [APXFirm].[AdvApp].[vPortfolioGroupMemberFlattened] p
        LEFT OUTER JOIN [APXFirm].[AdvApp].[vPortfolioInterestedParty] m
            ON p.memberid = m.PortfolioID
WHERE   m.ContactCode is not null
AND     p.PortfolioGroupCode like '%_Package'
ORDER BY m.ContactCode, p.MemberCode;

Then you can  join your results set with a table valued constructor with your 3 values (Cover, Sperator, Report), and just add a where clause to ensure 'Cover' only appears for the first row:
WITH Data AS
(   SELECT  p.PortfolioGroupID,
            p.PortfolioGroupCode,
            p.DisplayOrder,
            p.MemberCode,
            m.ContactCode,
            m.Custom01,
            RowNumber = ROW_NUMBER() OVER(PARTITION BY P.PortfolioGroupID ORDER BY p.DisplayOrder)
    FROM    [APXFirm].[AdvApp].[vPortfolioGroupMemberFlattened] p
            LEFT OUTER JOIN [APXFirm].[AdvApp].[vPortfolioInterestedParty] m
                ON p.memberid = m.PortfolioID
    WHERE   m.ContactCode is not null
    AND     p.PortfolioGroupCode like '%_Package'
)
SELECT  d.PortfolioGroupID,
        d.PortfolioGroupCode,
        d.DisplayOrder,
        d.MemberCode,
        d.ContactCode,
        d.Custom01,
        t.PDFType
FROM    Data d
        CROSS JOIN
        (   VALUES
                ('Cover'),
                ('Seperator'),
                ('Report')
        ) t (PDFType)
WHERE   d.RowNumber = 1
OR      t.PDFType != 'Cover'
ORDER BY ContactCode, MemberCode;

Example on SQL Fiddle


text:
Q: Multiple-Input Linear Regression works for one dataset but not another I am trying to run a logistic regression algorithm using Pytorch (and employing a neural network with one hidden layer), and I stumbled upon a problem. I am running the same algorithm for two different input data. My inputs are two-dimensional. The first set of data I created myself, while the second set of data come from real-world data which I got from a csv file, converted to lists and then to pytorch tensors.
For the first input data, the tensor I insert to the logistic regression code is:
 First tensor has rank
 torch.Size([1000, 2])

and it's given by:
T1= tensor([[ 0.6258,  0.9683],
        [-0.0833,  0.5691],
        [-0.4657, -0.8722],
        ...,
        [ 0.5868, -1.0565],
        [ 0.1611, -0.1716],
        [-0.1515, -0.8408]])

While the tensor for the second set of data is:
Second tensor has rank
 torch.Size([1064, 2])

and it's given by:
T2= tensor([[918.0600,  74.8220],
        [917.3477,  71.4038],
        [923.0400,  60.6380],
        ...,
        [916.6000,  71.0960],
        [912.6000,  58.4060],
        [921.5300,  77.7020]])

Now, for the first set of data, I get the following result:

So as you can see, the algorithm does a fairly good job with the reb/blue decision region, as most of the red points end up in the red region (and the same with the blue ones).
Now, for the second set of data, I get the following:

As you can see, it paints the whole region in red. I tried playing around with the number of neurons in my hidden layer and the learning rate, number of epochs and some other things, but nothing seems to work. I then thought that it might have to do with x-axis data having much larger values than the y-axis ones so I normalized them by dividing each with their mean, but this did not solve the problem.
The algorithm is the same, but it just doesn't work for this set of data. I was wondering if somebody who's more of an expert than me could have a hunch as to what might be going wrong here.

A: When you dont normalize the data the model can be easily fooled.
Your train set is composed of 1000 examples that by the looks of it, the majority of the values are in the range [-1, 1].
When you test your model however, you feed it with much much much higher numbers.
The solution is normalization. When you normalize your input your model can be free to learn the true distribution function of the data rather then "memorize" numbers.
You should normalize both the training set and the test set. Then your values will range between 0 and 1 and your network will have much better chance of picking up the desired correlation.
import torch
import torch.nn.functional as f

train = torch.rand((4, 2))*100

tensor([[36.9267,  7.3306],
        [63.5794, 42.9968],
        [61.3316, 67.6096],
        [88.4657, 11.7254]])

f.normalize(train, p=2, dim=1)

tensor([[0.9809, 0.1947],
        [0.8284, 0.5602],
        [0.6719, 0.7407],
        [0.9913, 0.1314]])


text:
Q: Distinct in table join is not working correctly Hi i am using distinct in table join but it's not working correctly.only first item working correctly.after that repeating item is getting means in user.user_id column  only first user_id get distinct(i am having group identical user_id) .after first ID i am getting repeating id.my query is like below .please help me in this regard.
@"distinct timesheet.user_id, timesheet.created_date,"
            + "  [user].first_name,[user].last_name")

            .From(@"timesheet "
                  + "INNER JOIN [user] ON  [user].user_id = timesheet.user_id "
                  + "INNER JOIN timesheet_status ON timesheet.timesheet_status_id = timesheet_status.timesheet_status_id"

A: Sounds like you need a GROUP BY clause:
SELECT     timesheet.user_id
          ,MIN(timesheet.created_date) As first_created_date
          ,MIN([user].first_name) AS first_name
          ,MIN([user].last_name) AS last_name
FROM      timesheet
          INNER JOIN [user] ON  [user].user_id = timesheet.user_id
          INNER JOIN timesheet_status
              ON timesheet.timesheet_status_id = timesheet_status.timesheet_status_id
GROUP BY  timesheet.user_id

The code above will get the earliest (MIN) timesheet for each user_id along with their name. For the latest timesheet you would change the keyword MIN to MAX.


text:
Q: Getting all changes made to an object in the Entity Framework Is there a way to get all the changes made to a object in the Entity Framework before it saves all changes. The reason for this is that i want to create a log table in our clients database:
so...
Is there a way to get the current database values(old) and the new values(current) before changes are saved?
If not, how can i achieve this in a generic way, so all my View Models can inherit from this?(I am using the MVVM + M Structure)

A: You can use ObjectContext's ObjectStateManager,GetObjectStateEntry to get an object's ObjectStateEntry, which holds its original and current values in the OriginalValues and CurrentValues properties. You can get the names of the properties that changed using the GetModifiedProperties method.
You can write something like:
var myObjectState=myContext.ObjectStateManager.GetObjectStateEntry(myObject);
var modifiedProperties=myObjectState.GetModifiedProperties();
foreach(var propName in modifiedProperties)
{
    Console.WriteLine("Property {0} changed from {1} to {2}",
         propName,
         myObjectState.OriginalValues[propName],
         myObjectState.CurrentValues[propName]);
}

A: Use the IsModified field of each property, which is accessible by Context.Entry(Entity).Properties.
In this example, the modified entries are listed as a Tuple of the original and current values, indexed by name. Use any conversion that is required to build the audit log.
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

//...

// gets somewhere in the scope
DbContext Context;
// Some entity that has been modified, but not saved and is being tracked by Context
object Entity;

//...

Dictionary<string, System.Tuple<object, object>> modified =
    Context.Entry(Entity)
        .Properties.Where(p => p.IsModified)
        .ToDictionary(p => p.Metadata.Name,
                      p => new System.Tuple<object,object>(p.OriginalValue, p.CurrentValue));
//...

Uses Entity Framework Core 3.1. Try it for EF 6.4, but it may not work.

A: For EF5 upwards you can log your changes in the SaveChanges() method like this:
public override int SaveChanges()
{
    var changes = from e in this.ChangeTracker.Entries()
                  where e.State != System.Data.EntityState.Unchanged
                  select e;

    foreach (var change in changes)
    {
        if (change.State == System.Data.EntityState.Added)
        {
            // Log Added
        }
        else if (change.State == System.Data.EntityState.Modified)
        {
            // Log Modified
            var item = change.Cast<IEntity>().Entity;
            var originalValues = this.Entry(item).OriginalValues;
            var currentValues  = this.Entry(item).CurrentValues;

            foreach (string propertyName in originalValues.PropertyNames)
            {
                var original = originalValues[propertyName];
                var current = currentValues[propertyName];

                if (!Equals(original, current))
                {
                    // log propertyName: original --> current
                }
            }
        }
        else if (change.State ==  System.Data.EntityState.Deleted)
        {
            // log deleted
        }
    }

    // don't forget to save
    base.SaveChanges();
}

A: I use this extension function that provides details on the entity being changed, the old and new values, the datatype, and the entity key.
This is tested with EF 6.1 using ObjectContext and uses log4net for output.
/// <summary>
/// dump changes in the context to the debug log
/// <para>Debug logging must be turned on using log4net</para>
/// </summary>
/// <param name="context">The context to dump the changes for</param>
public static void DumpChanges(this ObjectContext context)
{
    context.DetectChanges();

    // Output any added entries
    foreach (var added in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added))
    {
        Log.DebugFormat("{0}:{1} {2} {3}",
            added.State,
            added.Entity.GetType().FullName,
            added.Entity.ToString(),
            string.Join(",",
                added.CurrentValues.GetValue(1),
                added.CurrentValues.GetValue(2))
            );
    }
    foreach (var modified in context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
    {
        // Put original field values into dictionary
        var originalValues = new Dictionary<string,int>();
        for (var i = 0; i < modified.OriginalValues.FieldCount; ++i)
        {
            originalValues.Add(modified.OriginalValues.GetName(i), i);
        }

        // Output each of the changed properties.
        foreach (var entry in modified.GetModifiedProperties())
        {
            var originalIdx = originalValues[entry];
            Log.DebugFormat("{6} = {0}.{4} [{7}][{2}] [{1}] --> [{3}]  Rel:{5}",
                modified.Entity.GetType(),
                modified.OriginalValues.GetValue(originalIdx),
                modified.OriginalValues.GetFieldType(originalIdx),
                modified.CurrentValues.GetValue(originalIdx),
                modified.OriginalValues.GetName(originalIdx),
                modified.IsRelationship,
                modified.State,
                string.Join(",",
                    modified.EntityKey.EntityKeyValues
                        .Select(v => string.Join(" = ", v.Key, v.Value))
                    )
                );
        }
    }

    // Output any deleted entries
    foreach (var deleted in context.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted))
    {
        Log.DebugFormat("{1} {0} {2}",
            deleted.Entity.GetType().FullName,
            deleted.State,
            string.Join(",",
                deleted.CurrentValues.GetValue(1),
                deleted.CurrentValues.GetValue(2))
            );
    }
}


text:
Q: Execute crontab as root not working I need to execute a backup script each night. When I execute manually, backup is done without problems, but I use sudo crontab -e and add the script there:
root@SF-DES-SVN:/home/svn# crontab -l
# m h  dom mon dow   command
@daily /home/xxx/do_backup.sh &> /tmp/do_backup.log
@daily /home/xxx/do_rm_old.sh &> /tmp/do_rm_old.log

But the scripts are not being executed, in the log I have msg:
/etc/cron.daily/xxx_backups: line 3: /home/xxx/do_backup.sh: No such file or directory

In line 3 of the script
SVN_ROOT=/home/svn/

Which, of course, exists and keeps all my repositories. But makes me think is a permission problem…

*

*I tried with patterns instead of annotations, same behaviour.

*I tried with @hourly annotation and works, but I think is because root session is open.

Any idea of what's going on?
UPDATE:
root@SF-DES-SVN:/# cat /etc/fstab

# /etc/fstab: static file system information.
#
# Use 'blkid -o value -s UUID' to print the universally unique identifier
# for a device; this may be used with UUID= as a more robust way to name
# devices that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
proc            /proc           proc    nodev,noexec,nosuid 0       0
/dev/mapper/SF--DES--SERVER-root /               ext4    errors=remount-ro 0       1
# /boot was on /dev/sda1 during installation
UUID=fe2e0df4-cd99-4189-8eed-9d7519e2aba8 /boot           ext2    defaults        0       2
#/dev/mapper/SF--DES--SERVER-swap_1 none            swap    sw              0       0
/dev/fd0        /media/floppy0  auto    rw,user,noauto,exec,utf8 0       0
/dev/mapper/cryptswap1 none swap sw 0 0
/dev/sda3  /home/back_svn ext3 defaults,auto 0 2

UPDATE2: Output for ls -la /home/siconet/do_backup.sh
-rwxrwxrwx 1 siconet siconet 1055 2014-06-05 17:57 /home/siconet/do_backup.sh

UPDATE3: I execute each order after entering as root user with sudo su -. Am I right when I supose root@SF-DES-SVN:/home/svn# crontab -l lists the root user crontabs?


text:
Q: html - How to dynamic change base64 image I am try to transmit live video stream to server and show on web page. Well, I successfully show my image on the html page, but my image is freeze. The image will change only when I press refresh button on the browser. How to make it show like a video stream? Following is my snippet:

var socket = io();

socket.on('liveCam', function(url) {

  var old_url = '';
  var diff = strcmp(url , old_url);
  old_url = url;

  console.log('diff =', diff);
  var src_url = 'data:image/jpeg;base64,' + url;
  setInterval(setimagesrc(src_url), 50);

});

function setimagesrc(uurl){
  $('#image').attr('src', uurl);
}

function strcmp ( str1, str2 ) {
  return str1 == str2 ? 1 : 0;
}

streaming

Thanks for your patience!

A: The first parameter of the setInterval function evaluates an expression. What you did there is that you call the setimagesrc function to be executed in the set interval. This will cause the setimagesrc to be executed only once. What you have to do there is to add a reference to the setimagesrc function and use global variables or to use an anonymous function in the setInterval that will call the setimagesrc with the parameters.
Example 1:
setInterval(setimagesrc, 50);

function setimagesrc(){
  $('#image').attr('src', src_url );
}

Example 2:
setInterval(function(){setimagesrc(src_url)}, 50);

I prefer the second way.


text:
Q: Disabling or changing language for spell checking on Skype Skype is drawing red lines under non-English words I type. How to disable it, or change the spell checking language? Apparently, the spell checker is not a part of Skype itself.
Using Ubuntu 16.04 with Gnome, Skype 8.11.0.4.

A: Disclaimer: This is an old question but I haven't found a solution before fiddling it by myself. Hopefully it can reach more people given the annoyance.
Removing Skype's ability to write dictionaries to disk isn't fatal.
cd ~/.config/skypeforlinux/dictionaries
rm *
sudo chattr +i .

Using chmod(1) wouldn't remove Skype's ability to remove and recreate the dictionary directory. Note that chattr(1) is Linux-specific and for FreeBSD you'd use chflags schg and so on.
Furthermore please note that Skype ignores spellchecking preferences from KDE.
On some installations, the path is ~/.config/skypeforlinux/Dictionaries or even both variants might exist.


text:
Q: Google Spreadsheet API - returns remote 500 error Has anyone battled 500 errors with the Google spreadsheet API for google domains?
I have copied the code in this post (2-legged OAuth): http://code.google.com/p/google-gdata/source/browse/trunk/clients/cs/samples/OAuth/Program.cs, substituted in my domain;s API id and secret and my own credentials, and it works.
So it appears my domain setup is fine (at least for the contacts/calendar apis).
However swapping the code out for a new Spreadsheet service / query instead, it reverts to type: remote server returned an internal server error (500).
                var ssq = new SpreadsheetQuery();
                ssq.Uri = new OAuthUri("https://spreadsheets.google.com/feeds/spreadsheets/private/full", "me", "mydomain.com");
                ssq.OAuthRequestorId = "me@mydomain.com"; // can do this instead of using OAuthUri for queries
                var feed = ssservice.Query(ssq); //boom 500
                Console.WriteLine("ss:" + feed.Entries.Count);

I are befuddled

A: I had to make sure to use the "correct" class:
not
//using SpreadsheetQuery = Google.GData.Spreadsheets.SpreadsheetQuery;

but
using SpreadsheetQuery = Google.GData.Documents.SpreadsheetQuery;

stinky-malinky
Seems you need the gdocs api to query for spreadsheets, but the spreadsheet api to query inside of a spreadsheet but nowhere on the internet until now will you find this undeniably important tit-bit. Google sucks hard on that one.


text:
Q: git cherry-pick top from dirty branch I made some experiments in master (I know It wasn't good idea), and than checkout my feature branch. Later them I dropped old "dirty" master and recreated new one. Now I want to cherry-pick jst top commit (that only relates to developed feature) into new "clean" master.
But cherry-pick grabs additional commits, out of specified range, that was earlier on old master. How can one handle this?
o---o---o---o---o  old dirty master
    |            \
    |             o'--o'--o'  feature branch
     \
      o---o---o---o---o  clean master


text:
Q: Uploading Files with Ajax working on Postman but not browser I am trying to let certain users upload a video to the API using Ajax. This works on Postman, but when doing this from the browser I get a 500 Internal Server Error.
I do not have access to the server so I cannot show server logs, but according to the guy that does, he receives the "OPTIONS" post but not the second post with the multipart/form-data. When I check my form data in the chrome network tool it gives me this.
And the url I'm appending to for each upload looks like this.
The two requests in the network tool.
Seems to be something wrong with how my form is being posted and I'm pretty sure it's my fault not the server's since it works with Postman.
The postman code is:
var form = new FormData();
form.append("video", "C:\\Users\\Sidhant\\Downloads\\examplevid.mp4");

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://apiurl/catagoryid/videotitle",
  "method": "POST",
  "headers": {
    "Authorization": "Bearer token",
    "Content-Type": "application/x-www-form-urlencoded",
    "cache-control": "no-cache",
    "Postman-Token": "token"
  },
  "processData": false,
  "contentType": false,
  "mimeType": "multipart/form-data",
  "data": form
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

My code is the same except for how I get the file:
var fileinput = document.getElementById("fileinput").files[0];
var form = new FormData($('#fileinput')[0]);

With postman the video is added to the API, while through the browser it's given a 500 error. How can I stop getting this error, and what are some things I can try. I'm a beginner with Ajax so I'm not familiar with these sorts of issues.

A: The problem is how you are selecting the files in your formdata.
var fileinput = document.getElementById("fileinput").files[0];
var form = new FormData($('#fileinput')[0]);

You select the file correctly using plain js, but then use Jquery and simply select the file input element. So it's like you are trying to attach the html element itself, rather than the user data.
Use this.
//null check on the input
var fileinput = $('#fileinput').length ? $('#fileinput')[0].files[0] : null;
//Create the FormData and add the file to the FD
var form = new FormData();
form.append('video', fileinput );

A: Problem 1

var fileinput = document.getElementById("fileinput").files[0];
var form = new FormData($('#fileinput')[0]);

If you initialise FormData with a value, it should be a form element.
If you want to add a file, you need to create the object and then append the file.
Either way, you shouldn't get the file and then pass it to jQuery. That makes no sense at all. jQuery works with HTML, Selectors and DOM elements, not file objects.
Either:
var form = document.getElementById("fileinput").form;
var data = new FormData(form);

or
var file = document.getElementById("fileinput").files[0];
var data = new FormData();
data.append("video", file, "filename.mp4");

Problem 2
You are overriding the Content-Type of the request, so it won't be generating the correct one from the FormData object and the server won't know how to extract the data.
Delete

"Content-Type": "application/x-www-form-urlencoded",

and

"mimeType": "multipart/form-data",

Asides

"async": true,

This is the default. There is no point is setting it explicitly.

"crossDomain": true,

This does nothing unless you are making a same origin request which is redirected to be cross origin. There's usually no point in setting it.


text:
Q: Going Back to Grad School After Being Away from Math I graduated with a degree in Math-Computer Science(dual degree) from a college in the US in 2012, and have been working in the Software industry ever since. From 2012 to mid 2014 I was a software engineer and since then, I have been an operations engineer(maintaining servers and stuff).
Even though my degree is Math-CS, most of my major courses and electives are in math and I've been thinking about going back to school to get a master's in some discipline of math.  But I worry about whether I'll be able to pick up the material in school after being away from the field for a few years.  My question is should I be reviewing materials prior to attending grad school? (Such as calculus/Algebra/Real Analysis(by Rudin) etcetc). Should I know everything undergrad courses cover in Analysis/Algebra before thinking about going to grad school? I realized most syllabuses for grad school application says "One quarter in Analysis, One quarter in Algebra, One quarter in Linear Algebra" or something along that line, but I feel that may not be enough preparation.
If it helps, I am thinking about going to grad school to either do industry work/teach math and not necessarily to do research, so I am not thinking about a PhD at all.

A: I was undergrad math-physics and did compsci on the side. Afterwards i worked a CS job for 2 years and then applied to a math masters program with a similar goal. Having now completed it, I can say that it should be doable with little prior study (I never had analysis in undergrad) so I never even prepared for it in grad school. Though I prepared nothing outside of Calc 1/2/3 I did make it through, though I will admit that first year was trying as all heck.
If you want a smooth ride, I would strongly recommend an in depth review of Calc 1/2/3. A walkthrough of an undergrad analysis book ( try Rudin / bartle  in order of decreasing difficulty) and a good review of linear algebra (Hoffman& Kunze or Strang) and maybe some kind of a review of some differential equations and youll be ahead of or caught up to a majority of the students entering the program.
Good luck, you have a lot of reading ahead of you :)

A: Definitely review! Think of this as landing a job. One you look forward to advancing your career and/or happiness, to boot. But the employer wants you to be good at something you have skill at but haven't done in a while. Do you just play up the past and wing it from there, or do you re-familiarize yourself with that skill set as much as you can? The latter, of course!
Since grad departments can sometimes offer you a TA position or other financial aid, this is a very accurate view to take. Note availability of these varies widely. My department was always able to fund people it expected to be PhD track, but not necessarily master's students. And others can't even do that (this is common in public universities, even extremely good ones).
Lastly, grad departments are very much aware of the variability of undergraduate programs and personal lives. Especially for master's students. It is not unusual for a grad student, including promising doctorate potentials, to lack certain fundamentals. Topology was a common culprit in my observations. In which case they may have you take the appropriate undergrad course.
So some missing skills is not a huge problem, but certainly refine your skills.


text:
Q: openssl_x509_parse / validTo_time_t gives me "1970-01-01" OpenSSL 1.1.1 php enabled for apache
all sites give me "1970-01-01" as an expiry date
<?php

$websites = $_POST['websites'];
$websites = explode(',', $websites);

foreach ($websites as $website) :
    $website = trim($website);
    $cert = openssl_x509_parse(file_get_contents("https://{$website}"));
    $expiration = date('Y-m-d', $cert['validTo_time_t']);
    echo "{$website}: {$expiration}<br>";
endforeach;

?>

any site gives the same date

A: You are passing the contents (HTML) of the site to openssl_x509_parse:
$cert = openssl_x509_parse(file_get_contents("https://{$website}"));

You either need and certificate object or the contents of the actual certificate
 openssl_x509_parse(OpenSSLCertificate|string $certificate, bool $short_names = true): array|false

https://www.php.net/manual/en/function.openssl-x509-parse.php
See: How to get SSL certificate info with CURL in PHP? for an example.