text:
Q: Mock Axios instance and interceptors in React component jest test I'm testing a component that calls an API to populate a table with data. Though axios is used, axios is being wrapped in a convenience method of sorts to populate headers before executing the request via interceptors. I've tried axios-mock-adapter, but it's not working. I'm still new to testing React and I'm lost on how to mock data coming back from the api/axios. How do I go about mocking the api call to mock the data for my tests to pass??
This is my simple test:
test('<EmailTable/> ', async () => {
  const { debug, getByText } = render(<CommunicationEmail />);
  await waitFor(() => expect(getByText('Test Email Subject')).toBeTruthy());
}

This is the axios wrapper (api.js):
const instance = axios.create({
  baseURL: `${apiUrl}/v1`,
  timeout: 12000,
  withCredentials: true,
  headers: headers,
});

//intercept requests to validate hashed auth token
instance.interceptors.request.use((request) => {
  const token = request.headers['X-Our-Access-Token'];
  if (
    localStorage.getItem('user_token') == null ||
    SHA256(token).toString(enc.Hex) == localStorage.getItem('user_token')
  ) {
    return request;
  } else {
    console.log({ what: 'Auth key invalid' });
    return Promise.reject('Invalid token!');
  }
});

//intercept responses to handle 401 errors
instance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // handle 401 authentication errors and redirect to SSO
    if (error.response != null && error.response.status != null && error.response.status === 401) {
      console.error({ what: 'Authorization error', e: error });
    }
    return Promise.reject(error);
  }
);

export default instance;

And here's a simplification of the component I'm trying to test:
import api from './api.js';

const EmailTable = () => {
   const [emails, setEmails] = useState();

   useEffect(() => {
      if(!emails) {
         getEmails();
      }
   }, [emails]);

   const getEmails = async () => {
      await api({
        method: 'GET',
        url: `/communications/emails`,
      }).then((response) => {
        if (response.success) {
           setEmails(response.emails);
        }
      }
    }

   if(!emails) { return <div> Loading... </div> };
   return <div>{emails}</div>;
}

UPDATE WITH SOLUTION:
To mock the axios wrapper that is my API, I had to mock the api module and return a resolved promise like so:
jest.mock('../api', () => {
  return function (request) {
    // If we want to mock out responses to multiple API requests, we could do if (request.url = "/blah/blah") { return new Promise.... }
    return new Promise((resolve) => {
      resolve({
        data: { success: true, emails: [] },
      });
    });
  };
});


text:
Q: Vue.js: Uncaught promises in vuex actions I understand vuex actions return promises, but I haven't found the ideal pattern to handle errors in vuex. My current approach is to use an error interceptor on my axios plugin, then committing the error to my vuex store.
in plugins/axios.js:
export default function({ $axios, store }) {
    $axios.onError(error => {
        store.dispatch('setError', error.response.data.code);
    });
}

in store/index.js:
export const state = () => ({
    error: null,
});

export const mutations = {
    SET_ERROR(state, payload) {
        state.error = payload;
    },
}

export const actions = {
    setError({ commit }, payload) {
        commit('SET_ERROR', payload);
    },
};

I would then use an error component watching the error state and show if there is an error. Thus there is really no need to catch any errors in either my action or in the component that dispatched the action. However I can't help to worry if it's bad design leaving exceptions uncaught? What issues could I encounter if I handle errors by this design? Suggestions on any better ways to do this?

A: I would argue that you should make the API call in the vuex action and if it fails, reject the promise with the error from the API call. I would avoid listing to all Axios errors and instead handle the error when it is returned in the promise, in my opinion, it would be easier to maintain and debug this way

For example:
getCartItems: function ({commit}, url) {
    return axios.get(url).then(response => {
      commit('setCartItems', response.data)
      return response
    }).catch(error => {
      throw error
    })
 },

A: Improved above example to avoid redundant promise wrapping and use async/await for simplified code:
export const getCartItems = async ({commit}, url) => {
  const response = await axios.get(url);
  commit('setCartItems', response.data)
  return response;
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a message for write to a TCP socket I don't really know how to put this question, but here we go.
So let's assume I'm using ASIO from Boost libs to connect to a server using a TCP socket and write a certain message to it.
The message contains some user data and looks like this: 1 byte (packet ID), 4 bytes (integer), user null-terminated string and 6 zero bytes (reserved by the server but unused).
What would be the most convenient way to assemble such a message for use with ASIO's boost::asio::buffer function?
I'm really confused at this point. Help greatly appreciated.

A: Instead of making a single buffer using asio::buffer() function, you can adapt your structure to be a buffer sequence - asio functions accept such a concept. It would be convenient to send this way a pattern like fixed--null-terminated--null-terminated-fixed-fixed-etc...

A: A. Define packet structures that can be serialized.
class ISerializable
{
public:
    virtual ~ISerializable(){}

    virtual void serialize(std::ostream& stream) = 0;
};

class LoginPacket : public ISerializable
{
public:
    // Constructor and access functions

    virtual void serialize(std::ostream& stream)
    {
        stream.write((const char*)&packetId, 1);
        stream.write((const char*)&accountId, 4);
        stream.write(username.c_str(), username.size() + 1);
        // Write the unused 6-bytes of zero
        int zero(0);
        stream.write((const char*)&zero, 4);
        stream.write((const char*)&zero, 2);
    }

private:
    unsigned char packetId;
    unsigned int32_t accountId;
    std::string username;
};

B. Now, to use this packet class do something like:
LoginPacket packet;
// Fill details for the packet
std::stringstream data;
packet.serialize(data);
// Send the data to the network
yourSocket.send(data.str().c_str(), data.str().size());

A: the boost::asio::buffer() functions adapt or convert other kind of buffers to the one, used by asio.
You should use some kind of application buffer, fill that buffer and then pass the buffer to asio for writing onto the wire. For example:
std::vector< char > data;

data.push_back( id );
data.push_back( i & 0xff );
data.push_back( ( i >> 8 ) & 0xff );
data.push_back( ( i >> 16 ) & 0xff );
data.push_back( ( i >> 24 ) & 0xff );

const char* const str = s.c_str();
data.insert( data.end(), str, str + std::strlen( str ) );

for ( int pad = 0; pad != 4; ++pad )
    data.push_back( 0 );

boost::asio::write( socket, boost::asio::buffer( data ) );


text:
Q: Is there a way to find out which of my github repositories have github pages enabled? I don't want to check 200+ repositories manually, and I'm not seeing anything in gh documentation how to get it from the API.
Is there any automated way to get this information?

A: Is there any automated way to get this information?
Yes:

You can use the GitHub API rpeos Pages

The GitHub Pages API retrieves information about your GitHub Pages configuration, and the statuses of your builds.
Information about the site and the builds can only be accessed by
authenticated owners, even if the websites are public.
In GitHub Pages API endpoints with a status key in their response, the value can be one of:

*

*null: The site has yet to be built.

*queued: The build has been requested but not yet begun.

*building:The build is in progress.

*built: The site has been built.

*errored: Indicates an error occurred during the build.

You can then force a GitHub Page repository to rebuild, through
GitHub Action, if you want.

Source: Is there any way to filter GitHub repo that is GitHub page enabled?, answer by VonC


text:
Q: Branch versioning in ArcMap We have a people that only use ArcMap. We have a project created in ArcGIS Pro, which obviously supports branch versioning.
How can we allow those using ArcMap to edit the ArcGIS Pro project considering ArcMap won't work with branch versioning?


text:
Q: how to install ffmpeg in cpanel I heard that most probably cpanel server dont have ffmpeg preconfigured in it. Can you explain a way to install it in cpanel.
Please if you can guide me through the installtion of ffmpeg in cpanel server in step by step process.
Can anyone please also give me links of other servers which have ffmpeg preconfigured and set to run.

A: This appears to be a reasonably comprehensive guide, but my knowledge of the situation isn't good personally.  There are a few other tutorials but this would be good as a separate tutorial/perhaps wiki because it's quite a common question I hear asked by my hosting clients.
http://www.eukhost.com/forums/f15/how-install-ffmpeg-ffmpeg-php-mplayer-mencoder-flv2tool-lame-mp3-encoder-4893/
perhaps also
serverhostingsecrets.com/tutorials/cpanel-ffmpeg-howto/

A: If you have CentoOS, RedHat or fedorra, you can install it using yum.
First add the dag repo.
http://dag.wieers.com/rpm/FAQ.php#B
rpm -Uhv http://apt.sw.be/redhat/el5/en/x86_64/rpmforge/RPMS//rpmforge-release-0.3.6-1.el5.rf.x86_64.rpm
yum install ffmpeg ffmpeg-devel

Your can also install the mplayer and mencoder using yum from the dag repo
yum install mplayer mencoder


text:
Q: 'Image' has no propType for native prop 'RCTImageView.overlayColor' of native type 'number' Hello I am trying to run my react native app on android and I am getting this error message.  The app has been working on iOS for months and this is the first time we are trying to use it on android.  We are using react-native .19.  I have tried restarting the packager multiple times as well as restarting Android Studio and it has not helped at all.  I have also removed my entire node_modules folder and reinstalled everything and the error still exists
'Image' has no propType for native prop 'RCTImageView.overlayColor' of native type 'number'
Settings.gradle
rootProject.name = 'MassTuning'

include ':app'
include ':react-native-vector-icons'
project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons//Users/kvieira/code/masstuning/node_modules/react-native-vector-icons/android')
include ':react-native-linear-gradient'
project(':react-native-linear-gradient').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-linear-gradient/android')
include ':react-native-maps'
project(':react-native-maps').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-maps/android')
include ':react-native-image-picker'
project(':react-native-image-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-image-picker/android')
include ':react-native-mail'
project(':react-native-mail').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-mail/android')
include ':react-native-admob'
project(':react-native-admob').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-admob/android')

build.gradle
apply plugin: "com.android.application"

import com.android.build.OutputFile

/**
 * The react.gradle file registers two tasks: bundleDebugJsAndAssets and bundleReleaseJsAndAssets.
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation
 *   entryFile: "index.android.js",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"]
 * ]
 */

apply from: "react.gradle"

/**
 * Set this to true to create three separate APKs instead of one:
     *   - A universal APK that works on all devices
     *   - An APK that only works on ARM devices
     *   - An APK that only works on x86 devices
     * The advantage is the size of the APK is reduced by about 4MB.
     * Upload all the APKs to the Play Store and people will download
     * the correct one based on the CPU architecture of their device.
     */
    def enableSeparateBuildPerCPUArchitecture = false

    /**
     * Run Proguard to shrink the Java bytecode in release builds.
     */
    def enableProguardInReleaseBuilds = false

    android {
        compileSdkVersion 23
        buildToolsVersion "23.0.1"

        defaultConfig {
            applicationId "com.masstuning"
            minSdkVersion 16
            targetSdkVersion 22
            versionCode 1
            versionName "1.0"
            multiDexEnabled true
            ndk {
                abiFilters "armeabi-v7a", "x86"
            }
        }
        splits {
            abi {
                enable enableSeparateBuildPerCPUArchitecture
                universalApk true
                reset()
                include "armeabi-v7a", "x86"
            }
        }
        buildTypes {
            release {
                minifyEnabled enableProguardInReleaseBuilds
                proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            }
        }
        // applicationVariants are e.g. debug, release
        applicationVariants.all { variant ->
            variant.outputs.each { output ->
                // For each separate APK per architecture, set a unique version code as described here:
                // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
                def versionCodes = ["armeabi-v7a":1, "x86":2]
                def abi = output.getFilter(OutputFile.ABI)
                if (abi != null) {  // null for the universal-debug, universal-release variants
                    output.versionCodeOverride =
                            versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
                }
            }
        }
    }

    configurations.all {
      resolutionStrategy {
        force 'com.google.android.gms:play-services-ads:8.4.0'

}
}

dependencies {
    compile project(':react-native-admob')
    compile project(':react-native-mail')
    compile project(':react-native-image-picker')
    compile project(':react-native-maps')
    compile project(':react-native-linear-gradient')
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:0.19.+"

}

MainActivity.java
package com.masstuning;

import com.facebook.react.ReactActivity;
import com.sbugert.rnadmob.RNAdMobPackage;
import com.chirag.RNMail.RNMail;
import com.imagepicker.ImagePickerPackage;
import com.AirMaps.AirPackage;
import com.BV.LinearGradient.LinearGradientPackage;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;

import java.util.Arrays;
import java.util.List;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "MassTuning";
    }

    /**
     * Returns whether dev mode should be enabled.
     * This enables e.g. the dev menu.
     */
    @Override
    protected boolean getUseDeveloperSupport() {
        return BuildConfig.DEBUG;
    }

   /**
   * A list of packages used by the app. If the app uses additional views
   * or modules besides the default ones, add more packages here.
   */
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
        new MainReactPackage(),
        new RNAdMobPackage(),
        new RNMail(),
        new ImagePickerPackage(),
        new AirPackage(),
        new LinearGradientPackage());
    }
}

A: I was able to solve this issue by upgrading react to 20.  After that I never saw this issue again


text:
Q: How to extract the time into a formula field? I want to extract the time component of CreatedDate (standard field) into a formula field (which should be a string) that contains just the time part.
So if CreatedDate is Jan 4, 2014  17:23:10, then then formula field should just have 17:23:10.
While setting up the formula field, I've tried the following:
CreatedDate.format('hh:mm:ss')
DateValue(CreatedDate).format('hh:mm:ss')
but nothing appears to work.
Am I missing something simple?

A: There is an example on the help docs for formula date examples that shows the following to get the time from a Date/Time field

Finding the Hour, Minute, or Second from a Date/Time
  To get the hour, minute, and second from a Date/Time field as a numerical value, use the following formulas where TZoffset is the difference between the user's time zone and GMT.
  For hour in 24–hour format:

VALUE( MID( TEXT( date/time - TZoffset ), 12, 2 ) )

For hour in 12–hour format:

IF(
  OR(
    VALUE( MID( TEXT( date/time - TZoffset ), 12, 2 ) ) = 0,
    VALUE( MID( TEXT( date/time - TZoffset ), 12, 2 ) ) = 12
  ),
  12,
  VALUE( MID( TEXT( date/time - TZoffset ), 12, 2 ) )
   -
   IF(
     VALUE( MID( TEXT( date/time - TZoffset ), 12, 2 ) ) < 12,
     0,
     12
   )
)

For minutes:

VALUE( MID( TEXT( date/time - TZoffset ), 15, 2 ) )

For seconds:

VALUE( MID( TEXT( date/time - TZoffset ), 18, 2 ) )

And, to get "AM". or "PM" as a string, use:

IF(
  VALUE( MID( TEXT( date/time - TZoffset ), 12, 2 ) ) < 12,
  "AM",
  "PM"
)

To return the time as a string in "HH:MM:SS A/PM" format, use the following formula:

IF(
  OR(
    VALUE( MID( TEXT( date/time - TZoffset ), 12, 2 ) ) = 0,
    VALUE( MID( TEXT( date/time - TZoffset ), 12, 2 ) ) = 12
  ),
  "12",
  TEXT( VALUE( MID( TEXT( date/time - TZoffset ), 12, 2 ) )
   -
   IF(
     VALUE( MID( TEXT( date/time - TZoffset ), 12, 2 ) ) < 12,
     0,
     12
   )
  )
)
& ":" &
MID( TEXT( date/time - TZoffset ), 15, 2 )
& ":" &
MID( TEXT( date/time - TZoffset ), 18, 2 )
& " " &
IF(
  VALUE( MID( TEXT( date/time - TZoffset ), 12, 2 ) ) < 12,
  "AM",
  "PM"
)

When working with time in formula fields, you need to consider the time difference between your organization and GMT. See A Note About Date/Time and Time Zones for help understanding the time zone offset used in this formula.

Here is a blog post on one way to get time zones.

A: I'm not sure where you're getting those formula operators from.
For a list of actual operators you can use, see the help docs at:  https://help.salesforce.com/apex/HTViewHelpDoc?id=customize_functions.htm
In regards to your question, the following formula works for me:
LEFT(RIGHT(text( CreatedDate ),9),8)

I don't know the impacts of different regions will have on this.
I also get the feeling this may not be the best way to capture.

A: There isn't any formatting function for date/time fields, nor for extracting the time.
You can convert the date/time value to a string using TEXT( CreatedDate ), which will return the string in the format "YYYY-MM-DD HH:MM:SS", and then trim off the date part, but you have to be wary of time zones. Normally the date/time is converted from GMT to the user's time zone when viewed, but wrapping it in TEXT() will cause the GMT value to be returned, not the converted time zone. So you would need to convert it to the user's time zone first, which can't be determined in a formula. If all your users are in the same time zone, you can adjust the time zone difference by adding/subtracting the time difference between the user's time zone and GMT, but Daylight Saving Time makes this challenging too.
See "Overview of Using Date and Date/Time Values in Formulas" in the Salesforce Help, particularly the "A Note About Date/Time and Time Zones" section.

A: Here's a KB Article to Convert DateTime from GMT to Local and automaically adjust for GMT
Knowledge Article Number: 000181642
Description
This formula will allow you to convert any Date/Time field to display it's value in another time zone. It will convert the Date (if necessary), the Time, and will account for Daylight Savings (using US start/end dates for DST).

A: To display only the time, use:
LEFT(TEXT(TIMEVALUE(CreatedDate)),8)

This converts the TimeValue ("HH:MM:SS.MS") of the DateTime field to text then uses just the leftmost 8 characters.


text:
Q: Replacing a Matched Character in Powershell I have a text file of 3 name entries:
# dot_test.txt
001 AALTON, Alan .....25 Every Street
006 JOHNS, Jason .... 3 Steep Street
002 BROWN. James .... 101 Browns Road

My task is to find instances of NAME. when it should be NAME, using the following:
Select-String -AllMatches -Path $input_path -Pattern '(?s)[A-Z]{3}.*?\D(?=\s|$)' -CaseSensitive |
    ForEach-Object { if($_.Matches.Value -match '\.$'){$_.Matches.Value -replace '\,$'} }

The output is:
BROWN.

The conclusion is this script block identifies the instance of NAME. but fails to make the replacement.
Any suggestions on how to achieve this would be appreciated.

A: You can use -replace directly, and if you need to replace both a comma and dot at the end of the string, use [.,]$ regex:
Select-String -AllMatches -Path $input_path -Pattern '(?s)[A-Z]{3}.*?\D(?=\s|$)' -CaseSensitive | % {$_.Matches.Value -replace '\.$', ','}

Details:

*

*(?s)[A-Z]{3}.*?\D(?=\s|$) - matches

*

*(?s) - RegexOptions.Singleline mode on and . can match line breaks

*[A-Z]{3} - three uppercase ASCII letters

*.*? - any zero or more chars as few as possible

*\D - any non-digit char

*(?=\s|$) - a positive lookahead that matches a location either immediately followed with a whitespace or end of string.

The \.$ pattern matches a . at the end of string.

A:
$_.Matches.Value -replace '\,$'

This attempts to replace a , (which you needn't escape as \,) at the end of ($) your match with the empty string (due to the absence of a second, replacement operand), i.e. it would effectively remove a trailing ,.
However, given that your match contains no , and that you instead want to replace its trailing . with ,, use the following:
$_.Matches.Value -replace '\.$', ','  # -> 'BROWN,'


text:
Q: Declare variable outside any class: why is it possible I have a file fancy_button.dart for a custom Flutter widget FancyButton which is like:
class FancyButton extends StatefulWidget {
    // ...
}

class _FancyButtonState extends State<FancyButton> {
    // ...
}

// Declaration outside any class:

Map<_FancyButtonState, Color> _buttonColors = {};

final _random = Random();

int next(int min, int max) => min + _random.nextInt(max - min);

// ...

The application works just fine. Notice that I declare and use some variables outside any class. Now my question is: how is it even possible? Shouldn't everything be inside a class in Dart, like Java?

A: No, Dart supports variables and functions defined in global space. You can see this with the main() method which are declared outside any class.
Also, global variables (and static class variables) are lazy evaluated so the value are first defined when you are trying to use them. So your runtime are not going to slow down even if there are a bunch of global variables there are not used.

A: Are you coming from Java before touching Dart?
Basically, Dart is not single-class-single-file like how Java works. Yes, it does support Object Oriented Programming (in kinda different way). The behavior of constructor is different. There is no public, private, and protected keywords. Please just refer to the official docs.
Anyway, you don't need a complex public static void main(). The real entry point is main(). Unless you define that function, you won't be able to run a file in command line.


text:
Q: how to hide a vertical scroll bar when not needed I have a textarea which is contained in a div as I have jquery hint and wanted to use opacity without changing the border.
There is a visible vertical scroll bar how I only want this displayed when I am typing in the text field and it goes beyond the container. I have tried overflow: auto; but does not work.
Textfield:

        <textarea name="message" type="text" id="message"
            title="Enter Message Here"
            rows=9 cols=60 maxlength="2000"></textarea>

Styles:
#name {
    border: 1px solid #c810ca;
    width: 270px;
    height:159px;
    overflow: hidden;
    position: relative;
    }

#message {
    height: 400px;
    width: 235px;
    overflow: hidden;
    position: absolute;
}

A: overflow: auto; or overflow: hidden; should do it I think.

A: overflow: auto (or overflow-y: auto) is the correct way to go.
The problem is that your text area is taller than your div.  The div ends up cutting off the textbox, so even though it looks like it should start scrolling when the text is taller than 159px it won't start scrolling until the text is taller than 400px which is the height of the textbox.
Try this: http://jsfiddle.net/G9rfq/1/
I set overflow:auto on the text box, and made the textbox the same size as the div.
Also I don't believe it's valid to have a div inside a label, the browser will render it, but it might cause some funky stuff to happen.  Also your div isn't closed.

A: Add this class in .css class
.scrol  {
font: bold 14px Arial;
border:1px solid black;
width:100% ;
color:#616D7E;
height:20px;
overflow:scroll;
overflow-y:scroll;
overflow-x:hidden;
}

and use the class in div. like here.

-

I have attached image , you see the out put of the above code


text:
Q: Tried to prove that $e$ is irrational but ended up proving it's not a real number. Assume $e=p/q$, with integers $p,q$. Then we have:
\begin{align}
&qe=p\\
&(qe)^{2i\pi}=p^{2i\pi} , \text{ since $e^{2i\pi}=1$:} \\
&q^{2i\pi}=p^{2i\pi}, \text{since the exponents are the same:} \\
&q=p
\end{align}
that would imply $e=p/q=1$. But nowhere in the "proof" uses the fact that $p,q$ are integers. If we take $p,q$ complex $e$ might not even be a number.
Where is the mistake?

A: You went wrong in the last step. As you're fully aware, $e^{2i \pi} = 1$, just as $e^0 = 1$. This means that the complex exponential function is no longer injective, literally meaning that $e^z = e^w$ no longer implies $z = w$, with $z = 2 i \pi$ and $w = 0$ being a counterexample.
So, what does $e^z = e^w$ actually imply? We have
$$e^z = e^w \implies \frac{e^z}{e^w} = 1 \implies e^{z - w} = 1.$$
If we write $z - w = x + iy$, where $x, y \in \Bbb{R}$, this yields
$$1 = e^{x + iy} = e^x(\cos(y) + i \sin(y)),$$
which implies $e^x = 1$ from taking the modulus of both sides, and $y = 2\pi k$ for some integer $k$. Since $x \in \Bbb{R}$, we must have $x = 0$, so
$$z - w = 2 i \pi k$$
for some $k \in \Bbb{Z}$.
So, given $p^{2 i \pi} = q^{2 i \pi}$, we can conclude, by definition of complex exponentiation,
$$e^{2 i \pi \log p} = e^{2 i \pi \log q}$$
and thus, for some $k \in \Bbb{Z}$,
$$2 i \pi \log p = 2 i \pi \log q + 2 i \pi k \implies \log(p / q) = k \implies p / q = e^k.$$
In this case, $k = 1$; there is no contradiction.

A: $$q^{2\pi i}=p^{2\pi i}\to e^{i\cdot 2\pi \ln q}=e^{i \cdot 2\pi \ln p}\tag{1}$$
Remember that $e^{i\theta}=\cos\theta +i\sin \theta$:
Because of the periodicity of $\cos$ and $\sin$, the only conclusion you can draw from $(1)$ is:
$$2\pi\ln(q)=2\pi(\ln(p)+k) : k\in \Bbb Z$$
Which we may simplify to: $$\ln(q)-\ln(p)=k\implies \frac qp = e^k$$
Here, $k=-1$ trivially.


text:
Q: ReactJS - Labeling multi dimension array with chartJS-2 The chart below I'm trying to create:

I am trying to add labels to my chart but it's showing as undefined. When I enter
  labels: ["1", "2", "3"],

it gives the variable '1' to all the 1st variables. Any help on this would be brilliant. Thank you

const DummyChart = () => (
  <Doughnut data={data} options={options} width={360} height={360} />
);

 const data = {
  datasets: [
    {
      label: "Dummy 1",
      data: [487, 189],
      backgroundColor: ["rgba(0, 193, 189)"],
      borderColor: ["rgba(0, 193, 189)"],
      borderWidth: 1
    },
    {
      label: "Dummy 2",
      data: [236, 764],
      backgroundColor: ["rgba(0, 135, 136)"],
      borderColor: ["rgba(0, 135, 136)"],
      borderWidth: 1
    },
    {
      label: "Dummy 3",
      data: [811, 189],
      backgroundColor: ["rgba(0, 193, 189)"],
      borderColor: ["rgba(0, 193, 189)"],
      borderWidth: 1
    }
  ]
};

const options = {
  responsive: true,
  legend: {
    display: false
  },
  rotation: Math.PI,
  circumference: Math.PI,
  cutout: 50
};

export default DummyChart;

A: As per react-chartjs-2 examples there is a separate key named labels for that. You also have to use the tooltips options so you will be able to customize your labels. See the working example I made below:

var Doughnut = reactChartjs2.Doughnut;

const DummyChart = () => ( <Doughnut data={data} options = {options} width={360} height={360} />);

const data = {
  labels: [
    'Dummy 1',
    'Dummy 2',
    'Dummy 3',

  ],
  datasets: [{
      data: [487, 1000],
      backgroundColor: ["rgba(0, 193, 189)"],
      borderColor: ["rgba(0, 193, 189)"],
      borderWidth: 1
    },
    {
      data: [236, 1000],
      backgroundColor: ["rgba(0, 135, 136)"],
      borderColor: ["rgba(0, 135, 136)"],
      borderWidth: 1
    },
    {
      data: [811, 1000],
      backgroundColor: ["rgba(0, 193, 189)"],
      borderColor: ["rgba(0, 193, 189)"],
      borderWidth: 1
    }
  ]
};

const options = {
  responsive: true,
  legend: {
    display: false
  },
  rotation: Math.PI,
  circumference: Math.PI,
  cutout: 50,
  tooltips: {
    callbacks: {
      label: function(item, data) {
        return data.labels[item.datasetIndex] + ' ' + data.datasets[item.datasetIndex].data[0] + '/' + data.datasets[item.datasetIndex].data[1]
      }
    }
  }
};
ReactDOM.render(
  <DummyChart /> ,
  document.getElementById('app')
);

A: Have you tried using point Labels on the chart. Additional chart js contains a label plugin which allows for more customization.
You can install it using this - npm i chartjs-plugin-labels.
Heres a link to a few demo's - https://emn178.github.io/chartjs-plugin-labels/samples/demo/


text:
Q: Intersystems Caché with Java Gateway - Pass parameter as java.io.FileInputStream In my project I'm using a integration of Intersystems Caché with Java by a Java Gateway, it's basically maps JARs and create a class proxies in Caché to access Java classes into the JAR.
A class in Java has a parameter of type FileInputStream , my question is how I should send this parameter Caché proxie ? What type of data in Caché represent the FileInputStream in Java?
Regards,
Lucas Boeing Scarduelli

A: When you create proxy for that java, should be created cache-class for FileInputStream too.
simple java class, with FileInputStream as a type for an argument in function
package org.daimor;

import java.io.FileInputStream;
import java.io.IOException;

public class test {

    public long sizeStream(FileInputStream stream)
    {
        try {
            return stream.getChannel().size();
        } catch (IOException ex)
        {
            return -1;
        }
    }
}

then I created projection for this jar file in Caché Studio. And wrote a code
Set gateway = ##class(%Net.Remote.Gateway).%New()
Do gateway.%Connect("127.0.0.1", 55555)

Set file = ##class(java.io.FileInputStream).%New(gateway, "c:\test.txt")
Set javaObj=##class(org.daimor.test).%New(gateway)
Set size=javaObj.sizeStream(file)

so, it works well.


text:
Q: Jquery load() and Manually bootstrapping AngularJS I have a website full of exercises. I'm using jQuery load() to load parts of pages when a link on my website is clicked.
This takes the relevant part of the wanted page (the exercise itself) and puts it in a div for the user to interact with. While this works wonderfully for most of the website, since the vast majority is written in php, I'm trying to get it to work with the parts that use AngularJS as well.
I used this question as a starting point: AngularJS + JQuery : How to get dynamic content working in angularjs
It worked fairly well but only for one exercise. I think that manually bootstrapping angularJS could fix my problem but so far have had issues. How can I manually bootstrap my angular app upon jQuery load?
Here's some of what I've tried so far but it doesn't work:
irscript.js (ir is the name of the exercise) relevant code:
var ir = angular.module("ir", []);
ir.controller('MainCtrl', function($scope) {
//application logic.
});
angular.element(document).ready(function() {
angular.bootstrap(document, ['ir']);
});

index.html relavent code:

The hope is that irscript.js can be replaced by a function that returns the proper script for the loaded exercise at some point but just getting the above to work would be amazing.


text:
Q: Using git svn, I just rebased feature branch onto master and fast forwarded master. How do I check that my master's history is linear? I'm using git svn and I have two local branches: master and feature.  My feature is done and now I want it to be part of the master branch.  I think I'm supposed to do this:
git checkout feature
git rebase master
git checkout master
git merge feature --ff-only

Assuming that's right, I should be able to git svn dcommit master back to the svn repo.  But, is there a way to make sure my master is in the correct state before I attempt that?  Specifically, I want to make sure my master's history is linear.  How can I do that?
I tried running
git log --decorate --graph --oneline

But the output is massive and I'm not sure how to interpret it.  I think it may contain all the history of my svn repo.  All I want to see is the history of my local master to make sure it's linear.

A: The output of
git log --merges

will be empty if your history is linear from your current HEAD back.


text:
Q: c++11 multi threading vs boost_thread I am a beginner of c++ parallel computing. However, my project requires that I would need to use c++98 (stdlibc++) for it. I search online and it seems most of the tutorials is based on c++11 thread. I noted that boost_thread is an implementation for c++98 but there seems to be much less available tutorial. So I would like to ask what is the best way for me to learn and implement parallel computing for my project.
Eventually, my project would require calculations based on hundreds of cores and computing nodes. Would multi-threading be sufficient or do I have to use Boost_MPI? Thank you.

A: If you are limited to c++98 that means that you won't have all the thread managing and locking mechanisms as part of the language.
Therefore you will have to implement them by yourself based on available OS APIs.
There are different APIs for Windows and Linux.
Here is an example of C++ wrapper for Linux pthread library.
And this is an example of C++ wrapper for Windows Threads.
So your project won't be portable unless you create (or find somewhere) a class which hides these libraries behind a common interface under which it implements the same logic for Windows and Linux differed by #ifdef WINDOWS / #ifdef LINUX.
Regarding

what is the best way for me to learn and implement parallel computing
  for my project.

There is no a correct answer for this. Look for some basic Multi Threading tutorials. Try to implement few simple programs (before you move to a big project) and come back when you face difficulties with more specific questions.
I have heard about boost but never used it so I can't provide any feedback on that. But again, you need to ask specific question. You can provide some specific requirements from your project and ask question based on them.
Anyway dive into boost documentation, you can find there threads related libraries (also pay attention for boost usage license).


text:
Q: Using imported data in further calculations I have quite a lot of data in an Excel file, which I have to use in further calculations. The transformation should map a data point with thre coordinates into a two coordinate result. Example: $(r,g,b)\mapsto(r/2 + g, r \, tan(\pi/3)/2)$.
So far I have tried the following, but it doesn't work since the result is the same as the imported data.
coords[{r_, g_, b_}] := {r/2 + g, r Tan[Pi/3]/2};
data = Import["file.xlsx"]
coords[data]

Edit
OK, i'm sorry for not posting the data earlier:
{{{"0.1", "0.65", "0.25"}, {"0.8", "0.1", "0.1"}, {"0.7", "0.15", "0.15"},
  {"0.6", "0.1", "0.3"}, {"0.5", "0.2", "0.3"}, {"0.4", "0.1", "0.5"},
  {"0.3", "0.3", "0.4"}, {"0.2", "0.1", "0.7"}, {"0.1", "0.8", "0.1"}}}

A: You have two issues... first, the data is in the form of strings, so needs to be changed into numbers (this is the ToExpression). The Flatten removes an extra pair of brackets, and then you can Map the coords function onto the data. The symbols /@ are shorthand for this mapping.
stringData = {{{"0.1", "0.65", "0.25"}, {"0.8", "0.1", "0.1"},
 {"0.7", "0.15", "0.15"}, {"0.6", "0.1", "0.3"}, {"0.5", "0.2", "0.3"},
 {"0.4", "0.1", "0.5"}, {"0.3", "0.3", "0.4"}, {"0.2", "0.1", "0.7"}, {"0.1", "0.8", "0.1"}}};
data = Flatten[ToExpression[stringData], 1];
coords[{r_, g_, b_}] := {r/2 + g, r Tan[Pi/3]/2};
coords /@ data

Your output is then:
{{0.7, 0.0866025}, {0.5, 0.69282}, {0.5, 0.606218}, {0.4, 0.519615},
 {0.45, 0.433013}, {0.3, 0.34641}, {0.45, 0.259808}, {0.2, 0.173205}, {0.85, 0.0866025}}


text:
Q: Intermittent crash when performing fetch on core data I have a published app that is occasionally crashing when performing a core data fetch. I know where the crashes are occurring, however I can't figure out why they are happening.
The app uses a tab view controller, and the crash occurs in a tab that has a tableView as the initial view. Because I need this tableView to update whenever data is changed elsewhere in the app, I'm performing a fetch in the viewWillAppear method.
Here is the relevant code:
lazy var fetchedResultsController: NSFetchedResultsController<Day> = {
    let request: NSFetchRequest<Day> = Day.fetchRequest()
    request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
    request.predicate = NSPredicate(format: "calories > %@", "0")

    let frc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)

    return frc
}()

override func viewWillAppear(_ animated: Bool) {
    do {
        try fetchedResultsController.performFetch()
    } catch {
        print("Could not fetch results")
    }
    tableView.reloadData()
}

And here is an image of the call stack.

I haven't been able to recreate the crash on my device or on the simulator, so I really don't know how to go about fixing this bug. I'd appreciate any advice on solving this.
Here's a screenshot of the calories attribute in the core data model.

Here's the class method for creating a Day entity.
    class func dayWithInfo(date: Date, inManagedContext context: NSManagedObjectContext) -> Day {
    let defaults = UserDefaults.standard

    let formatter = DateFormatter()
    formatter.dateStyle = .full
    let dateString = formatter.string(from: date)

    let request: NSFetchRequest<Day> = Day.fetchRequest()
    request.predicate = NSPredicate(format: "dateString = %@", dateString)

    if let day = (try? context.fetch(request))?.first {
        if let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date()) {
            // Update the macro goals if the date is the current or future date
            if date > yesterday {
                day.proteinGoal = defaults.double(forKey: Constants.UserDefaultKeys.proteinValueKey)
                day.carbohydrateGoal = defaults.double(forKey: Constants.UserDefaultKeys.carbohydratesValueKey)
                day.lipidGoal = defaults.double(forKey: Constants.UserDefaultKeys.lipidsValueKey)
                day.fiberGoal = defaults.double(forKey: Constants.UserDefaultKeys.fiberValueKey)
                day.calorieGoal = defaults.double(forKey: Constants.UserDefaultKeys.caloriesValueKey)
            }
        }

        return day
    } else {
        let day = Day(context: context)

        // Set the date as a string representation of a day
        day.dateString = dateString
        day.date = date

        // Set the calorie and macronutrient goals from user defaults
        day.proteinGoal = defaults.double(forKey: Constants.UserDefaultKeys.proteinValueKey)
        day.carbohydrateGoal = defaults.double(forKey: Constants.UserDefaultKeys.carbohydratesValueKey)
        day.lipidGoal = defaults.double(forKey: Constants.UserDefaultKeys.lipidsValueKey)
        day.fiberGoal = defaults.double(forKey: Constants.UserDefaultKeys.fiberValueKey)
        day.calorieGoal = defaults.double(forKey: Constants.UserDefaultKeys.caloriesValueKey)

        // Creat meals and add their ralationship to the day
        if let meals = defaults.array(forKey: Constants.UserDefaultKeys.meals) as? [String] {
            for (index, name) in meals.enumerated() {
                _ = Meal.mealWithInfo(name: name, day: day, slot: index, inManagedContext: context)
            }
        }
        return day
    }

}

A: Allow me to posit a theory about what I think is happening. I might be making incorrect assumptions about your project, so please correct anything I get wrong. You likely understand all the below, but I'm trying to be thorough, so please excuse anything obvious.
You have a calories attribute of your model class that is implemented as an optional attribute with no default at the model level. Something like the below.

You also do not implement func validateCalories(calories: AutoreleasingUnsafeMutablePointer<AnyObject?>, error: NSErrorPointer) -> Bool in your managed object subclass, so it's possible to save an instance with a nil (remember that Core Data is still Objective-C, so your Double Swift attribute is an NSNumber in Core Data, so nil is perfectly valid for an optional attribute).

You can specify that an attribute is optional — that is, it is not required to have a value. In general, however, you are discouraged from doing so — especially for numeric values (typically you can get better results using a mandatory attribute with a default value — in the model — of 0). The reason for this is that SQL has special comparison behavior for NULL that is unlike Objective-C's nil. NULL in a database is not the same as 0, and searches for 0 will not match columns with NULL.

At this point, it would be easy to confirm the hypothesis. Simply edit the SQLite database used for Core Data by your app in the simulator and set the calories attribute of a single record to null and see if you crash in the same way.
If so, do a Core Data migration on your next release and remove the Optional designation on the model attribute and provide a Default value of zero.


text:
Q: Subset set a dataframe column based on first row value in R I have a 1 row dataframe called ff.
A   B   C   D   E   F
2   5   9   1   7   6

How do I create a single column dataframe (ColContribs) when the a column equals 7
E
7

Like that..?
I was using
ColContribs <- ff[,ff[1,]==7]

but i'm getting this error
Error in Ops.data.frame(ff[1, ], ColContribs) :
'==' only defined for equally-sized data frames

Paul

A: I tried to create a similar case and it worked as below.
library(tidyverse)

a <- 2
e <- 7

lol <- cbind(a,e) %>% data.frame()

ColContribs <- lol[,lol[1,]==7] %>% data.frame()

A: ff <- data.frame(A = 2, B = 5, C = 9, D = 1, E = 7, F = 6)

ColContribs <- ff[,ff[1,] == 7, drop = FALSE]

Because it's a single element data frame, you need to specify drop == FALSE


text:
Q: Get a particular column value count in oracle with inner join I am having 2 tables by joining both i am getting some columns and values
 Select
    tbl_orderdetails.category_name,
    tbl_orderdetails.branch_name,
    tbl_ordermaster.created_date,
    tbl_ordermaster.user_id,
    tbl_orderdetails.order_details_id,
    tbl_orderdetails.branch_id
 From tbl_orderdetails Inner Join tbl_ordermaster ON
    tbl_orderdetails.order_master_id=tbl_ordermaster.ordermasterid
 where tbl_ordermaster.user_id='12'

I want to get number of times a particular branch name came.I used count but its not working and i want only max number of times the branch name came and top 3 to be displayed .
Eg:
vellore=100,
chennai=18,
tvl=80,
harithuwar=90

It should display only
vellore
harithwar
tvl

sample data
orderdetails
orderdatailsid | order_master_id |branchname| category| branchid
1   |   112 |   vellore |   nad |   123
2   |   112 |   vellore |   hu  |   123
3   |   113 |   chennai |   ji  |   121
4   |   112 |   vellore |   hi  |   123
5   |   134 |   tvl |   ui  |   145
6   |   134     |   tvl |   jo  |   145
masterdetails
ordermasterid  |  userid
112        |      12
113 |    13
134  |        14

A: Try this
SELECT T.*,S.* FROM
(
  Select TD.category_name,TD.branch_name,TM.created_date,TM.user_id,TD.order_details_id,TD.branch_id
  From tbl_orderdetails TD Inner Join tbl_ordermaster TM ON
    TD.order_master_id = TM.ordermasterid
  Where TM.user_id='12'
) T Left Join
(
  Select T1.branch_name,Count(T1.branch_name) As No_Of_Branch
  From tbl_orderdetails T1 Inner Join tbl_ordermaster T2 ON
       T1.order_master_id = T2.ordermasterid
  Where T2.user_id='12'
  Group By T1.branch_name
) S On S.branch_name = T.branch_name

Update
If you want to get Max of count
Try this
SELECT T.*,S.* FROM
(
  Select TD.category_name,TD.branch_name,TM.created_date,TM.user_id,TD.order_details_id,TD.branch_id
  From tbl_orderdetails TD Inner Join tbl_ordermaster TM ON
    TD.order_master_id = TM.ordermasterid
  Where TM.user_id='12'
) T Inner Join
(
SELECT M.branch_name,Max(M.No_Of_Branch) FROM
  (
    Select T1.branch_name,Count(T1.branch_name) As No_Of_Branch
    From tbl_orderdetails T1 Inner Join tbl_ordermaster T2 ON
         T1.order_master_id = T2.ordermasterid
    Where T2.user_id='12'
    Group By T1.branch_name
  ) M Group By M.branch_name
) S On S.branch_name = T.branch_name

A: Try this Count is working good below the Examples,
create table orderdetails(orderdatailsid number, order_master_id number,branchname varchar(20), category varchar(20), branchid number);
insert into orderdetails values (1 , 112 ,'vellore','nad', 123);
insert into orderdetails values (2 , 112 ,'vellore','hu', 123);
insert into orderdetails values (3 , 113 , 'chennai','ji', 121);
insert into orderdetails values (4 , 112 , 'vellore' ,'hi', 123);
insert into orderdetails values (5 , 134 , 'tvl','ui', 145);
insert into orderdetails values (6 , 134 , 'tvl','jo', 145);
insert into orderdetails values (7 , 113 , 'chennai','ji', 121);
insert into orderdetails values (8 , 112 , 'vellore','hi', 123);
insert into orderdetails values (9 , 134 , 'tvl','ui', 145);

select * from orderdetails;
create table masterdetails(ordermasterid number, userid number);
insert into masterdetails values(112 , 12);
insert into masterdetails values(113 , 13);
insert into masterdetails values(134 ,14);

select * from masterdetails;
SELECT * FROM (
 SELECT orderdetails.branchname, count(*)   as Cout
            From orderdetails left Join masterdetails ON
            orderdetails.order_master_id=masterdetails.ordermasterid
            group by orderdetails.branchname
            order by cout desc
            ) WHERE ROWNUM <4;


text:
Q: ASP.NET MVC - hide response headers I'm building an ASP.NET MVC 5 app using Visual Studio 2015 Update 3. I need to hide these response headers that are sent back to the client:

*

*Server

*X-AspNet-Version

*X-AspNetMvc-Version

Before marking my question as a duplicate, please consider the following:

*

*I need to not only strip the headers from dynamic content but also from static ones; the solutions listed below don't seem to work on static. In other words, images, CSS, JS, etc., will still display the headers. Some solutions fail on this.

*"Bad requests" will cause other solutions to break and display the headers.

*If possible, not install anything on the server. The recommended tools include UrlRewrite and UrlScan [obsolete product]. If necessary, I can live with this path however. But which one?

I've considered the following solutions,

*

*Remove Server Response Header IIS7 - many answers; it seems most point to running a tool on the server

*https://www.dionach.com/blog/easily-remove-unwanted-http-headers-in-iis-70-to-85 - custom module

*http://www.henrylee.link/2015/09/10/how-to-remove-all-information-about-iis-server-from-response-header/

*https://github.com/Dionach/StripHeaders/
As you can see, the posts are many, the paths confusing for my requirements. If I have to install a tool, which one?


text:
Q: Quotient of quasi-isomorphic cdga's I'm looking for a theorem about quotient of quasi-isomorphic cdga's:
Let $A, B$ be two cdga's (commutative differential $\mathbb Z$-graded algebra) of nonpositive degrees, and $\mathfrak m \subset A, \mathfrak n \subset B$ be maximal ideals closed under differentials. Suppose $\phi: A \to B$ is a quasi-isomorphism of cdga's and $\phi(\mathfrak m) \subset \mathfrak n$. Is the induced map $\phi: A/ \mathfrak m^2 \to B/\mathfrak n^2$ still a quasi-isomorphism?
I guess more assumptions on $A,B, \mathfrak m, \mathfrak n$ might be needed. Any theorems of this type would be helpful.

A: Let $A$ be the complex $\Bbb Q$ concentrated in degree zero, and let $B$ be the CDGA $(\Bbb Q[t] \to \Bbb Q[t] dt)$ concentrated in (cohomological) degrees $0$ and  $1$, with de Rham differential $d f(t) = f'(t) dt$. Then $B$ is a commutative DGA under the wedge product, and the natural inclusion $\Bbb Q \to \Bbb Q[t] \subset B$ becomes a quasi-isomorphism of CDGAs.
The only maximal ideal $\mathfrak m \subset A$ is zero, whereas there are a lot of maximal ideals of $B$ of the form $\mathfrak n = ((f(t)) \to \Bbb Q[t] dt)$ for $(f(t)) \subset \Bbb Q[t]$ a maximal ideal of $\Bbb Q[t]$ generated by a monic irreducible polynomial $f(t)$. The resulting map on quotients is $\Bbb Q \to \Bbb Q[t] / (f(t))$, which is an isomorphism if and only if $f(t)$ is linear; for example, we could take $f(t) = (t^2 + 1)$.

For a positive result, you could ask about CDGAs concentrated in nonpositive (cohomological) degree such that $\mathfrak m$ and $\mathfrak n$ are closed under the differential; then any maximal ideal automatically contains all elements in nonzero degree.


text:
Q: What starts a hot observable sequence in reactive expressions So, in the following example from RxJS on GitHub, when is the mouse move observable 'activated', by which I mean, what triggers it to start sampling the mousemove event?
I thought the subscribe would mark the start of the sequences for all the observables in mousedrag, but that does not seem to be the case. Obviously, there are mousemove events before the mousedown, but these events are never used.
var dragTarget = document.getElementById('dragTarget');

// Get the three major events
var mouseup   = Rx.Observable.fromEvent(dragTarget, 'mouseup');
var mousemove = Rx.Observable.fromEvent(document,   'mousemove');
var mousedown = Rx.Observable.fromEvent(dragTarget, 'mousedown');

var mousedrag = mousedown.flatMap(function (md) {
    // calculate offsets when mouse down
    var startX = md.offsetX, startY = md.offsetY;

    // Calculate delta with mousemove until mouseup
    return mousemove.map(function (mm) {
        mm.preventDefault();

        return {
            left: mm.clientX - startX,
            top: mm.clientY - startY
        };
    }).takeUntil(mouseup);
});

// Update position
var subscription = mousedrag.subscribe(function (pos) {
    dragTarget.style.top = pos.top + 'px';
    dragTarget.style.left = pos.left + 'px';
});

Any insight would be appreciated.

A: I'm a big fan of RxJS because of the answer to your question!

...when is the mouse move observable 'activated', by which I mean, what triggers it to start sampling the mousemove event?

The mouse move observable is "activated" (the real term is "subscribed to") at the moment that is needed and then disposed of the moment it is not!  The exact location that the event binding occurs in the example you provided is after
return mousemove.map(function (mm) { ... })
is called (which isn't called until after mousedrag.subscribe is called).
If you look in the code for observable.map, you will see that the parent (mousemove in this case) is subscribed to and the function passed into map is called inside its onNext event.
If you dig deep down the bunny hole, you'll come across Observable.fromEvent which is the exact location where the event listening occurs, but for all intents and purposes, the subscribe method called in the observable.map function is where it is "activated".
Finally, the .takeUntil(mouseup) method that is called at the end of the .map chain is where everything gets cleaned up and disposed. The onNext for that observable will dispose of the previous subscription, which in the case of the example, would be the .map function aka the event listener.  Once a mouseup event occurs, the subscription for mousemove is disposed of and "deactivated".
To test this, you can Set breakpoints at var subscription = ..., return mousemove.map and mm.preventDefault();, and they would be hit in this order:

*

*var subscription = ...

*Mouse down

*return mousemove.map

*mouse move

*mm.preventDefault();

*mouse up

*mouse move, no breaking
Let me know if that makes sense, or if you have any questions about what I posted.  I can clarify anything that you still don't understand.
Good luck!


text:
Q: VHDL Timer Synchronous/Asynchronous load speed issue I am trying to code a i2c like bus on a spartan 6. I have a bunch of states that i time using the folowing counter.
  -- Timer --
  TimesUp <=  true when TmrCnt = 0 else
             false when TmrCnt /= 0 else
             false;
  tmrProc: process(ClkxC, SetTmr, TmrInit)
  begin
    if (rising_edge(ClkxC)) then
      if (SetTmr = '1') then
        TmrCnt <= TmrInit;
      elsif (TmrCnt > 0) then
        TmrCnt <= TmrCnt - 1;
      end if;
    end if;
  end process;

The problem is that my state machine is clocked on the same clock and for some short duration states it just blasts through as if the timer is not set in time.
So I tried this:
  -- Timer --
  TimesUp <=  true when TmrCnt = 0 else
             false when TmrCnt /= 0 else
             false;
  tmrProc: process(ClkxC, SetTmr, TmrInit)
  begin
    if (SetTmr = '1') then
      TmrCnt <= TmrInit;
    elsif (rising_edge(ClkxC)) then
      if (TmrCnt > 0) then
        TmrCnt <= TmrCnt - 1;
      end if;
    end if;
  end process;

Now it simulates just fine, but when I try to implement i get an error message saying that:

   This design contains one or more registers/latches that are directly
   incompatible with the Spartan6 architecture. The two primary causes of this is
   either a register or latch described with both an asynchronous set and
   asynchronous reset, or a register or latch described with an asynchronous
   set or reset which however has an initialization value of the opposite
   polarity (i.e. asynchronous reset with an initialization value of 1).

I really don't know how to make the timer load fast enough without braking the rules of the spartan 6.

A: The warning has been explicitly described in Xilinx WP309 Targeting and Retargeting Guide for Spartan-6 FPGAs [P9-11].
To reduce cost of the overall architecture, slices in Spartan-6 FPGAs do not have a REV
pin. As a result, flip-flops no longer implement both a set signal and a reset signal. In
addition, a register with a set or reset signal can only have an initialization value of
the same polarity. For example, a flip-flop with an asynchronous reset can only have an
initialization value of 0.

That is to say, the following kinds of registers/latches are NOT RECOMMENDED when using Xilinx Spartan-6 FPGAs:
      ______|______
      |    Set    |
      |           |
   ---| D       Q |---      -- 1. a register/latch with both ASYNCHRONOUS
      |         _ |               set and reset signals
   ---|>Clk     Q |o--      -- NOT RECOMMENDED
      |           |
      |   Reset   |
      |___________|
            |

    -- 2. a register/latch described with an ASYNCHRONOUS set/reset which
          however has an initialization value of the opposite polarity

    -- The default value of reg is 0 which is the left
    -- bound value of the integer type definition.
    signal reg: integer range 0 to 7;   <-----
                                              |
    process (clk, reset)                      |___  opposite
    begin                                     |     NOT RECOMMENDED
       if (reset = '0') then                  |
          reg <= 7;                     <-----
       elsif ( rising_edge(clk) ) then
          reg <= val;
       end if;
    end process;

Solutions recommended by Xilinx:
 1. Remove either the set or reset from all registers and latches
    if not needed for required functionality
 2. Modify the code in order to produce a synchronous set and/or
    reset (both is preferred)
 3. Ensure all registers have the same initialization value as the
    described asynchronous set or reset polarity
 4. Use the -async_to_sync option to transform the asynchronous
    set/reset to synchronous operation
    (timing simulation highly recommended when using this option)

In your design, you can either initialize TmrCnt to TmrInit or count TmrCnt in an upward direction.

A: Moving from the first (synchronous) approach to the second (asynchronous set) is rarely the right way to solve the problem; regardless of the Spartan-6 economies on reset logic. Indeed I would justify them on grounds of ... "don't do that".
Instead, look at the statement "The problem is that my state machine is clocked on the same clock and for some short duration states it just blasts through as if the timer is not set in time."
Firstly, there is nothing short duration about I2C signals, unless perhaps this is a multi-hundred MHz derivative of it...
Secondly, one thing VHDL does really well is synchronous design, so "blasting through" without resetting the counter points at something else : possibly the signal assignment rules referred to here.
I suspect this is causing issues where the state machine is setting SetTmr to communicate with the counter in a separate process; so the counter sees SetTmr one cycle later, and that cycle delay is causing the observed mis-behaviour because TimesUp has the wrong value during that cycle.
One answer - a pattern I use a lot - is simply to roll the timer into the SM process itself; then you set it directly and save the handshaking logic and a separate process...
StateMch : process(Clock)
  begin
    if rising_edge(Clock) then
      -- default actions
      if Timer > 0 then
        Timer <= Timer - 1;
      end if;

      -- state machine
      case State is
      when Start_Wait =>
        Timer <= My_Delay;
        State <= Waiting;
      when Waiting =>
        if Timer = 0 then
          State <= Done;
        end if;
      when others =>
        State <= Start_Wait;
      end case;

    end if;
  end process;

Apart from being simpler and (I find) easier to understand than a huge collection of tiny processes, this allows several states to use the same timer to generate different delays.


text:
Q: How does this su -c "..." command seem to pass two commands instead of one? I am trying to understand the script below and I am confused about the su line. I understand the postgres command line arguments.
when I do man su the manual says

-c, --command=COMMAND
                pass a single COMMAND to the shell with -c

However the line with the su - postgres -c ... seems to contain two commands

*

*first one setting the LD_LIBRARY environment variable

*second one calling pg_ctl

So are there two commands being passed with -c or one ?
start()
{
        echo $"Starting PostgreSQL 9.1: "
        su - postgres -c "LD_LIBRARY_PATH=/opt/PostgreSQL/9.1/lib:$LD_LIBRARY_PATH /opt/PostgreSQL/9.1/bin/pg_ctl -w start -D \"/opt/PostgreSQL/9.1/data\" -l \"/opt/PostgreSQL/9.1/data/pg_log/startup.log\""

        if [ $? -eq 0 ];
        then
                echo "PostgreSQL 9.1 started successfully"
                exit 0
        else
                echo "PostgreSQL 9.1 did not start in a timely fashion, please see /opt/PostgreSQL/9.1/data/pg_log/startup.log for details"
                exit 1
        fi
}

A: It's a single command passed to the shell. The shell allows you to set environment variables on a per-command basis, eg:
PGPORT=5433 psql

su invokes the shell with its argument, so:
su -c 'PGPORT=5433 psql'

is like doing:
su
exec bash -c 'PGPORT=5433 psql'

Frankly, I tend to prefer using sudo, which makes setting environment variables easy and handles commands with complex quoting properly because it doesn't go via the shell.


text:
Q: AWS Cognito: dealing with token expiration time I am experimenting with Cognito and when I thought it was starting to be OK, I am facing the issue of (Google) token expiring after 1 hour.
When I start with a clean device, I can sign up, use the app for 1 hour, then as soon as I need to refresh a dataset, I get and error saying the the token is not authorised.
Are there any example on how to deal with this?
Is it really something the app developers should be doing?
I was expecting the SDK to manage such things in the background.
Is it meaning that we have to check the credentialsProvider.getSessionCredentitalsExpiration() before each dataset synchronisation ?
Many thanks,
JM
Edit 1 : Added code
I do have a SigninActivity, but it is only called when no credentials exists at all, in theory only once the first time the user logs in.
It is built as follows (removed useless bits).
So what happens is that I authenticate right the first time, but as I never enter this activity again, maybe something is missing.
But there must be a way to refresh this token silently?
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.signin);

    // Aws Credential provider
    credentialsProvider = new CognitoCachingCredentialsProvider(
            getApplicationContext(), // Context
            getString(R.string.aws_identity_pool), // Identity Pool ID
            Regions.EU_WEST_1 // Region
    );

    // Google connect
    findViewById(R.id.signin_with_google_btn).setOnClickListener(this);

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestProfile()
            .requestIdToken(getString(R.string.google_server_client_id))
            .requestId()
            .build();

    // Build a GoogleApiClient with access to the Google Sign-In API and the
    // options specified by gso.
    googleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this )
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

    SignInButton signInButton = (SignInButton) findViewById(R.id.signin_with_google_btn);
    signInButton.setSize(SignInButton.SIZE_WIDE);
    signInButton.setScopes(gso.getScopeArray());
    signInButton.setColorScheme(SignInButton.COLOR_DARK);
}

@Override
public void onClick(View view) {
    this.signinWithGoogle();
}

/**
 * Triggers Google signin
 */
private void signinWithGoogle() {
    Log.v(this, "Signing in with Google...");

    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
    this.startActivityForResult(signInIntent, GOOGLE_SIGN_IN);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GOOGLE_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        this.handleGoogleSignInResult(result);
    } else {
        // Other stuff
    }
}

/**
 * Handle Google sign in result
 */
private void handleGoogleSignInResult(GoogleSignInResult result) {

    if (result.isSuccess()) {

        Log.v(this, "Successfully logged in with Google...");

        GoogleSignInAccount acct = result.getSignInAccount();
        Log.v(this, "Signed in as %s / %s (token %s)", acct.getDisplayName(), acct.getEmail(), acct.getIdToken());
        Map<String, String> logins = new HashMap<>();
        logins.put("accounts.google.com", acct.getIdToken());
        Log.v(SigninActivity.this, "Google token <<<\n%s\n>>>", logins.get("accounts.google.com"));
        credentialsProvider.setLogins(logins);
    } else {
        // Signed out
        Log.w(this, "Failed to authenticate against Google #%d - %s", result.getStatus().getStatusCode(), result.getStatus().getStatusMessage());

        SimpleMessageDialog.show(SigninActivity.this,
                R.drawable.icon,
                R.string.error,
                R.string.sorry_error_signing_you_in_please_try_again,
                R.string.try_again);
    }
}

A: Are you following all the steps documented here? The SDK will get you AWS credentials in exchange of a valid token automatically, but if your Google token is expired, then you need to refresh it.


text:
Q: How to disable the touchscreen in Ubuntu 21.04? I faced a problem after a couple of days that my malfunctioned touchscreen was on unexpectedly, despite setting MatchIsTouchscreen "off" at /usr/share/X11/xorg.conf.d/40-libinput.conf
How to make it disabled just like Ubuntu 20 and the older versions?

A: So after hours of searching a solution to that is keep that configuration MatchIsTouchscreen "off" and to make Xinput runs by default again to apply that configuration.
To disable Wayland:

*

*open the file: sudo nano /etc/gdm3/custom.conf

*uncomment (remove # from): WaylandEnable=false


text:
Q: Need to upgrade my dedicated server. Is this a good deal? I'm looking to upgrade to a better dedicated server at my host LiquidWeb and would like some advice.
I currently have a Pentium 4 3GHZ Hyperthreaded, 2GB RAM, and 2 120GB Hard Drives and have been paying $227/month (I've actually been overpaying, since they have lowered their prices since I first signed up with them, but never pro-rated me..)
My current server is very overloaded. What I really need is more RAM, but apparently I need a processor upgrade to add more ram, so..
They said that I can upgrade to the following setup for $270 a month:
»   Processor: Intel i5-750 Quad Core
»   RAM: 4GB DDR SDRAM
»   HD1: SATA Drive (7,200 rpm) (+250 GB 7200 RPM SATA hard drive)
»   HD2: SATA Backup Drive (+250 GB SATA (7,200 rpm))
»   GUARD: No Remote Backup Needed
»   OS: Windows Server (+Windows 2008 Standard 64-bit) (+No Anti-Virus) (+No MSSQL Software Required.)
»   Bandwidth: 6000GB Monthly Transfer (3000 in + 3000 out) (+100M uplink port)
»   ControlPanel: cPanel/ Web Host Manager - Fully Managed (+ServerSecure) (+Fantastico)
»   SetupFee: No setup fee
»   Monthly Fee: $270.00 /mon
Is this a fairly decent server upgrade for the price?

A: Do you need a dedicated server?
Because there are some really good deals on VPS's around, and personally I dont know if having a physical machine vs virtual would matter. Places like Slice-host linode or gandi.net are great, and really very cheap. I've only used gandi.net, but i've heard good things about the others. Full root access, choice of operating systems etc.


text:
Q: Filter PySpark column containing Null using not contains When filtering a column:
Ex.

Column

DontShow

null

null

using df.filter(~col('Column).contains('DontShow))
Expected result.

Column

null

null

However, this returns nothing. I assume it treats null values differently. Seeing how this works in where I specify it could also be null: df.filter(~(col('Column).contains('DontShow)) | col('Column').isNull())
Out of curiosity why is this? One would assume it would return every row not containing the condition regardless if its null or not.

A: Use isNull
df.where(col('Column').isNull()).show()


text:
Q: Getting an error when defining a list of lists I am trying to define a list in a list so that I can store the following data but getting the error as defined at end.
(x = 50, y = 25)
(x = 33, y => 50)  (x = 66, y = 50)

My code is as follows
// == Classes
public class XYPos
{
  public int x { get; set; }
  public int y { get; set; }
}

public class Positions : List<XYPos>{}

// == Define the data code
var positionGroups = new List<Positions>();

var positions = new List<XYPos>();
positions.Add(new XYPos { x = 50, y = 25});
positionGroups.Add(new List<Positions>(positions)); **

var positions = new List<XYPos>();
positions.Add(new XYPos { x = 33, y = 50});
positions.Add(new XYPos { x = 66, y = 50});
positionGroups.Add(new List<Positions>(positions));

I am getting this error on line **
Argument 1: cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable'

A: I am a bit confused on why you create a class which is a specific list of other classes, but I think you're looking for something along these lines:
var positions = new List<XYPos>();
positions.Add(new XYPos { x = 33, y = 50 });
positions.Add(new XYPos { x = 66, y = 50 });

var positionGroups = new List<List<XYPos>>();
positionGroups.Add(positions);

The "groups" is a list of lists.. So there are multiple (grouped) XY positions within that list.
If you're only looking for a group of XY positions, you have no need for the public class Positions : List<XYPos>{} at all.
Also worth to mention, if you make a list of lists (without any specific identifier on which list that group is about) you might have a lot of looping to do to find a specific item.


text:
Q: Conditional ng-class style applies to all divs I have a list of card numbers for a patient that displays on a modal. If the card is set to be the default card then it should have a grey background - this is based on a value of true for the object.

{{obj.ElectronicPaymentAccountType}} {{trimCardNum(obj.CreditCardNumber)}}

Exp: {{obj.ExpirationDate}}

Important piece:
ng-class="{'chosencard' : obj.PreferredAccount }"

Relevant CSS:
.chosencard {
        background-color: @gray-lighter;
    }

Here you can see that I iterate over the array and retrieve the objects using an ng-repeat and then apply an ng-class on the div inside the table cell to determine if the style is applied. The odd thing is that I do the same exact thing on the span inside the div and it reacts as I expect but the actual div doesn't - why is that?
Here's a screenshot of the behaviour.
P.S. When I click on an individual div the grey background disppears from all the others except the div that I clicked on. And of the four objects that you see above only one of them has a value of true and that's the last card.

A: I can't see how you selecting payment methods but you can do that like in demo below.

var app = angular.module('app', []);

app.controller('homeCtrl', function($scope) {

  $scope.paymentAndShipping = [

    {
      ElectronicPaymentAccountType: "a",
      CreditCardNumber: "155652",
      ExpirationDate: "01/01/2014",
      ElectronicPaymentAccountID: 1
    }, {
      ElectronicPaymentAccountType: "b",
      CreditCardNumber: "155652",
      ExpirationDate: "01/11/2014",
      ElectronicPaymentAccountID: 2
    }, {
      ElectronicPaymentAccountType: "c",
      CreditCardNumber: "1545652",
      ExpirationDate: "21/01/2414",
      ElectronicPaymentAccountID: 3
    }, {
      ElectronicPaymentAccountType: "d",
      CreditCardNumber: "1554652",
      ExpirationDate: "31/01/2024",
      ElectronicPaymentAccountID: 4
    }

  ];

  $scope.PreferredAccount = $scope.paymentAndShipping[0];

  $scope.setDefaultPaymentMethod = function(index) {

    $scope.PreferredAccount = $scope.paymentAndShipping[index];

  }

});
.chosencard {
        background-color: yellow;
    }
td {
border:solid 1px grey
}

{{obj.ElectronicPaymentAccountType}} {{obj.CreditCardNumber}}

Exp: {{obj.ExpirationDate}}

PreferredAccount :
 {{PreferredAccount | json }}


text:
Q: How to delete orphaned Google Calendars + Events? My app performs a one-way sync to Google Calendar. As in, if you create an event in my app it will be added to Google Calendar, but you can't update that event from Google Calendar.
I store all the Google Calendar IDs and Event IDs that their API gives me back so that I can update the calendars + events later.
However, I'm concerned about orphaned records. If, for example, someone deletes an event in my app but either the API request fails to delete the corresponding event from Google Calendar or my app has a bug in it, then that record will become orphaned -- it will exist on Google Calendar but I will have no reference to it.
So what's the best way to delete orphaned records?
Here are my ideas:

*

*Download a list of every single event ID in Google Calendar, fetch all the event IDs out of my database, do a set subtraction to determine which ones are orphaned, and then delete those one-by-one.

*Delete the entire calendar if I notice a mishap, and then re-sync all the events.

The problem with (1) is that it might get quite memory intensive once I've accumulated a lot of events. The problem with (2) is that a full re-sync can take awhile and those events will be missing from Google Calendar while the sync is happening. Plus, I might have a race-condition if users are creating new events during the sync.
What's the best approach? Are there any other solutions?


text:
Q: WLAN issue: wlan auto-connects upon entering function body I have a Pycom Lopy 4 that will recieve sensor readings from another MCU and structure the received data before sending it on to an MQTT server. To achieved that, I initialised the WLAN mode of my LoPy4 to 'STA_AP'.
However, I realised that when i attempted a wlan.disconnect(), and my code enters a function block to deal with the data, wlan.isconnected() returns True again! I know this because I placed a few print statements within the function body to check for connectivity. Below is my code:
import usocket
from network import WLAN
import ustruct
from mqtt import MQTTClient
import machine

sensor_dict = {
    0x77 : "bme280"
    # Add more sensors here #
    }

wlan = WLAN()

## Set static IP address for server
wlan.ifconfig(id = 1, config=('192.168.0.104', '255.255.255.0', '192.168.0.1', '192.168.0.1'))

## Set WLAN mode to STA_AP (station & access point)
print("Setting up wlan access point...")
wlan.init(mode = WLAN.STA_AP, ssid = 'server_layer1', auth = (WLAN.WPA2, 'Password123'), channel=7, antenna=WLAN.INT_ANT)
print("wlan mode set up: with WPA2 auth\n")

## -----------------------------This is the function block---------------------------------- ##
def send_data(data_raw):
    print("Unpacking raw data...")
    data = ustruct.unpack('lifff', data_raw)
    loc, sensor_type, temp, press, hum = data

    if wlan.isconnected():
        print("connected1")

    ## Connect to internet
    wlan.connect("Name", auth=(WLAN.WPA2, "hahahahaha"), timeout=5000)
    if wlan.isconnected():
        print("connected3")
    while not wlan.isconnected():
        machine.idle()
    print("Connected to WiFi\n")

    print("Sending data up to MQTT server...")
    client = MQTTClient("xxx123", "io.adafruit.com",user="yoplo", password="xxx123", port=1883)
    client.connect()

    client.publish(topic="yoplo/feeds/{}/{}/temp".format(loc, sensor_dict[sensor_type]), msg=temp, retain = True)

## ---------------------------------End of function block------------------------------------- ##

UDP_IP = "0.0.0.0"
UDP_PORT = 6006

## Set up UDP socket and bind
sock = usocket.socket(usocket.AF_INET,usocket.SOCK_DGRAM) ## UDP
sock.bind((UDP_IP, UDP_PORT))
print('Socket binded.')

data_raw, addr = sock.recvfrom(24) ## buffer size is 24 bytes

## -----------------------------------ran wlan.disconnect() here--------------------------------##
wlan.disconnect()

if wlan.isconnected():
    print("connected2")

send_data(data_raw)
machine.deepsleep(10)

My output was:
Setting up wlan access point...
wlan mode set up: with WPA2 auth

Socket binded.

raw data payload: b'q\x01\x00\x00w\x00\x00\x00\xe1z\xd0Aq\xedzD\x14\xae^B'
source:  ('192.168.0.105', 49258)
connected2
Unpacking raw data...

connected1
connected3
Connected to WiFi

Sending data up to MQTT server...
Traceback (most recent call last):
  File "main.py", line 65, in <module>
  File "main.py", line 43, in send_data
  File "/flash/lib/mqtt.py", line 66, in connect
OSError: [Errno 113] EHOSTUNREACH
Pycom MicroPython 1.18.2.r6 [v1.8.6-849-a210e85] on 2019-05-13; LoPy4 with ESP32
Type "help()" for more information.

'connected1' and 'connected3' were printed, although 'connected2' was not printed. Not sure why, appreciate any assistance!


text:
Q: DatabaseError: no such table: django_template Im getting this error when trying to access a customized version of flatpages in my admin:
DatabaseError: no such table: django_template
On settings I have flatpages, the middleware and of course my custom flatpages installed... what could be the problem?
This is my custom flatpage model and admin, Im trying to get the flatpages to have translations.
Also Im guessing I have to change the templatetag on the flatpage in order to use my custom model...
My flat pages model -> https://gist.github.com/2052903
My flat pages admin -> https://gist.github.com/2052907
and the lookup translation util -> https://gist.github.com/2052919
All suggestions are welcome to change the code or anything...
=== EDIT ===
This is my settings file -> https://gist.github.com/2054598
and this is the complete error traceback -> http://dpaste.com/717679/
This error happens when I try to access the flatpages admin
Thank you all!

A: This is because you have "dbtemplates.loader.Loader" in TEMPLATE_LOADERS, but "dbtemplates" is not is INSTALLED_APPS.
So either add "dbtemplates" to INSTALLED_APPS and syncdb, either remove "dbtemplates.loader.Loader" from TEMPLATE_LOADERS.
Note: if you're going to use dbtemplates, then you should really use JohnnyCache if you don't want database queries at each template load.


text:
Q: class not found: org.springframework.web.servlet.mvc.annotation. DefaultAnnotationHandlerMapping My dispatcher-servlet file is
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
                          http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.2.xsd
                          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
                          http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

 <context:component-scan base-package="com.controller"/>

     <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping

" />

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

after running the application I found the error in server log is
class not found: "org.springframework.web.servlet.mvc.annotation. DefaultAnnotationHandlerMapping"

Someone said me to add appropriate jar files but I already added org.springframework.web.servlet-3.2.2.RELEASE.jar.
and I added all needed jar.

A: Try replacing your bean class with-
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
also remove  <mvc:annotation-driven/> from your xml.
You need to do this if you have upgraded from spring 3.1.x to 3.2.x


text:
Q: Can I plant any fruit in my town? I know I can plant fruit I get from visiting other towns, such as apples or peaches or oranges, but if I plant the coconuts and the durian from the island, will they grow in my town? Or will those trees only grow on the island?

A: All growable fruits can be planted in all towns. There are the following restrictions:

*

*Palm trees only grow on sand, i.e. your beach. Palm trees are Coconut and Banana trees. These are easy to identify by the unique shape and the fact that they produce two fruits at a time, not three.

*

*This includes Bananas and Coconuts

*Deciduous trees (including island fruit!) only grow in dirt, so not on your beach. These are all trees that have 3 fruits per tree, including the island fruit. Even on the island, deciduous trees won't grow in sand (a common mistake).

*

*This includes pears, oranges, cherries, peaches, apples, durians, lyches, lemons,
mangos and persimmons

*You cannot plant Perfect Fruit trees for non-native fruit. Non-native perfect fruits will grow into regular trees of that fruit. Native perfect fruits will grow into trees that grow more perfect fruit before eventually (randomly) dying.

*

*This means to get the most out of perfect fruit (3,000 bells per) you will need to grow lots of native perfect fruit and bring it to a town where it is not native for selling.


text:
Q: Is this data appropriate for keeping in a database? In relation to my previous question where I was asking for some database suggestions; it just occured to me that I don't even know if what I'm trying to store there is appropriate for a database. Or should some other data storage method be used.
I have some physical models testing (let's say wind tunnel data; something similar) where for every model (M-1234) I have:
name (M-1234)
length L
breadth B
height H
L/B ratio
L/H ratio
...
lot of other ratios and dimensions ...
force versus speed curve given in the form of a lot of points for x-y plotting
...
few other similar curves (all of them of type x-y).

Now, what I'm trying to accomplish is store that in some reasonable way, so that the user who will be using the database can come and see what are the closest ten models to L/B=2.5 (or some similar demand). Then for that, somehow get all the data of those models, including the curve data (in a plain text file format).
Is a sql database (or any other, for that matter) an appropriate way of handling something like this ? Or should I take some other approach ?
I have about a month to finish this, and in that time I have to learn enough about databases as well, so ... give your suggestions, please, bearing that in mind. Assume no previous knowledge on the subject, whatsoever.

A: I think what you're looking for is possible. I'm using Postgresql here, but any database should work. This is my test database

CREATE TABLE test (
    id serial primary key,
    ratio double precision
);
COPY test (id, ratio) FROM stdin;
1   0.29999999999999999
2   0.40000000000000002
3   0.59999999999999998
4   0.69999999999999996
.

Then, to find the nearest values to a particular ratio

select id,ratio,abs(ratio-0.5) as score from test order by score asc limit 2;

In this case, I'm looking for the 2 nearest to 0.5
I'd probably do a datamodel where you have one table for the main data, the ratios and so on, and then a second table which holds the curve points, as I'm assuming that the curves aren't always the same size.

A: Yes, a database is probably the best approach for this.
A relational database (which usually uses SQL for data access) is suitable for data that is more or less structured as tables.
To give you an idea:
You could have a main table model with fields name, width etc. . Then subtable(s) for any values which can appear more than once, which refers back to model (look up "foreign key").
Then a subtable for your actual curves, again refering back to model.
How to actually model the curves in the DB I don't know, as I don't know how you model them. But if its lots of numbers, it can go into the DB.
It seems you know little about relational DBMS. Consider reading something on WIkipedia, or doing a few simple DBMS tutorials (PostgreSQL has some: http://www.postgresql.org/docs/8.4/interactive/tutorial.html , but there are many others). Then pick a DBMS for trying out (PostgreSQL is probably not a bad choice, but again there are many others).
Then try implementing a simple table schema, and get back to us with any detail questions (which you'll probably have).
One more thing: Those questions are probably more appropriate to serverfault.com.

A: This is arguably scientific data: you might find libraries/formats intended for arbitrary scientific data useful: HDF5 http://www.hdfgroup.org/ (note I am not an expert)


text:
Q: Valet status is showing "is stopped" I have a windows 10 insider build, and I am trying to install cpriego/valet-linux using wsl2
I have installed composer, php and all other the requirements.
Now when I do valet start then valet status it shows me nginx Is Stopped fpm is stopped. See the picture below:

A: The status message is in a slightly different format on WSL and without the tweaks that are in the WSL specific fork of valet getting a status of services through valet will not work. see valeryan/valet-wsl merge request 4 for the changes that have to be made for status detection within wsl using valet.


text:
Q: manipulate payload on ember data normalizePayload How can I manipulate one of the values in normalizePayload (I need it anyway to convert result to session)
I need start_time and end_time to be multipled with 1000 in order to get smoothly into an attr('date')
  "result": [
    {
      "end_time": 1412687629.42063,
      "start_time": 1412687629.26851,
    },
   {
      "end_time": 1412688377.15329,
      "start_time": 1412688377.11507,
    },
...

The current code I have is:
App.SessionSerializer = DS.ActiveModelSerializer.extend({
    normalizePayload: function(payload) {
        return {
            sessions: payload.result
        };
    }
});

A: Sorry I gave you bad info in the answer in your other question.  The normalizePayload method should manipulate the payload hash directly:
App.SessionSerializer = DS.ActiveModelSerializer.extend({
    normalizePayload: function(payload) {
        payload.sessions= payload.result;
        delete payload.result;
        delete payload.metadata;
        return payload;
    }
});


text:
Q: How to position images next to text using CSS I have problem with CSS with two divs.
My first div contain texts while second div contains images. I need to put the image div in top right corner of text div.
My div structures as below:

text text text .... more text

image image

I want to archieve this:
========================
text text  - image -
text text  - image -
text text text text
text text text text
text text text text
=========================
I  illustred this problem with an image:

How to achieve this?

A: Float the image?

image image

text text text .... more text

Live Example - This example demonstrates the principle. It has more styles to make it look nicer, but it will work without them. Play with it and see what I mean.

A: If you reformat the HTML to put the images in the text ,  you can float the images within that container and the text will flow around it.

    Lorum ipsum .....

Placing the images into a different container means they're 'separated' from that text,  so the text can't flow.


text:
Q: Wordpress - Publish post with featured image at same time via PHP I am publishing to Wordpress via PHP, as follows.

*

*Create post with wp_insert_post()

*Add Featured Image with wp_insert_attachment()
Problem:
When creating the Post, there is a Plugin (SNAP autoposter) that will automatically publish it on Facebook. But, as obvious, it does not wait until the featured image is attached.
Question:
How should I proceed to publish the post with an already assigned attachment?
Thanks a lot for your help :)

A: Don't publish the post until the attachment has been added.

*

*Set the post_status to draft when you call wp_insert_post.

*Add the attachment to the draft.

*Use wp_publish_post to publish the post.

If the plugin is setup correctly, it will be listening for the status transition to publish.


text:
Q: How to search in DataGridView using access database? I am working on a winform database application that update data using access database. In which I am trying to add textbox to search and filter data in datagridview (I connect my datagridview to Access Database using OleDb dataadapter.
My code for search text box is as follows:
private void txtSearchAdmin_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)13)
        {
            if (string.IsNullOrEmpty(txtSearchAdmin.Text))
                dataGridView.DataSource = employeesBindingSource;
            else
            {
                var query = from o in this.adminData.Employees
                            where o.Customer_Name.Contains(txtSearchAdmin.Text) || o.Phone == txtSearchAdmin.Text || o.Address.Contains(txtSearchAdmin.Text)
                            select o;
                dataGridView.DataSource = query.ToList();
          }
        }

A: @Abhi you currently using KeyPress event and this event fires before enter the text in the textbox, so you should use textbox TextChanged event.
private void txtSearchAdmin_TextChanged(object sender, EventArgs e)
    {

            if (string.IsNullOrEmpty(txtSearchAdmin.Text))
                dataGridView.DataSource = employeesBindingSource;
            else
            {
                var query = from o in this.adminData.Employees
                            where o.Customer_Name.Contains(txtSearchAdmin.Text) || o.Phone == txtSearchAdmin.Text || o.Address.Contains(txtSearchAdmin.Text)
                            select o;
                dataGridView.DataSource = query.ToList();
          }

}


text:
Q: Azure Pipelines: Access matrix variable from an expression In Azure Pipelines I'm trying to modify the value of a matrix variable with an expression as shown below.
I saw the example in
How to reference an Azure DevOps matrix variable, inside an expression?
but it only shows how to access a variable, not how to modify the value in an expression.
stages:
- stage: Test
  jobs:
  - job: Test
    strategy:
      matrix:
        'Python 3.9':
          image: 'ubuntu-20.04'
          python_version: '3.9'
          pytag: 'py39'
        'Python 3.10':
          image: 'ubuntu-20.04'
          python_version: '3.10'
          pytag: 'py310'

    pool:
      vmImage: $(image)

    variables:
      var_a: $[replace(variables['python_version'], '.', '')]

    steps:
    - script: |
        echo python_version '$(python_version)'
        echo pytag $(pytag)
        echo var_a $(var_a)
        echo expression $[replace(variables['python_version'], '.', '')]
      displayName: 'Output Test'

I'm trying to get rid of the pytag variables in the matrix and to compute them within the pipeline.
I would expect the output to contain env_a py39, but I receive the following output.
python_version 3.9
pytag py39
env_a
/home/vsts/work/_temp/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.sh: line 5: replace(variables['python_version'], '.', ''): syntax error in expression (error token is "(variables['python_version'], '.', '')")
##[error]Bash exited with code '1'.

A: The . should be escaped with a \.
Try
echo expression $[replace(variables['python_version'], '\.', '')]


text:
Q: MVC3 Modelbinder EF4 ICollection property In an MVC3 Razor application using EF4 I have a problem.
EF4 generates POCO classes and adds navigation properties for nested collections. A navigation property is always of type ICollection<T>.
In a View I try to bind to a class which has such a navigation property;
@Html.TextBoxFor(m => m.Items[0].Quantity)

This would generate a correctly named input field "Model.Items[0].Quantity". But because the property is ICollection<T>, I cannot use indexers. So I try:
@Html.TextBoxFor(m => m.Items.First().Quantity)

But that will generate an incorrect input field with the id "Quantity", and the DefaultModelBinder will not be able to bind correctly.
So, how can I bind a Model with a nested ICollection property?


text:
Q: Issues compiling libf2c w/ latest mingw-get-inst (3.16.11), gcc I'm trying to port some very old fortran code to windows. I'd like to use mingw and f2c, which has no problem converting the code to usable C on OS X and Ubuntu. I used f2c.exe as distributed by netlib on a fresh install of mingw, and it translated the code fine. I have a "ported" version of libf2c that seems to still contain some unresolved references -- mostly file i/o routines (do_fio, f_open, s_wsfe, e_wsfe) and, peculiarly, one arithmetic routine (pow_dd). To resolve these issues, I tried to build libf2c from source, but ran into an issue during the make process. The make proceeds to dtime_.c, but then fails due to a dependency on sys/times.h, which is no longer a part of the mingw distro. There appears to be a struct defined in times.h that defines the size of a variable in dtime_.c, specifically t and t0 on lines 53 and 54 (error is "storage size of 't' isn't known"; same for t0).
The makefile was modified to use gcc, and make invoked with no other options passed.
Might anyone know of a workaround for this issue? I feel confident that once I have a properly compiled libf2c, I'll be able to link it with gcc and the code will work like it does on linux and os X.
FOLLOW-UP: I was able to build libf2c.a by commenting out the time related files in the makefile (my code does not contain any time related functions, so don't think it will matter). I copied it to a non-POSIX search directory as show in -print-search-dirs, specifically C:\MinGW\lib\gcc\mingw32\3.4.5. That seems to have fixed the issue on the unresolved references, although the need to eliminate the time files does concern me. While my code is now working, the original question stands -- how to handle makefiles that call for sys/times.h in mingw?

A: Are you sure the MinGW installation went correct? As far as I can tell the sys/times.h header is still there, in the package mingwrt-3.18-mingw32-dev.tar.gz. I'm not familiar with the gui installer, but perhaps you have to tick a box for the mingwrt dev component.


text:
Q: MySQL won't allow Java Program to insert using JDBC I have a Java Server that connects to a MySQL database using JDBC.  I have created a user for the server to use and granted it all permissions on the database.  MySQL allows Select commands from the server. However, any updates or inserts fail.  I have logged in to MySQL from the terminal using the same user as the server and I am allowed to insert.  I'm not sure what's going on.
Something else to note is that if I run the server locally with a local instance of MySQL, everything works just fine.  However, this problem occurs on an Amazon EC2 server.
Many thanks to anyone who can help!

A: Sounds like you've solved your problem. Just FYI, if you want MySQL to be case-insensitive on Unix, you can add the following line to your my.cnf file:

lower_case_table_names = 1

On Windows and Mac, MySQL is case-insensitive by default. But on Unix, it's case-sensitive by default. See http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html for more info on that.

A: Turns out that MySQL cares about the case of table names...


text:
Q: Logging proper user ip behind a reverse proxy in GAE I'm using cloudflare as a reverse proxy in front of AppEngine. Hence, in GCP Logging request log, the IP being logged is Cloudflare's.
Behind cloudflare, the actual user IP is req.headers['x-forwarded-for'].split(',')[0], so I've been trying to work through Google Logging log correlation to get it right (in an express middleware):
const forwardedForHeader = req.headers['x-forwarded-for']
const userIp = forwardedForHeader ? forwardedForHeader.split(',')[0] : req.ip
res.on('finish', () => {
    logger.info(req.originalUrl, {
        httpRequest: {
            status: res.statusCode,
            requestUrl: req.originalUrl,
            requestMethod: req.method,
            remoteIp: userIp,
        },
        remoteIp: userIp, // workaround to get remote IP as metadata - GAE has everything else
    })
})

LOGGING_SPAN_KEY & LOGGING_TRACE_KEY are both set properly.
Unfortunately, I'm still getting 2 log entries (GAE generated 1 in request log; mine generated as above).
Is there any way to get the actual user ip in the request log ?