text:
Q: How to repair tfjs error on adding fetch from @tensorflow/tfjs-react-native? TensorFlow.js version
@tensorflow/tfjs 1.5.1
@tensorflow/tfjs-react-native 0.1.0-alpha.3
Versions
Android 10 on mobile
Windows 10 on PC
Expo SDK version 36.0.0
Node.js 12.14.1
Describe the problem or feature request
import { fetch } from '@tensorflow/tfjs-react-native
Is generating error:
TypeError: null is not an object (evaluating 'RNFSManager.RNFSFileTypeRegular)
Without this line I have:
Error: Unable to resolve module `./http@http://192.168.1.7:19001/node_modules\expo\AppEntry` from ``:

None of these files exist:
  * http@http:\192.168.1.7:19001\node_modules\expo\AppEntry(.native|.android.expo.ts|.native.expo.ts|.expo.ts|.android.expo.tsx|.native.expo.tsx|.expo.tsx|.android.expo.js|.native.expo.js|.expo.js|.android.expo.jsx|.native.expo.jsx|.expo.jsx|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json|.android.wasm|.native.wasm|.wasm)
  * http@http:\192.168.1.7:19001\node_modules\expo\AppEntry\index(.native|.android.expo.ts|.native.expo.ts|.expo.ts|.android.expo.tsx|.native.expo.tsx|.expo.tsx|.android.expo.js|.native.expo.js|.expo.js|.android.expo.jsx|.native.expo.jsx|.expo.jsx|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json|.android.wasm|.native.wasm|.wasm)
    at ModuleResolver.resolveDependency (C:\Users\lukas\Desktop\Projekty\HearObjects\node_modules\metro\src\node-haste\DependencyGraph\ModuleResolution.js:163:15)
    at ResolutionRequest.resolveDependency (C:\Users\lukas\Desktop\Projekty\HearObjects\node_modules\metro\src\node-haste\DependencyGraph\ResolutionRequest.js:52:18)
    at DependencyGraph.resolveDependency (C:\Users\lukas\Desktop\Projekty\HearObjects\node_modules\metro\src\node-haste\DependencyGraph.js:282:16)
    at C:\Users\lukas\Desktop\Projekty\HearObjects\node_modules\metro\src\lib\transformHelpers.js:267:42
    at C:\Users\lukas\Desktop\Projekty\HearObjects\node_modules\metro\src\Server.js:1305:37
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (C:\Users\lukas\Desktop\Projekty\HearObjects\node_modules\metro\src\Server.js:99:24)
    at _next (C:\Users\lukas\Desktop\Projekty\HearObjects\node_modules\metro\src\Server.js:119:9)
    at processTicksAndRejections (internal/process/task_queues.js:94:5)

[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'environment_1.env().platform.fetch')]
* HTTPRequest@http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:162543:50 in <unknown>
* http@http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:162781:27 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:161455:29 in <unknown>
* [native code]:null in forEach
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:161454:22 in getHandlers
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:188344:54 in findIOHandler
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:188362:33 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:188248:25 in step
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:188150:73 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27123:9 in tryCallTwo
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27287:25 in doResolve
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27146:14 in Promise
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:188127:36 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:188485:34 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:188248:25 in step
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:188150:73 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27123:9 in tryCallTwo
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27287:25 in doResolve
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27146:14 in Promise
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:188127:36 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:203017:47 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:202905:25 in step
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:202807:73 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27123:9 in tryCallTwo
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27287:25 in doResolve
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27146:14 in Promise
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:202784:36 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:202987:44 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:202905:25 in step
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:202807:73 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27123:9 in tryCallTwo
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27287:25 in doResolve
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27146:14 in Promise
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:202784:36 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:123695:63 in loadCocossdModel$
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:25759:23 in tryCatch
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:25934:32 in invoke
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:25759:23 in tryCatch
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:25835:30 in invoke
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:25865:19 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27123:9 in tryCallTwo
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27287:25 in doResolve
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27146:14 in Promise
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:25864:29 in callInvokeWithMethodAndArg
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:25869:157 in enqueue
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:25885:69 in async
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:123690:42 in loadCocossdModel
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:123726:72 in componentDidMount$
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:25759:23 in tryCatch
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:25934:32 in invoke
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:25759:23 in tryCatch
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:25835:30 in invoke
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:25845:21 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27114:16 in tryCallOne
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:27215:27 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:30669:17 in _callTimer
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:30705:19 in _callImmediatesPass
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:30924:33 in callImmediates
* [native code]:null in callImmediates
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:2712:35 in __callImmediates
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:2489:34 in <unknown>
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:2695:15 in __guard
* http://192.168.1.7:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:2488:21 in flushedQueue
* [native code]:null in flushedQueue
* [native code]:null in invokeCallbackAndReturnFlushedQueue

Code to reproduce the bug / link to feature request
App.js
import React from 'react';
import { StyleSheet, Text, View, StatusBar, ActivityIndicator, TouchableOpacity, Dimensions, Image } from 'react-native';
import { Camera } from 'expo-camera';
import * as tf from '@tensorflow/tfjs';
import * as cocoSsd from '@tensorflow-models/coco-ssd';
import * as Permissions from 'expo-permissions';
import * as jpeg from 'jpeg-js';
import * as FileSystem from 'expo-file-system';
import { Buffer } from 'buffer'
import { Asset } from 'expo-asset';

export default class App extends React.Component {
  state = {
    isTfReady: false,
    isModelReady: false,
    isCameraReady: false,
    predictions: null,
    image: null,
  };

  async getPermissionAsync() {
    await Permissions.askAsync(Permissions.AUDIO_RECORDING)
    await Permissions.askAsync(Permissions.CAMERA_ROLL)
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    this.setState({ isCameraReady: status });
  }

  async loadTf() {
    await tf.ready();
  }

  async loadCocossdModel() {
    const model = await cocoSsd.load();
  }

  async componentDidMount() {
    await this.getPermissionAsync();

    await this.loadTf();
    this.setState({ isTfReady: true });
    await this.loadCocossdModel();
    this.setState({ isModelReady: true });
  }

  imageToTensor(rawImageData) {
    const TO_UINT8ARRAY = true;
    const { width, height, data } = jpeg.decode(rawImageData, TO_UINT8ARRAY);
    const buffer = new Uint8Array(width * height * 3);
    let offset = 0;
    for (let i = 0; i < buffer.length; i += 3) {
      buffer[i] = data[offset];
      buffer[i + 1] = data[offset + 1];
      buffer[i + 2] = data[offset + 2];
      offset += 4;
    }
    return tf.tensor3d(buffer, [height, width, 3]);
  }

  async classifyImage() {
    try {
      const response = await FileSystem.readAsStringAsync(this.state.image, { encoding: FileSystem.EncodingType.Base64 });
      const rawImageData = await Buffer.from(response, 'base64');;
      const imageTensor = this.imageToTensor(rawImageData);
      const predictions = await this.model.classify(imageTensor);
      this.setState({ predictions });
      console.log(predictions);
    } catch (error) {
      console.log(error);
    }
  }

  async takePicture() {
    try {
      const cameraData = await this.camera.takePictureAsync()
      this.setState({ image: cameraData.uri });
    } catch (e) {
      console.log(e)
    }
    await this.classifyImage();
  }

  render() {
    const { isTfReady, isModelReady, isCameraReady, predictions, image } = this.state

    if (isCameraReady === null) {
      return <View />
    }
    else if (isCameraReady === false) {
      return <Text> No access to camera</Text>
    }

    return (
      <View style={styles.container}>
        <Camera
          ref={ref => {
            this.camera = ref;
          }}
          autoFocus={false}
          type={Camera.Constants.Type.back}
          style={styles.preview}
        />
        <StatusBar barStyle='light-content' />
        <TouchableOpacity
          style={styles.imageWrapper}
          onPress={isModelReady ? this.takePicture : undefined}>
          {image && <Image source={{uri: image}} style={styles.imageContainer} />}

          {isModelReady && !image && (
            <Text style={styles.transparentText}>Tap to choose image</Text>
          )}
        </TouchableOpacity>
        <View style={styles.predictionWrapper}>
          {isModelReady && image && (
            <Text style={styles.text}>
              Predictions: {predictions ? '' : 'Predicting...'}
            </Text>
          )}
          {isModelReady &&
            predictions &&
            predictions.map(p => this.renderPrediction(p))}
        </View>
      </View>
    );
  }
}

const { width: winWidth, height: winHeight } = Dimensions.get('window');

const styles = StyleSheet.create({
   preview: {
    height: winHeight,
    width: winWidth,
    position: 'absolute',
    left: 0,
    top: 0,
    right: 0,
    bottom: 0,
    paddingBottom: 1000,
    backgroundColor: '#fff',
  },
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  imageWrapper: {
    width: winWidth,
    height: winHeight,
    padding: 10,
    borderColor: '#cf667f',
    borderWidth: 5,
    borderStyle: 'dashed',
    marginTop: 40,
    marginBottom: 10,
    position: 'relative',
    justifyContent: 'center',
    alignItems: 'center'
  },
  predictionWrapper: {
    height: winHeight,
    width: '100%',
    flexDirection: 'column',
    alignItems: 'center',
    position: 'absolute',
  },
});

metro.config.js
const blacklist = require('metro-config/src/defaults/blacklist');

module.exports = {
  transformer: {
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: false,
      },
    }),
    babelTransformerPath: require.resolve(
      'react-native-typescript-transformer',
    ),
  },
  resolver: {
    assetExts: ['bin', 'txt', 'jpg', 'png', 'ttf'],
    sourceExts: ['js', 'json', 'ts', 'tsx', 'jsx'],
    blacklistRE: blacklist([/platform_node/])
  },
};

package.json
{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.7.1",
    "@tensorflow-models/coco-ssd": "^2.0.1",
    "@tensorflow/tfjs": "^1.5.1",
    "@tensorflow/tfjs-react-native": "^0.1.0-alpha.3",
    "buffer": "^5.4.3",
    "expo": "~36.0.0",
    "expo-asset": "^8.0.0",
    "expo-camera": "^8.0.0",
    "expo-gl": "^8.0.0",
    "expo-gl-cpp": "^8.0.0",
    "expo-permissions": "^8.0.0",
    "jpeg-js": "^0.3.6",
    "metro-config": "^0.56.4",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-36.0.0.tar.gz",
    "react-native-fs": "^2.16.2",
    "react-native-screens": "2.0.0-alpha.12",
    "react-native-typescript-transformer": "^1.2.13",
    "react-native-unimodules": "^0.7.0",
    "react-native-web": "^0.12.0-rc.1"
  },
  "devDependencies": {
    "@babel/core": "^7.0.0",
    "@types/react": "~16.9.0",
    "@types/react-native": "~0.60.23",
    "babel-preset-expo": "~8.0.0",
    "typescript": "~3.6.3"
  },
  "private": true
}

tsconfig.json
{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "jsx": "react-native",
    "lib": ["dom", "esnext"],
    "moduleResolution": "node",
    "noEmit": true,
    "skipLibCheck": true,
    "resolveJsonModule": true
  }
}

I can't run this code. What can I do to repair?

SOLUTION
Expo version is broken, use React Native instead.


text:
Q: Configuring a Cisco 5505 router I have a Cisco 5505 router that I need help configuring. I have 3 VLANs set up. VLAN 1 is set for 192.168.1.0/24 subnet. I have one computer hooked up to this subnet with the address 192.168.1.2. The VLAN 1 address is 192.168.1.1 which is the default route set in the computer. VLAN 2 is set to get its address from company DHCP server.
I also have it configured to set the default route in the router to this same subnet. VLAN 3 is configured for the subnet 192.168.10.0/24. I have a static route set so packets with a 192.168.10.x address from the PC are vpn-tunneled through VLAN 3. The problem is I can't get packets with any other address to go out the default address set in the router, e.g., out to the company network which, by the way, is not a VPN.
Do I need to set another static route in the router to make this happen? If not, what do I need to do?

A: Cisco 5505 is a Firewall, it's possible that in the license base vlan3 is restricted.
Verify the Crypto Map used in your VPN (configuration, site-to-site-vpn, advanced, crypto map)

A: It looks like the company gateway where your router default route points to does not know how to reach your VLANs.
You need the routes 192.168.1.0/24 and 192.168.10.0/24 configured on that gateway pointing to the IP set on the VLAN2, therefore using DHCP is not a good option as this IP may change.
(company gateway)---VLAN2----(your router)----VLAN1
                                   |
                                   |
                                 VLAN3

A: Do the VLANs have the same security level?
If so, make sure you have :
hostname(config)# same-security-traffic permit inter-interface

Also confirm that there is a default route to the ASA firewall from where ever it is that you need to access the outside.
I hope this'll work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: get_cookies() returns empty list with Whatsapp web using Chrome in Selenium I am trying to save my cookies for Whatsapp so I can run my program without having to scan a QR code every time.
when using the following code, cookies returns an empty list after logging into Whatsapp
from selenium import webdriver
import time

browser = webdriver.Chrome()
browser.get('https://web.whatsapp.com/')

time.sleep(10) #give me enough time to scan the QR code

cookies = browser.get_cookies()
print cookies

I am at a loss as to why the cookies that should exist don't show up. (cookies for google.com do show up.)
In this case, I can't use a user-data-dir argument as I am going to run this headlessly, any other suggestions would be helpful.

A: Your session would be stored on google-chrome by-default once you login, you can use user-data to import the same settings and cookies. This won't require you to login again.
chrome-user-path template ** C:\Users\\AppData\Local\Google\Chrome\User Data\Default**
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument(user_profile_path)
driver = webdriver.Chrome( executable_path="chromedriver", chrome_options=options)
driver.get( "https://api.WhatsApp.com/send?phone={}".format(phone_number))

This works for me, you can checkout this repo as well, code is a little outdated but will for fine with a few tweaks


text:
Q: sympy set expectation and variance of random variable I have a symbol, x, in my sympy code and have been computing a number of expressions with it. Ultimately the expression I have is very long and I am only interested in its expectation under the assumption E(x) = 0, E(x^2) = 1. Is there some way to set the expectation and variance of x in advance and then ask sympy to compute expectation of my entire expression?

A: Let x=stats.Bernoulli('x', 1/2, succ=1, fail=-1). Then the E and variance are what I want. So if I compute any expression with only the first two moments and take E and variance, I get the answer I want.


text:
Q: Как прикрутить к сайту эмоджи? Вопрос на засыпку. Как прикрутить к своему сайту emoji ?
Есть сайт на php с mysql в кодировке utf8mp4 , jquery присутствует.
Есть textarea куда хотелось бы чтобы юзер вставлял эмоджи при наборе текста
Как вывести на экран браузера в div все эти картинки и чтобы по нажатию на них они вставлялись в поле textarea?
Чего то гугловство не очень помогает, т.к. не могу понять сам принцип
может быть есть где готовые примеры, чтобы посмотреть как это работает?

A: В сети много библиотек для этого.
Ткк отмчено, что используется джиквери, запрос: "jquery emoji picker"
Пример: http://wedgies.github.io/jquery-emoji-picker/demo.html

A: вот такую нашел либу https://github.com/OneSignal/emoji-picker
хорошее описание, попробую ее использовать


text:
Q: What is the difference between a layer with a linear activation and a layer without activation? I'm playing with Keras a little bit and I'm thinking about what is the difference between linear activation layer and no activation layer at all? Doesn't it have the same behavior? If so, what's the point of linear activation then?
I mean the difference between these two code snippets:
 model.add(Dense(1500))
 model.add(Activation('linear'))
 model.add(Dense(1500))

and
 model.add(Dense(1500))
 model.add(Dense(1500))

A: You are right, there is no difference between your snippets: Both use linear activation.
The activation function determines if it is non-linear (e.g. sigmoid is a non-linear activation function):
model.add(Dense(1500))
model.add(Dense(1500, activation='sigmoid'))

7 Common Nonlinear Activation Functions  and How to Choose an Activation Function

A: If you don't assign in Dense layer it is linear activation. This is from keras documentation.

activation: Activation function to use (see activations). If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x)

You can only add Activation if you want to use other than 'linear'.
model.add(Dense(1500))
model.add(Activation('relu'))
model.add(Dense(1500))


text:
Q: Find all files with os.walk for a specific directory only A directory tree looks like this:
DirA--
     |
     -- Map
     |
     -- Fig--
            |
            --file.png
     |
     -- Data--
              |
              -- file.xls
              |
              -- file.csv

There are multiple directories, containing multiple files. I would like to get full path to those files that are found in Data directory only.
This is what I have so far:
dirlist = []
thisdir = os.getcwd()

for root, dirs, files in os.walk(thisdir):
    for d in dirs:
        if d.startswith("Data"):
            dirlist.append(os.path.join(root, d))

A: To get only Data directory files, you will need to combine root and files.
for root, dirs, files in os.walk(thisdir):
        if "Data" in root: # try using in instead of startswith
           for f in files:
            dirlist.append(os.path.join(root, f))

Trying to do it using 'dirs'
In case of 'dirs', you don't have access to the files. For example, when root is DirA, you will have --Data-- in your dirs list but you will have no access to the files of --Data-- folder.

A: import os
from os import listdir
from os.path import isfile, join

rootdir = os.getcwd()

folder_name = "Data"

def get_files(path):
    onlyfiles = [f for f in listdir(path) if isfile(join(path, f))]
    return onlyfiles

def get_search_files(start_path, folder_name):
    for subdir, dirs, files in start_path:
        for x in dirs:
            if x == folder_name:
                data_folder_path = os.path.join(subdir, x)
                dirlist = get_files(data_folder_path)
                return dirlist

dirlist = get_search_files(os.walk(rootdir), folder_name)


text:
Q: Selenium browser is getting an enable cookies page, not the page I am sending it to I am trying to scrape a js website with selenium.  When beautiful soup reads what selenium retrieved I get an html page that says: "Cookies must be enabled in order to view this page."
If anyone could help me past this stumbling block I would appreciate it.  Here is my code:
# import libraries and specify URL
import lxml as lxml
import pandas as pd
from bs4 import BeautifulSoup
import html5lib
from selenium import webdriver
import urllib.request
import csv

url = "https://racing.hkjc.com/racing/information/English/Racing/LocalResults.aspx?RaceDate=2020/06/09"

#new chrome session
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(executable_path= '/Users/susanwhite/PycharmProjects/Horse
Racing/chromedriver', chrome_options=chrome_options)

# Wait for the page to fully load
driver.implicitly_wait(time_to_wait=10)

# Load the web page
driver.get(url)
cookies = driver.get_cookies()

# Parse HTML code and grab tables with Beautiful Soup
soup = BeautifulSoup(driver.page_source, 'html5lib')
print(soup)

A: Try removing this line: chrome_options.add_argument("--incognito"). There's no need for it, as Selenium naturally doesn't save cookies or any other information from websites.

A: Removing below code solved it for me, but headless mode will be disabled and the browser window will be visible.
chrome_options.add_argument("--headless")

A: Your issues might also be with the specific website you're accessing.  I had the same issue, and after poking around with it, it looks like something in the way the HKJC website loads, selenium thinks the page is finished loading prematurely.  I was able to get good page_source objects out of fetching the page by putting in a time.sleep(30) after the get statement, so my code looks like:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import time

options = Options()
options.headless = True
driver = webdriver.Firefox(options=options, executable_path=r'C:\Python\webdrivers\geckodriver.exe')
driver.get("https://racing.hkjc.com/racing/information/English/Racing/LocalResults.aspx?RaceDate=2023/01/01&RaceNo=1")
time.sleep(30)
html = driver.page_source
with open('Date_2023-01-01_Race1.html', 'wb') as f:
     f.write(html.encode('utf-8'))
     f.close()

You might not have to sleep that long.  I found manually loading the pages takes 20+ seconds for me because I have slow internet over VPNs.  It also works headless for me as above.
You do have to make sure the Firefox geckodriver is the latest (at least according to other posts, as I only tried this over ~2 days, so not long enough for my installed Firefox and geckodriver to get out of sync)


text:
Q: Advanced search: roles and multiple taxonomies I have a site with custom roles, and custom taxonomies. I'm making the advanced search, where custom posts can be filtered by roles and taxonomies.
To accomplish this, I'm using my own custom SQL query, which works fine with the roles, and one taxonomy, but I'm having a hard time getting it to work with a second taxonomy (I get no results). Here's the code I'm generating (with some sample values coming in from the form):
SELECT DISTINCT p.* FROM wp_posts p
LEFT JOIN wp_usermeta um ON p.post_author = um.user_id
LEFT JOIN wp_term_relationships txr ON p.ID = txr.object_id
LEFT JOIN wp_term_taxonomy tx ON txr.term_taxonomy_id = tx.term_taxonomy_id
LEFT JOIN wp_terms trm ON tx.term_id = trm.term_id
LEFT JOIN wp_terms trk ON tx.term_id = trk.term_id
WHERE (um.meta_key = 'wp_capabilities' AND (um.meta_value LIKE '%student%' OR um.meta_value LIKE '%instructor%' ))
AND (tx.taxonomy= 'mediums' AND ( trm.name LIKE '%acrylic%' OR trm.name LIKE '%oil%' ))
AND ( tx.taxonomy= 'keywords' AND ( trk.name LIKE '%landscape%' OR trk.name LIKE '%test%'))
AND p.post_status = 'publish'
AND p.post_type = 'gallery'
GROUP BY p.ID
ORDER BY p.post_date DESC

When I input this directly into PHPMyAdmin, I get no errors, but the thing just hangs ("Loading message").
What am I doing wrong?

A: I was able to solve my problem with this query, although I bet it can be more efficient (I just couldn't figure out how to do it.)
SELECT DISTINCT p.* FROM wp_posts p
LEFT JOIN wp_usermeta um ON p.post_author = um.user_id
LEFT JOIN wp_postmeta pm ON p.ID = pm.post_id
INNER JOIN (
    SELECT txrm.object_id FROM wp_term_relationships AS txrm
    LEFT JOIN wp_term_taxonomy txm ON txrm.term_taxonomy_id = txm.term_taxonomy_id
    LEFT JOIN wp_terms trm ON txm.term_id = trm.term_id
    WHERE txm.taxonomy = 'mediums'
    AND ( trm.name LIKE '%Acrylic%' )
    GROUP BY txrm.object_id
    HAVING count(trm.name) = 1
) AS trm ON p.ID = trm.object_id
INNER JOIN wp_term_relationships txrk ON p.ID = txrk.object_id
INNER JOIN wp_term_taxonomy txk ON txrk.term_taxonomy_id = txk.term_taxonomy_id
INNER JOIN (
    SELECT txrk.object_id FROM wp_term_relationships AS txrk
    LEFT JOIN wp_term_taxonomy txk ON txrk.term_taxonomy_id = txk.term_taxonomy_id
    LEFT JOIN wp_terms trk ON txk.term_id = trk.term_id
    WHERE txk.taxonomy = 'keywords'
    AND ( trk.name LIKE '%Landscape%' )
    GROUP BY txrk.object_id
    HAVING count(trk.name) = 1
) AS trk ON p.ID = trk.object_id
WHERE p.post_status = 'publish'
AND p.post_type = 'gallery'
GROUP BY p.ID
ORDER BY p.post_date DESC

So basically, I had to add an inner query for each taxonomy, in which it sends back a list of term relationships that match the criteria, but by grouping them, I don't get duplicates.


text:
Q: Are extension methods the solution to this problem? In my program the source rectangle for drawing can either be a regular rectangle, an empty rectangle, or a rectangle with an X or Y of -1. If the rectangle is normal (example being (0, 0, 64, 64)) then it just draws that from the texture. If it is Rectangle.Empty it draws nothing and just continues with the loop. If the source rectangle has an X or Y of -1 then it is determined to be a collision tile.
The problem with this is that it -1 is not intuitive. It is confusing and a bad solution. Also if there come to be more tile types it will start getting ridiculous like -2 meaning a slow tile or -3 meaning a water tile.
Another problem is that since I did not know there were going to be collision tiles early on and regular XNA rectangles were fine, the entire system (thankfully only around 1,000 of lines of code at the moment) uses XNA rectangles. I figure I'm going to have to make a separate class at this point and update everything but I'm not sure.
What would be a good solution to this? I have not really dabbled in extension methods at all. Could they be applied to the Rectangle class and be given methods like IsCollisionTile() or IsBlankTile()? Initially I was hoping I could derive from the Rectangle class to make a Tile class but unfortunately the class is sealed. I suppose another simple solution could be just making a global constants class with -1 being CollisionTile, 0 being BlankTile, et cetera. This would at least make it slightly more understandable but this still looks ugly to me:
if (tiles[y, x].X == Constants.BlankTile)
    continue;

if (tiles[y, x].X == Constants.CollisionTile)
{
    Utility.DrawRectangle(spriteBatch, new Rectangle(x * TileSize, y * TileSize, TileSize, TileSize), collisionTileColor);
    continue;
}

spriteBatch.Draw(tileset, new Rectangle(x * TileSize, y * TileSize, TileSize, TileSize), tiles[y, x], Color.White);

If only there was a property I could use like Tag with controls. I'd really like to not abandon using the Rectangle class because it is so embedded in to the system and the program is purely functional, just not aesthetic in this regard. Ideally, I'd prefer a solution that just allows the Rectangle class to be extended to somehow be able to communicate with its clients what kind of tile it is supposed to be.
Well then, that took a lot more typing than I had originally hoped for. Sorry for the long read x_x

A: I would recommend setting global constants. The problem with extension methods in this case arises because Rectangle is a struct, a value type. That means that your extension method is working with a copy of the rectangle, not the original.

A: If the class can't be inherited from (which would usually be the appropriate solution here. Shame on you Microsoft!) then extension methods could defiantly work as you described.
Problem is - IMO it's less in style with C# and OOP in general to use methods that function like getters. That's what getters are for.
Because of that, I think the global constants option is more in line with the general style, but that's just my opinion.
From a totally programmatic POV - both methods are valid where the global constant class might be slightly faster (though I'm not sure of this)

A: At the beginning, you should consider, when do you use your Methods
IsCollisionTile() and IsBlankTile()

You have two choices:
*) You wanna use it globally, then you should better write a Utility-Class to have your Methods right there where you need them:
public static class CollisionHelper
{
  public static Boolean IsCollisionTile(ITile tileToCheck)
  {
    ...
  }
}

*) Second, if you wanna use it only in connection with your tiles, you should definitly write an extension method, e.g. to accept every ITile-Object. Extensions methods are a great way to widely EXTEND the capabilities of classes. A sample could be:
public class RectangleTile : ITile
{
  public static Boolean IsCollisionTile(this ITile tileToCheck)
  {
    ...
  }
}

I hope you have now an idea about Extension-Methods and how you could use them to solve your problem very easily ;)


text:
Q: How recent is recent? In user profiles it's very common to see:

This user has no recent positive reputation changes

Question is: how recent is this recent? My best guess is one month, can anyone confirm this or come with the actual time span?

A: My initial guess was 6 months based on:

*

*Exhibit A - Profile summary shows recent rep changes.

*

*Last positive rep change - 10th May (182 days)

*Last post - 4th Feb (278 days)

*Last seen - 4th Feb (278 days)

*Exhibit B - Profile summary shows "This user has no recent positive reputation changes"

*

*Last positive rep change - 5th May (187 days)

*Last post - 1st April (221 days)

*Last seen - 28th Sept (41 days)

However, it turned out to be a lot more complicated. Here are some counter examples:

*

*Exhibit C: -  Profile summary shows recent rep changes.

*

*Last positive rep change - 23rd Nov 2011 (351 days)

*Last post - 22 Oct (17 days)

*Last seen - 4th Nov (4 days)

*Exhibit D: - "This user has no recent positive reputation changes" (rep now shown)

*

*Last positive rep change - 1st August. (99 days)

*Last post - 1st August. (99 days)

*Last seen - today (0 days)

It does appears that last postive rep change isn't the only metric used to determine whether recent rep changes are shown. Or, more likely, the patterns are being skewed by cached results.
In the case of exhibit C, considering his recent activity the profile owner may have viewed his own profile. I don't believe the "no recent positive changes" message is shown to the profile owner so that would have triggered a cache refresh with actual rep data.
In the case of exhibit D, I'm not sure if the cache excuse will wash since that would mean a 3-month old cache fragment. Perhaps SO uses a different time span from MSO?


text:
Q: Discord.py on_raw_reaction_add() missing 1 required positional argument: 'user' I want to have my bot give someone a certain role whenever someone reacts to a certain message
Code:
@client.event
async def on_raw_reaction_add(reaction, user):
    if reaction.message.id == 747566918466273300 and reaction.emoji in "✅":
        role = discord.utils.get(user.server.roles, name="Member")
        await bot.add_roles(user, role)

and i get error:
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
  File "C:\Users\Bruker\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
TypeError: on_raw_reaction_add() missing 1 required positional argument: 'user'

Thanks

A: You are getting this exception because the on_reaction_add event does not take a user or a reaction parameter, you have to use payload instead, for example:
@client.event
async def on_raw_reaction_add(payload):
    # Code here

Then for the rest of your code:
if payload.message.id == 747566918466273300 and payload.emoji.name == "✅":
    role = discord.utils.get(payload.guild.roles, name="Member")
        await payload.author.add_roles(role)


text:
Q: Detect black ink blob on paper - Opencv Android I'm new to openCV, I've been getting into the samples provided for Android.
My goals is to detect color-blobs so I started with color-blob-detection sample.
I'm converting color image to grayscale and then thresholding using a binary threshold.
The background is white, blobs are black. I want to detect those black blobs. Also, I would like to draw their contour in color but I'm not able to do it because image is black and white.
I've managed to accomplish this in grayscale but I don't prefer how the contours are drawn, it's like color tolerance is too high and the contour is bigger than the actual blob (maybe blobs are too small?). I guess this 'tolerance' I talk about has something to do with setHsvColor but I don't quite understand that method.
Thanks in advance! Best Regards
UPDATE MORE INFO
The image I want to track is of ink splits. Imagine a white piece of paper with black ink splits. Right now I'm doing it in real-time (camera view). The actual app would take a picture and analyse that picture.
As I said above, I took color-blob-detection sample (android) from openCV GitHub repo. And I add this code in the onCameraFrame method (in order to convert it to black and white in real-time) The convertion is made so I don't mind if ink is black, blue, red:
mRgba = inputFrame.rgba();
/**************************************************************************/
/** BLACK AND WHITE **/
// Convert to Grey
Imgproc.cvtColor(inputFrame.gray(), mRgba, Imgproc.COLOR_GRAY2RGBA, 4);

Mat blackAndWhiteMat = new Mat ( H, W, CvType.CV_8U, new Scalar(1));
double umbral = 100.0;
Imgproc.threshold(mRgba, blackAndWhiteMat , umbral, 255, Imgproc.THRESH_BINARY);

// convert back to bitmap for displaying
Bitmap resultBitmap = Bitmap.createBitmap(mRgba.cols(), mRgba.rows(), Bitmap.Config.ARGB_8888);
blackAndWhiteMat.convertTo(blackAndWhiteMat, CvType.CV_8UC1);
Utils.matToBitmap(blackAndWhiteMat, resultBitmap);
/**************************************************************************/

This may not be the best way but it works.
Now I want to detect black blobs (ink splits). I guess they are detected because the Logcat (log entry of sample app) throws the number of contours detected, but I'm not able to see them because the image is black and white and I want the contour to be red, for example.
Here's an example image:-

And here is what I get using RGB (color-blob-detection as is, not black and white image). Notice how small blobs are not detected. (Is it possible to detect them? or are they too small?)

Thanks for your help! If you need more info I would gladly update this question
UPDATE: GitHub repo of color-blob-detection sample (second image)
GitHub Repo of openCV sample for Android

A: The solution is based on a combination of adaptive Image thresholding and use of the connected-component algorithm.
Assumption - The paper is the most lit area of the image whereas the ink spots on the paper are darkest regions.
from random import Random
import numpy as np
import cv2

def random_color(random):
    """
    Return a random color
    """
    icolor = random.randint(0, 0xFFFFFF)
    return [icolor & 0xff, (icolor >> 8) & 0xff, (icolor >> 16) & 0xff]

#Read as Grayscale
img = cv2.imread('1-input.jpg', 0)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

# Gaussian to remove noisy region, comment to see its affect.
img = cv2.medianBlur(img,5)

#Find average intensity to distinguish paper region
avgPixelIntensity = cv2.mean( img )
print "Average intensity of image: ", avgPixelIntensity[0]

# Generate mask to distinguish paper region
#0.8 - used to ignore ill-illuminated region of paper
mask = cv2.inRange(img, avgPixelIntensity[0]*0.8, 255)
mask = 255 - mask
cv2.imwrite('2-maskedImg.jpg', mask)

#Approach 1
# You need to choose 4 or 8 for connectivity type(border pixels)
connectivity = 8
# Perform the operation
output = cv2.connectedComponentsWithStats(mask, connectivity, cv2.CV_8U)
# The first cell is the number of labels
num_labels = output[0]
# The second cell is the label matrix
labels = output[1]
# The third cell is the stat matrix
stats = output[2]
# The fourth cell is the centroid matrix
centroids = output[3]

cv2.imwrite("3-connectedcomponent.jpg", labels)
print "Number of labels", num_labels, labels

# create the random number
random = Random()

for i in range(1, num_labels):
    print stats[i, cv2.CC_STAT_LEFT], stats[i, cv2.CC_STAT_TOP], stats[i, cv2.CC_STAT_WIDTH], stats[i, cv2.CC_STAT_HEIGHT]
    cv2.rectangle(cimg, (stats[i, cv2.CC_STAT_LEFT], stats[i, cv2.CC_STAT_TOP]),
        (stats[i, cv2.CC_STAT_LEFT] + stats[i, cv2.CC_STAT_WIDTH], stats[i, cv2.CC_STAT_TOP] + stats[i, cv2.CC_STAT_HEIGHT]), random_color(random), 2)

cv2.imwrite("4-OutputImage.jpg", cimg)

The Input Image

Masked Image from thresholding and invert operation.

Use of connected component.

Overlaying output of connected component on input image.


text:
Q: Change glyph for quotes One should quote with `` and '', for example
``quote''

will produce
"quote"

with the correct glyphs, that is the glyphs on the left are a rotation of 180° of the glyphs on the right.
Unfortunately, in some fonts (I am using mathpazo) the glyphs for left and right marks are too similar, and they actually look the same, especially when printed with non high quality printers, for example here:

Is it possible to use a different glyph on the left? I would really like to have something similar to this:

where it is a lot more clear where the quote starts and ends.

A: Ugly:
\documentclass{article}
\usepackage{mathpazo}
\def\lQ{\bgroup\fontfamily{cmm}\selectfont``\egroup}
\def\rQ{\bgroup\fontfamily{cmm}\selectfont''\egroup}
\begin{document}
Here is a \lQ test\rQ{}
\end{document}

or this:
\documentclass{article}
\usepackage{mathpazo,graphicx}
\def\lQ{\scalebox{-1}[1]{''}}
\begin{document}
Here is a \lQ test''
\end{document}

Trust the font designer.

A: \usepackage{graphicx}
\reflectbox{''}quote''


text:
Q: Is there really any point to using relative font sizing in CSS? I've read a lot about the pros and cons of sizing with either relative or absolute font sizes. Fixed sizes don't zoom in IE6 but that's not much of an issue these days. Accessibility is important, but I assume that all good accessibility software is built to deal with these issues?
I guess it mainly comes down to whether you want to be able to change all font sizes with one rule (i.e. the default font size you set) or whether you want to be able to change a font size somewhere without affecting nested elements (this is the thing that frustrates me most!).
Anyone have any tips?

A: According to YUI Font CSS,

Always use percentages as the units
  because they render more consistently
  than ems, and because they allow
  user-initiated resizing (unlike
  pixels).

Relative font sizes work pretty well when they are part of a framework like YUI. Especially because they normalize how fonts work across browsers.
Personally, I do throw in absolute px every once in a while, but typically only for text that must somehow match up size-wise with some other design elements (like a menu).
The % stuff does break down when you assign % to a certain element and then a different % to a contained element. But that's the only real gotcha I've found.

A: As explained in this CSS font size article:

Ideally? The very best unit of measure is NONE AT ALL! Let the user-agent determine the display according to the user's preference - BUT! We also know that with most designs, this is not a very practical approach. Personally? I prefer the "mix 'n match" flexibility of .em and .px - As user-agents become more "user-friendly" designer sizing will NOT be as potentially problematic OR controversial as it stands now.

Do not forget though relative font size can be used for other things than... font size!

*

*css image text wrap

*css em scale image

A: Apart from the ability to resize in IE6 (which is still, alas, a very popular browser), relative fonts give you a greater likelihood of matching the user's needs by default without them having to resize (or knowing how to, if we're talking inexperienced users here). The user — or someone on their behalf — may have increased font size as a DPI, OS or browser customisation for good reasons (eg. visual impairment) and with relative sizing you can use that information to their advantage.
Use 'px' for text that has to match sizes with other on-page elements that are sized in pixels (ie. images). For the rest, '%'. The question assumes that using relative font sizes is in some way difficult; I don't think it is.
Typically you'll set one font-size in '%' on the body, and a few on other page elements which are more or less important than general body text. You should rarely have enough levels of nesting and nested font-sizes that you can't easily keep track of them.
There is not anything about sizes being relative to their parent's size that is particularly hard to understand, and this property can be useful: should you want to change the basic font size on your page or a part of it, you can just change it once rather than having to go through fixing up every font-size declaration on contained elements.
The only real difficulty with relative is when you've sized a block relatively, but you want to size something inside it back to the original size. You can work out a percentage that's the inverse of the parent's percentage, but it's likely to be an ugly number, and you may get 1px rounding errors if you don't/can't state it in full accuracy. In this occasional case it may be a good idea to step back and look at the selector, see if you can't apply the sizing more selectively to avoid having to undo it.
It would, admittedly, be nice if we had a unit that was relative only to the user's default size, not parent sizes, to attack problems like this. Unfortunately the only values that work like that are the smallest/smaller/small/medium/etc. keywords, which are rather coarse-grained in addition to the historical browser consistency problems.

A: OS X and Windows handle at least pt font sizes differently so this is certainly a complete no-go. On the other hand, is there any good reason not to use relative font sizes? It's not really as if this were a weighted debate with good arguments on both sides. Rather, on one side are several advantages (that might not be apparent all the time). But on the other hand there are only apparent advantages that, upon the slightest probing, prove worthless.1
Actually, I can only think of one argument for absolute font sizes, namely that it makes it easier to implement the CSS for a finished design, by copying the font sizes used in the design software. In reality, a consistent design will only use a handful of different font sizes that are simple ratios of each other (say, 80%) and can thus trivially be expressed in terms of em or %.

1) You said:

or whether you want to be able to change a font size somewhere without affecting nested elements

What exactly do you mean by that? The whole point of CSS is that you (generally) change an element's attributes relative to its parents'. Why should this ever be a problem?
The whole debate is slightly reminiscent of the "don't use layout tables" debates. The arguments might seem dogmatic to nonprofessionals2 but there's simply no reason not to follow them anyway. This isn't to say that it's wrong to ask for arguments! But there are soo many pointless violations of this rule.

2) For the record, I'm not a web design professional. Take my technical opinions here with just a grain of salt. But the argument is really independent of the technology used.

A: think about your parents or grandparents looking at your web page, with and without their bifocals (or trifocals). If they can't read it because you made all the fonts 8px, they'll probably go somewhere else. If they click 'text size >> largest' and nothing happens, they'll probably go somewhere else.
given that - at least in the USA - a lot of web surfers are older people with time, money, and failing eyesight, the use of em for fonts for public web sites would seem to be of great benefit ;-)

A: The only big reason valid is that a lot of people is still using IE6. Just this.
Probably could be a good thing, at the end of 2008, to give no more attention at IE6. But is difficult to ignore IE6. I work as web designer/devolper for a big company in Italy, and many of ours employes  or clients, in their work computers, are browsing the internet with IE6 right now.
Why? They don't have administrator rights and can't install anithing in their machines, and the system admistrators are always too busy to upgrade the computers of every office. May be this people will upgrade to IE7 (something like  Firefox is a dream) when their hard disks will need to be changed.
Is possible that this sort of things happens only in Italy. But I would not bet on this.

A: Using relative units for font-size, line-height, and top/bottom margin and padding will also keep the typographic scale intact as users increase/decrease text size. Typography and design people will appreciate it =)


text:
Q: How do I wrap a function in Javascript? I'm writing a global error handling "module" for one of my applications.
One of the features I want to have is to be able to easily wrap a function with a try{} catch{} block, so that all calls to that function will automatically have the error handling code that'll call my global logging method. (To avoid polluting the code everywhere with try/catch blocks).
This is, however,  slightly beyond my understanding of the low-level functioning of JavaScript, the .call and .apply methods, and the this keyword.
I wrote this code, based on Prototype's Function.wrap method:
Object.extend(Function.prototype, {
  TryCatchWrap: function() {
    var __method = this;
    return function() {
            try { __method.apply(this, arguments) } catch(ex) { ErrorHandler.Exception(ex); }
    }
  }
});

Which is used like this:
function DoSomething(a, b, c, d) {
    document.write(a + b + c)
    alert(1/e);
}

var fn2 = DoSomething.TryCatchWrap();
fn2(1, 2, 3, 4);

That code works perfectly. It prints out 6, and then calls my global error handler.
My question is: will this break something when the function I'm wrapping is within an object, and it uses the "this" operator? I'm slightly worried since I'm calling .apply, passing something there, I'm afraid this may break something.

A: Personally instead of polluting builtin objects I would go with a decorator technique:
var makeSafe = function(fn){
  return function(){
    try{
      return fn.apply(this, arguments);
    }catch(ex){
      ErrorHandler.Exception(ex);
    }
  };
};

You can use it like that:
function fnOriginal(a){
  console.log(1/a);
};

var fn2 = makeSafe(fnOriginal);
fn2(1);
fn2(0);
fn2("abracadabra!");

var obj = {
  method1: function(x){ /* do something */ },
  method2: function(x){ /* do something */ }
};

obj.safeMethod1 = makeSafe(obj.method1);
obj.method1(42);     // the original method
obj.safeMethod1(42); // the "safe" method

// let's override a method completely
obj.method2 = makeSafe(obj.method2);

But if you do feel like modifying prototypes, you can write it like that:
Function.prototype.TryCatchWrap = function(){
  var fn = this; // because we call it on the function itself
  // let's copy the rest from makeSafe()
  return function(){
    try{
      return fn.apply(this, arguments);
    }catch(ex){
      ErrorHandler.Exception(ex);
    }
  };
};

Obvious improvement will be to parameterize makeSafe() so you can specify what function to call in the catch block.

A: Object.extend(Function.prototype, {
Object.extend in the Google Chrome Console gives me 'undefined'
Well here's some working example:
    Boolean.prototype.XOR =
//  ^- Note that it's a captial 'B' and so
//      you'll work on the Class and not the >b<oolean object
        function( bool2 ) {

           var bool1 = this.valueOf();
           //         'this' refers to the actual object - and not to 'XOR'

           return (bool1 == true   &&   bool2 == false)
               || (bool1 == false   &&   bool2 == true);
        }

alert ( "true.XOR( false ) => " true.XOR( false ) );

so instead of
Object.extend(Function.prototype, {...})
Do it like:
Function.prototype.extend = {}

A: 2017 answer: just use ES6. Given  the following demo function:
function doThing(){
  console.log(...arguments)
}

You can make your own wrapper function without needing external libraries:

function wrap(someFunction){
  function wrappedFunction(){
    var newArguments = [...arguments]
    newArguments.push('SECRET EXTRA ARG ADDED BY WRAPPER!')
    console.log(`You're about to run a function with these arguments: \n  ${newArguments}`)
    return someFunction(...newArguments)
  }
  return wrappedFunction
}

In use:
doThing('one', 'two', 'three')

Works as normal.
But using the new wrapped function:
const wrappedDoThing = wrap(doThing)
wrappedDoThing('one', 'two', 'three')

Returns:
one two three SECRET EXTRA ARG ADDED BY WRAPPER!

2016 answer: use the wrap module:
In the example below I'm wrapping process.exit(), but this works happily with any other function (including browser JS too).
var wrap = require('lodash.wrap');

var log = console.log.bind(console)

var RESTART_FLUSH_DELAY = 3 * 1000

process.exit = wrap(process.exit, function(originalFunction) {
    log('Waiting', RESTART_FLUSH_DELAY, 'for buffers to flush before restarting')
    setTimeout(originalFunction, RESTART_FLUSH_DELAY)
});

process.exit(1);

A: Function wrapping in good old fashion:
//Our function
function myFunction() {
  //For example we do this:
  document.getElementById('demo').innerHTML = Date();
  return;
}

//Our wrapper - middleware
function wrapper(fn) {
  try {
    return function(){
      console.info('We add something else', Date());
      return fn();
    }
  }
  catch (error) {
    console.info('The error: ', error);
  }
}

//We use wrapper - middleware
myFunction = wrapper(myFunction);

The same in ES6 style:
//Our function
let myFunction = () => {
  //For example we do this:
  document.getElementById('demo').innerHTML = Date();
  return;
}

//Our wrapper - middleware
const wrapper = func => {
  try {
    return () => {
      console.info('We add something else', Date());
      return func();
    }
  }
  catch (error) {
    console.info('The error: ', error);
  }
}

//We use wrapper - middleware
myFunction = wrapper(myFunction);

A: Here is an ES6 style:
const fnOriginal = (a, b, c, d) => {
    console.log(a);
    console.log(b);
    console.log(c);
    console.log(d);
    return 'Return value from fnOriginal';
};

const wrapperFunction = fn => {
    return function () {
        try {
            const returnValuFromOriginal = fn.apply(this, arguments);
            console.log('Adding a new line from Wrapper :', returnValuFromOriginal);
        } catch (ex) {
            ErrorHandler.Exception(ex);
        }
    };
};

const fnWrapped = wrapperFunction(fnOriginal);
fnWrapped(1, 2, 3, 4);

A: The following wrapping utility takes a function and enables the developer to inject a code or wrap the original:

function wrap(originalFunction, { inject, wrapper } = {}) {

    const wrapperFn = function(...args) {
        if (typeof inject === 'function') {
            inject(originalFunction, this);
        }
        if (typeof wrapper === 'function') {
            return wrapper(originalFunction, this, args);
        }
        return originalFunction.apply(this, args);
    };

    // copy the original function's props onto the wrapper
    for(const prop in originalFunction) {
      if (originalFunction.hasOwnProperty(prop)) {
        wrapperFn[prop] = originalFunction[prop];
      }
    }
    return wrapperFn;
}

Usage example:

// create window.a()
(function() {

    const txt = 'correctly'; // outer scope variable

    window.a = function a(someText) { // our target
        if (someText === "isn't") {
            throw('omg');
        }
        return ['a', someText, window.a.c, txt].join(' ');
    };

    window.a.c = 'called'; // a.c property example
})();

const originalFunc = window.a;
console.log(originalFunc('is')); // logs "a is called correctly"

window.a = wrap(originalFunc);
console.log(a('is')); // logs "a is called correctly"

window.a = wrap(originalFunc, { inject(func, thisArg) { console.log('injected function'); }});
console.log(a('is')); // logs "injected function\na is called correctly"

window.a = wrap(originalFunc, { wrapper(func, thisArg, args) { console.log(`doing something else instead of ${func.name}(${args.join(', ')})`); }});
console.log(a('is')); // logs "doing something else instead of a(is)"

window.a = wrap(originalFunc, {
    wrapper(func, thisArg, args) {
        try {
            return func.apply(thisArg, args);
        } catch(err) {
            console.error('got an exception');
        }
    }
});
a("isn't"); // error message: "got an exception"

The last example demonstrates how to wrap your function with a try-catch clause

A: As far as polluting the namespaces, I'm actually going to pollute them some more...
Since everything that happens in JS is initiated by an event of some kind, I'm planning to call my magical wrapper function from within the Prototype Event.observe() method,  so I don't need to call it everywhere.
I do see the downsides of all this, of course, but this particular project is heavily tied to Prototype anyway, and I do want to have this error handler code be as global as possible, so it's not a big deal.
Thanks for your answer!


text:
Q: Process builder returns exit code 127 when running a Kshell script I am trying to run a Kshell script via Java process builder. The script itself works perfectly when run on the server. However, when I run it via process builder I am getting exit code 127 - command not found.
Code:
ProcessBuilder procBuilder = new ProcessBuilder(command);
procBuilder.directory(new File(codeDir));
proc = procBuilder.start();
errorCode = proc.waitFor();

return errorCode;

My command look like:
[/bin/ksh, -c, myscript.ksh, 20150714]

I run the script on the server by itself using following command:
ksh -x myscript.ksh 20150714

any idea what is going on wrong here?

A: Gave up on procesbuilder and tried common-exec and it worked perfectly. Here is my updated code:
CommandLine cmdLine = CommandLine.parse(command);

for (String comm : cmd)
{
    cmdLine.addArgument(comm);
}

DefaultExecutor exec = new DefaultExecutor();
exec.setExitValue(0);
exec.setWorkingDirectory(new File(codeDir));
exitCode = exec.execute(cmdLine);

Hope it help someone in the future.

A: ProcessBuilder does so because it does not find your script on PATH. Just execute the command echo $PATH with ProcessBuilder. You will see that 'its' PATH is different.


text:
Q: Icluding JS files in views in asp.net mvc Is it possible to include a .js file in the View in asp.net mvc?
I use razor engine, MVC 3.
It looks that header is already defined in _Layout.cshtml....So I pretty much have to include all my js files in the layout file?

A: You can define an optional section in your layout file. Then in your view define it.
_Layout.cshtml
<head>
  ..
  @RenderSection("Includes", required: false)
  ..
</head>

In your view
@section Includes {
   <script ...
}

A: Another way that can be used to organize and load javascript is using the following line in the Layout file.
   <script src="@Url.Content("~/Scripts/ViewScripts/" +
                 ViewContext.RouteData.Values["controller"].ToString() + "." +
                 ViewContext.RouteData.Values["action"].ToString() + ".js")"
                 type="text/javascript"></script>

Then you can create separate js files for each controller action/view.  For example, if you want to load a script specifically for your homepage using the default controller you create a file called home.index.js  or for the about page home.about.js
This gives a way to organize page specific javascript in small manageable files without having to specificallty load the script for every page.  If the Controller/Action has a file it will be loaded, if it doesn't it will be skipped.


text:
Q: Hibernate перезаписывает данные Доброго дня, товарищи.
Столкнулся с такой проблемой: сконфигурировал Hibernate, начал записывать сущности, всё хорошо, но после перезапуска приложения таблица очищается и данные записываются заново. Как сделать, чтобы при перезапуске данные дополнялись, а не перезаписывались?
UPD: выкладываю листинг конфигурации
 <?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">123</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="model.PostEntity"/>
    </session-factory>
</hibernate-configuration>

Узнал, что hbm2ddl.auto со значением create виновен в вопросе, но допустим при первом запуске таблицы вообще нет, а при повторном нужно проверять её существование.

A: hibernate.hbm2ddl.auto может принимать такие значения:

*

*validate: проверяет схему но не вносит изменения.

*update: обновляет схему

*create: создаёт схему удаляя старую

*create-drop: удаляет схему после окончания сессии.

вам нужно заменить create на update

A: Это происходит из-за:
<property name="hbm2ddl.auto">create</property>

validate: validate the schema, makes no changes to the database.
update: update the schema.
create: creates the schema, destroying previous data.
create-drop: drop the schema at the end of the session.

A: На самом деле я смотрел в правильную сторону, сюда нужно указать update и даже если таблицы нет, он её создаст и при каждом перезапуске будет дополнять.
<property name="hbm2ddl.auto">create</property>


text:
Q: Live tracking of GPS coordinates in Google Maps using PHP I have an application for android for my business that automatically tracks the users GPS location. This location is then stored in a database and shown on a Google Maps using API V3 with HTML and PHP.
We are using this for a long time now and it works perfectly, the only thing i can't get to work is the updating the markers live without refreshing the page. I've been looking for a long time now and hope that someone here can help me.

A: It's been a while so I don't know if you are still looking for an answer.
Create a function that deletes all current markers and then adds them. You need to loop through all map items by interrogating the map.
Create a php file that returns the current marker locations. This will be basically Javascript that you can query which has an array of locations.
Finally you need a timeout loop in Javascript, something like
function timeout() {
    setTimeout(function () {
    // Read new markers in via AJAX
    // Delete markers
    // Add Markers
       timeout();
    }, 1000);
}

Hope this helps.


text:
Q: Troubles with undefined citations I am new to Latex and having trouble with undefined citations. I am using Texmaker on Ubuntu.
I have tried all of the suggestions so far, but the same problem persists.
This is most my main .tex-file that I use for quick build:
\documentclass[12pt]{book}

\usepackage{a4wide}
\usepackage{fancyhdr}
\usepackage{graphicx}
\usepackage[english, ngerman]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[bookmarks]{hyperref}
\usepackage{braket}
\usepackage{mathrsfs}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{natbib}

\pagestyle{fancyplain}
\renewcommand{\chaptermark}[1]%
         {\markboth{\thechapter.\ #1}{}}
\renewcommand{\sectionmark}[1]%
         {\markright{\thesection\ #1}}
\lhead[\fancyplain{}{\bfseries\thepage}]%
    {\fancyplain{}{\bfseries\rightmark}}
\rhead[\fancyplain{}{\bfseries\leftmark}]%
    {\fancyplain{}{\bfseries\thepage}}
\cfoot{}

\hypersetup {
pdfpagemode = {UseNone}
}

\begin{document}

  \frontmatter

  \include{pages/deckblatt}

  \include{pages/titleblatt}

  \include{pages/zweite_seite}

  \tableofcontents
  \markboth{Inhaltsverzeichnis}{Inhaltsverzeichnis}

  \listoffigures
  \markboth{Abbildungsverzeichnis}{Abbildungsverzeichnis}

  \listoftables
  \markboth{Tabellenverzeichnis}{Tabellenverzeichnis}
  \cleardoublepage

  \markboth{Zusammenfassung}{Zusammenfassung}
  \include{pages/zusammenfassung}

  \mainmatter\setcounter{page}{1}
  \include{chapter/kap_01}
  \include{chapter/kap_02}
  %\include{chapter/kap_03}
  %\include{chapter/kap_04} usw.
  \include{pages/anhang}

  \backmatter
  \bibliographystyle{unsrtnat}
  \bibliography{literatur}
  \markboth{}{}

  \include{pages/danksagung}

\end{document}

And this is the literatur.bib file in the same folder:
@Article{EPR,
  author    = {A. Einstein and B. Podolsky and N. Rosen},
  title     = {Can quantum-mechanical description of physical reality be considered complete?},
  journal   = {Physical Review},
  publisher = {American Physical Society},
  year      = {1935},
  volume    = {47},
  pages     = {777-780}
}

@Article{Aspect,
  author    = {A. Aspect and J. Dalibard and G. Roger},
  title     = {Experimental Test of Bell's Inequalities Using Time-Varying Analyzers},
  journal   = {Physical Review Letters},
  publisher = {American Physical Society},
  year      = {1982},
  volume    = {49},
  number    = {25},
  pages     = {1804-1807}
}

@Article{Bell,
  author    = {J. S. Bell},
  title     = {On the Einstein Podolsky Rosen Paradox},
  journal   = {Physics},
  publisher = {Physics Publishing Co.},
  year      = {1964},
  volume    = {1},
  number    = {3},
  pages     = {195-200}
}

@Article{Stern-Gerlach,
  author    = {W. Gerlach and O. Stern},
  title     = {Der experimentelle Nachweis der Richtungsquantelung im Magnetfeld},
  journal   = {Zeitschrift für Physik},
  band      = {9},
  year      = {1922},
  pages     = {349-352}
}

@Article{Bertlmann,
  author    = {J. S. Bell},
  title     = {Bertlmann's socks and the nature of reality},
  journal   = {Journal de Physique Colloques},
  year      = {1981},
  volume    = {42},
  number    = {C2},
  pages     = {41-62}
}

@Article{Bohm,
  author    = {D. Bohm and H. Aharonov},
  title     = {Discussion of experimental proof of the paradox of Einstein, Rosen, and Podolsky},
  journal   = {Physical Review},
  publisher = {American Physical Society},
  year      = {1957},
  volume    = {108},
  number    = {4},
  pages     = {1070-1076}
}

@Article{Innsbruck,
  author    = {G. Weihs and T. Jennewein and C. Simon and H. Weinfurter and A. Zeilinger},
  title     = {Violation of Bell's inequality under strict Einstein locality conditions},
  journal   = {Physical Review Letters},
  publisher = {American Physical Society},
  year      = {1998},
  volume    = {81},
  number    = {23},
  pages     = {5039-5043}
}

@Article{CHSH,
  author    = {J. Clauser and M. Horne and A. Shimony and R. Holt},
  title     = {Proposed experiment to test local hidden-variables theories},
  journal   = {Physical Review Letters},
  publisher = {American Physical Society},
  year      = {1969},
  volume    = {23},
  number    = {15},
  pages     = {880-884}
}

@Article{Loopholefreebelltest,
  author    = {B. Hensen et al.},
  title     = {Loophole-free Bell test using electron spins in diamond: second experiment and additional analysis},
  journal   = {Scientific Reports},
  publisher = {Nature},
  year      = {2016},
  volume    = {6},
  number    = {30289},
  pages     = {1-11}
}

@Book{Ballentine,
    author        = {L. Ballentine},
    booktitle     = {Quantum Mechanics: A Modern Development},
    publisher     = {World Scientific Publishing Company},
    edition       = {2nd revised and edited edition},
    year          = {2014}
}

@Book{Sakurai,
    author        = {J. Sakurai and J. Napolitano},
    booktitle     = {Modern Quantum Mechanics},
    publisher     = {Pearson Education (US)},
    edition       = {2nd edition},
    year          = {2010}
}

@incollection{GHZ,
    author    = {D. Greenberger and M. Horne and A. Zeilinger},
    title     = {Bell's Theorem, Quantum Theory and Conceptions of the Universe},
    series    = {Fundamental Theories of Physics},
    volume    = {37},
    publisher = {Springer},
    year      = {1989},
    pages     = {69-72}
}

@Book{Cohen-Tannoudji-1,
    author        = {C. Cohen-Tannoudji and B. Diu and F. Laloë and J. Streubel},
    booktitle     = {Quantenmechanik},
    volume        = {1},
    publisher     = {De Gruyter Studium},
    edition       = {5. Auflage},
    year          = {2019}
}

@Book{Cohen-Tannoudji-2,
    author        = {C. Cohen-Tannoudji and B. Diu and F. Lalo{\"e} and J. Streubel},
    booktitle     = {Quantenmechanik},
    volume        = {2},
    publisher     = {De Gruyter Studium},
    edition       = {5. Auflage},
    year          = {2019}
}

@Book{Bub,
    author        = {J. Bub},
    booktitle     = {Interpreting the Quantum World},
    publisher     = {Cambridge University Press},
    edition       = {1st revised edition},
    year          = {1999}
}

When I want to insert the citation in the appropriate place in kap_01.tex, I start typing \cit..., and I am already suggested \citep{According names in the .bib file}, which makes me think that the .bib file is in the right place and recognized, which seems to be the reason for most similar issues. There is some peculiar behavior here though: Sometimes the bib entries are not suggested and then, without me being aware of having made any changes, after a restart of the program, the suggestions are there again...
When I go "quick build", it reports undefined citations wherever I have used them and they are shown as question marks in the pdf.
Unfortunately, the log is to long to attach here, instead I've uploaded the file here: https://easyupload.io/9jhap8
The only .blg file I could find was last modified in Ocotber, so that can't be it. Back then I hadn't edited the bib-file either.


text:
Q: Multi Tab Session - file manager I use Kcfinder file manager for uploading files on server. The file manager is enabled just for admins. I want to pass to kcfinder upload location through session. If admin is in page news files will be uploaded in a subfolder news, if admin is in page newsletter files will be uploaded in file newsletter.
How can I handle this for multitab? If the admin open in a tab news page and in another page newsletter then $_SESSION["uploadURL"] will contain the url from last open tab.

A: Yes, your session variable will be the url from the last open tab when the user opens your newsletter page in a new page.
If by 'page' you mean 'tab' then what you say will occur. But you could use a QueryString variable to solve this.
For example for the news page, a valid request should include something like:
 news.php?p=news (other another value pair)

You can use this to decide which will be the value of your upload destination directory.


text:
Q: Page contents grows both up and down in bootstrap page I have a problem with Bootstrap and ASP.NET WebForms. I've built a basic site which outline is basically:

and then heaps of content in various containers and rows.
What I've noticed is that the page grows from the center and outwards on the vertical axis, so if the page grows to where I need to scroll, parts of the page ends up out of bounds in the top (which is a bit icky since the navigation tends to be part of the stuff that disappears). The scrollbar in the web browser is already in its top-most position, so the content seems to be in some kind of "negative margin" space.
Is there a way to build the page ONLY grow downwards? I don't need the centered vertical alignment, it was simply there by default. I'll be just as happy with a page starting from the top and building downwards.
I hope someone understands my question here.


text:
Q: How to get the output of python script executed from a ruby method I am trying to run a python script from ruby method. I am running this method as a rake task within a Rails app. I am using the solution mentioned here:
def create
    path = File.expand_path('../../../../GetOrders', __FILE__)
    output = `"python2 " + path + "/parse.py"`
    print output
    str = JSON.parse(output)
    print str
end

EDIT: This works:
    output = `python2 #{path}/parse.py`

EDIT2:
Using the python script i am trying to pass a list of dictionaries to the ruby function. The python script looks something like:
import xml.etree.ElementTree as ET
import json

def parse():
    tree = ET.parse('response.xml')
    root = tree.getroot()
    namespaces = {'resp': 'urn:ebay:apis:eBLBaseComponents'}
    order_array = root.find("resp:OrderArray", namespaces=namespaces)
    detailsList = []
    for condition:
        details["key1"] = value1
        details["key2"] = value2
    detailsList.append(details)
    output = json.dumps(detailsList)
    return output

print parse()

Could someone explain what i am doing wrong and how can I fix this. Thanks

A: You are calling this exact line on the shell:
"python2 -path- /parse.py"

which the shell interprets as a single command: python2 (with a space at the end).
Try using string interpolation, which works with the backtick operator:
output = `python2 #{path}/parse.py`

A: Imagine typing this exact string:
"python2 " + path + "/parse.py"

into your shell (e.g. bash).  It would look for a program named "python2 " and give it four arguments
+
path
+
/parse.y

You can't put arbitrary Ruby code inside a backtick string the same way you can't put arbitrary code in normals strings.  You must use string interpolation.

A: When you do this:
output = `python2 #{path}/parse.py`

output will be assigned the standard output of the python script, but that script isn't writing anything to standard output; the json data that's the return value of the parse() call is simply discarded.  You seem to be expecting the execution of the script to have a "return value" that's the return value of the script's last expression, but that's not how processes work.
You probably want to replace the parse() call at the end of the script with print parse().


text:
Q: Error en sentencia SQL en access Alguien podria decirme por favor cual es el error en esta sentencia o que es lo que falta?
select count(distinct BLART) from COV_SAP_AccP_LA where Country = "XXX"

Lo estoy haciendo en access y lo que quiero es que me cuente por separado los diferentes datos que hay en una columna.
El error que me aparece en pantalla es

Syntax error(missing operator) in query expresion 'count(distinct BLART)'

Ya revisé varios ejemplos pero no se si access tiene una sintaxis diferente.
Gracias de antemano

A: Una sugerencia puede ser:
SELECT count(BLART) AS [Cantidad_datos], BLART
FROM COV_SAP_AccP_LA
WHERE Country = "XXX"
GROUP BY BLART;

La anterior consulta genera como resultado la cantidad de datos (en este caso, la cantidad de BLART).
Si "por ejemplo" existiese mas de un elemento en la columna BLART, solo mostrará el nombre una vez, pero en la columna Cantidad_datos se mostrará la cantidad de veces que existe.

A: Yo te recomendaria agruparlos para que tengas una lista de los datos con sus concurrencias, esto lo haces de la siguiente manera.
select count(BLART)
from ( select distinct BLART from COV_SAP_AccP_LA )
where Country = "XXX

Espero te ayude esto.
Saludos.


text:
Q: Instantiate web service I have clasess BankImpl, BankService, BankClient, BankServer and Bank interface.
I want to instantiate that bank service so I can use it with my other webservices but dont know the correct way of doing it.
I have something like this now:
Service service = Service.create(wsdlLocation, new
QName("http://bla/bla/bank", "BankService"));
Bank bank = service.getPort(new
QName("http://bla/bla/bank", "Bank"), Bank.class);

Is that the correct way or is there another, I saw on the net there is a ServiceFactory and some other techniques and all with their errors. I just want someone to tell me the correct way of instantiating the service class and using it. Thank you

A: The way you are trying to create the client is correct, be carreful with the classes that you use, but the general idea is correct. This is a good tutorial for creating a web service and the client in that way.
Another way is using the wsconsume or wsimport tools. This are command line tools. Given a wsdl, they generate all the client side artifacts that let you call the web service.
Eclipse is integrated with this tools so you can create the client with the GUI. In File -> New -> Other -> Web Service Client is the GUI version of this tools. You have to provide the wsdl and some basic configuration (server runtime, web service runtime, etc).


text:
Q: mysql sum with named column I have table where I have two columns briefeng and briefbng, I need the count of total null and not null values in a proper way:
Here is my sql code:
SELECT
Sum(If(brief_english Is Null, 1, 0)) AS briefeng,
Sum(If(brief_english Is NOT Null, 1, 0)) AS briefengnotnull,

Sum(If(brief_bangla Is Null, 1, 0)) AS briefbng
FROM synopsis;

but it returns a result like this way:
+----------+-----------------+----------+
| briefeng | briefengnotnull | briefbng |
+----------+-----------------+----------+
|      946 |             896 |      841 |
+----------+-----------------+----------+

But I need the result in this ways
 +----------+--------------+
 | status | total          |
 +----------+--------------+
 | briefeng |         946  |
 +----------+--------------+
 | briefengnotnull |  896  |
 +----------+--------------+
 | briefengnotnull |  841  |
 +----------+--------------+

How can I do that? I couldn't find a easy and efficient way.

A: Use union or union all like this :
SELECT
'briefeng' as status,
Sum(If(brief_english Is Null, 1, 0)) AS total
FROM synopsis
UNION ALL
SELECT
'briefengnotnull' as status,
Sum(If(brief_english Is NOT Null, 1, 0)) AS total
FROM synopsis
UNION ALL
SELECT
'briefbng' as status,
Sum(If(brief_bangla Is Null, 1, 0)) AS total
FROM synopsis

Difference between Union All and Union

A: SELECT count(*) FROM tablename WHERE a IS NULL
UNION ALL
SELECT count(*) FROM tablename WHERE a IS NOT NULL

or
select sum(case a when null then 1 else 0) "Null values",
       sum(case a when null then 0 else 1) "Non-null values"
from tablename;

or
select sum(case when a is null then 1 else 0 end) count_nulls
     , count(a) count_not_nulls
  from tablename;

A: It's a by hook or by crook sort of approach but if you create a secondary table containing the titles with this schema
CREATE TABLE `titles` (
  `title` varchar(255) CHARACTER SET latin1 NOT NULL,
  PRIMARY KEY (`title`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin

and this data
insert into `titles`(`title`) values ( 'briefeng'), ( 'briefengnotnull'), ( 'briefbng');

use this query
SELECT t.title, IF(a.total IS NOT NULL, a.total, IF(b.total IS NOT NULL, b.total, c.total)) AS total FROM
titles t
LEFT JOIN (SELECT 'briefeng' AS title, SUM(IF(brief_english IS NULL, 1, 0)) AS total FROM synopsis) a ON a.title=t.title
LEFT JOIN (SELECT 'briefengnotnull' AS title, SUM(IF(brief_english IS NULL, 0, 1)) AS total FROM synopsis) b ON b.title=t.title
LEFT JOIN (SELECT 'briefbng' AS title, SUM(IF(brief_bangla  IS NULL, 1, 0)) AS total FROM synopsis) c ON c.title=t.title

to get this result (depending on the records in synopsis table)
+-----------------+-------+
| title           | total |
+-----------------+-------+
| briefbng        |     3 |
| briefeng        |     1 |
| briefengnotnull |     4 |
+-----------------+-------+


text:
Q: IntArray vs Array in Kotlin I'm not sure what the difference between an IntArray and an Array<Int> is in Kotlin and why I can't used them interchangeably:

I know that IntArray translates to int[] when targeting the JVM, but what does Array<Int> translate to?
Also, you can also have String[] or YourObject[]. Why Kotlin has classes of the type {primitive}Array when pretty much anything can be arranged into an array, not only primitives.

A: Array<Int> is an Integer[] under the hood, while IntArray is an int[]. That's it.
This means that when you put an Int in an Array<Int>, it will always be boxed (specifically, with an Integer.valueOf() call). In the case of IntArray, no boxing will occur, because it translates to a Java primitive array.

Other than the possible performance implications of the above, there's also convenience to consider. Primitive arrays can be left uninitialized and they will have default 0 values at all indexes. This is why IntArray and the rest of the primitive arrays have constructors that only take a size parameter:
val arr = IntArray(10)
println(arr.joinToString()) // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

In contrast, Array<T> doesn't have a constructor that only takes a size parameter: it needs valid, non-null T instances at all indexes to be in a valid state after creation. For Number types, this could be a default 0, but there's no way to create default instances of an arbitrary type T.
So when creating an Array<Int>, you can either use the constructor that takes an initializer function as well:
val arr = Array<Int>(10) { index -> 0 }  // full, verbose syntax
val arr = Array(10) { 0 }                // concise version

Or create an Array<Int?> to avoid having to initialize every value, but then you'll be later forced to deal with possible null values every time you read from the array.
val arr = arrayOfNulls<Int>(10)

A: It is worth noting that using the spread (*) operator on a vararg will return an IntArray. If you need an Array<Int>, you can convert your IntArray using .toTypedArray().

A: Arrays in Kotlin are classes (not "special" types like Java).
Kotlin's stdlib provides special purpose classes for JVM primitive arrays in order to improve Java language integration and performance.
The rule of thumb would be to use Array<T> except if it cause a problem when mixing with existing Java code, or should be called from Java classes. For the record, I never had to use IntArray.
You can check the Language's documentation regarding this matter here: https://kotlinlang.org/docs/reference/basic-types.html#arrays


text:
Q: Binding a static global causes error in MonoTouch I started with a functioning bindings project, but I needed to add a global int for a status flag and I can't get it to bind without error.  I started with the sample code and can't get this to work.
The code I add to my bindings file is:
[Static]
interface CameraEffects {
    [Field ("kCameraEffectsZoomFactorKey", "CameraLibrary")]
    NSString ZoomFactorKey { get; }
}

I get three errors:
obj/Debug/ios/PDFExpert/CameraEffects.g.cs(34,94): error CS0117: `MonoTouch.Constants' does not contain a definition for `CameraLibraryLibrary'
obj/Debug/ios/PDFExpert/CameraEffects.g.cs(34,76): error CS1502: The best overloaded method match for `MonoTouch.ObjCRuntime.Dlfcn.dlopen(string, int)' has some invalid arguments
obj/Debug/ios/PDFExpert/CameraEffects.g.cs(34,76): error CS1503: Argument `#1' cannot convert `object' expression to type `string'

If I leave the library off it tried to assign it to another unknown constant.  This seems really screwed up as it is strait from the documentation.

A: I guess this should be bound like this
[Static]
interface CameraEffects {
    [Field ("kCameraEffectsZoomFactorKey", "__Internal")]
    NSString ZoomFactorKey { get; }
}

This is due to on the final app, the executable and the libxxx.a will be linked and merged together so it should work.
Alex

A: Another option that allows both assignment and retrieval of the value is to use the internal marshalling that MonoTouch uses.  I got this from a Xamarin support person, notice that this is for manipulating an int, but should be a pattern you can use if you get the right marshalling code.
public unsafe static partial class RDPDFGlobal
{
  static readonly IntPtr __Internal_libraryHandle = Dlfcn.dlopen (null, 0);

  public static int RDPDFFeatures {
    get {
      return Dlfcn.GetInt32 (__Internal_libraryHandle, "RDPDFKitEnabledFeatures");
    }
    set {
      var indirect = Dlfcn.dlsym (__Internal_libraryHandle, "RDPDFKitEnabledFeatures");
      if (indirect == IntPtr.Zero)
        throw new Exception ("Field 'RDPDFKitEnabledFeatures' not found.");
        Marshal.WriteInt32 (indirect, value);
    }
}


text:
Q: expand the product $\prod_{i=1}^n(a_i+b_i)$ Is there a formula to expand the product $\prod_{i=1}^n(a_i+b_i)$, where $a_i,b_i$ are elements of a commutative domain?

A: There really isn't a good formula.
If you define, for $S\subseteq \{1,2,...,n\}$: $$a(S)=\prod_{i\in S} a_i\\b(S)=\prod_{i\in S} b_i$$
then $$\prod_{i=1}^{n} (a_i+b_i)=\sum_{S\subseteq\{1,...,n\}} a(S)b(S^{c})$$
Where $S^c=\{1,2,3,\dots,n\}\setminus S$ is the complement of $S$.
This essentially means that each term in the expansion must contain exactly one of $a_i,b_i$ for each $i$.
[Note, an empty product - when $S=\emptyset$ - is defined to be $1$.]


text:
Q: Terraform Azure Event hub - disable public network access What is the way we can disable public network access using Terrform for Azure Event Hub
I selected options  public_network_access_enabled as false and public_network_access as false under network_rulesset block and following error
"public_network_access_enabled" is not expected here.
I am not sure what I am missing here...any support would be great help here.

A: As you say the attribute public_network_access_enabled does not exist in the module azurerm_eventhub
The attribute public_network_access_enabled it is part of the module azurerm_eventhub_namespace

public_network_access_enabled - (Optional) Is public network access enabled for the EventHub Namespace? Defaults to true.

Source: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/eventhub_namespace#public_network_access_enabled
For example:
resource "azurerm_eventhub_namespace" "example" {
  name                          = "example-namespace"
  location                      = azurerm_resource_group.example.location
  resource_group_name           = azurerm_resource_group.example.name
  SKU                           = "Standard"
  capacity                      = 2
  public_network_access_enabled = false # Default is true

  tags = {
    environment = "Production"
  }
}

A: Better if you can provide more details about how you have configured the access to your Azure Event Hub Namespace. Because, if you have disabled the public access, you need to enable access via private endpoints. In that case, you need to correctly use public_network_access_enabled property in both namespace level and network_rulesets level.
If you are using hashicorp as the provider, check the latest documentations for this in https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/eventhub_namespace#network_rulesets
Note:


text:
Q: Custom Json serialization format for MonetaryAmount JSR354 / moneta, How to register the Serializer properly Hello stackoverflow experts
I have the following InvoiceItem Class which has monetary Amounts
import jakarta.json.bind.annotation.JsonbProperty;
import jakarta.json.bind.annotation.JsonbTypeSerializer;
import jakarta.json.bind.serializer.JsonbSerializer;
import jakarta.json.bind.serializer.SerializationContext;
import jakarta.json.stream.JsonGenerator;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import org.eclipse.persistence.annotations.UuidGenerator;
import org.javamoney.moneta.FastMoney;

@Entity
@UuidGenerator(name = "INVOICE_ITEM_GEN")
@Table(name = "invoice_items")
public class InvoiceItem {
    @Getter
    @Setter
    @jakarta.persistence.Id
    @JsonbProperty("id")
    @GeneratedValue(generator = "INVOICE_ITEM_GEN")
    private String Id;

    @Getter
    @Setter
    @Column(name = "name")
    @JsonbProperty("name")
    private String Name;

    @Getter
    @Setter
    @Convert(converter = PersistentFastMoney.class)
    @Column(name = "price")
    @JsonbProperty("price")
    private FastMoney Price;

    public InvoiceItem() {
    }

    public InvoiceItem(String name, String price) {
        this.setName(name);
        this.setPrice(FastMoney.parse(price));
    }
}

I generate this sucessfully in my function from a different input.
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;

@Path("/invoices")
public class InvoiceSystem {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Invoice CreateNewInvoice(InvoiceInput input) {
        var invoice = new Invoice();
        invoice.setCreditor(new InvoiceParty());
        for (var item: input.getItems()) {
            invoice.Items.add(item.toInvoiceItem());
        }

        return invoice;
    }
}

the toInvoiceItem uses the Contructor of InvoiceItem with two string parameters.
Now I want to print the Class as JSON back to the Consumer after it has been created.
But this fails with

HTTP Status 500 - Internal Server Error

type Exception report

messageInternal Server Error

descriptionThe server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: javax.json.bind.JsonbException: Unable to serialize property 'Items' from com.openflowlabs.faktura.Invoice

root cause

javax.json.bind.JsonbException: Unable to serialize property 'Items' from com.openflowlabs.faktura.Invoice

root cause

javax.json.bind.JsonbException: Unable to serialize property 'price' from com.openflowlabs.faktura.InvoiceItem

root cause

javax.json.bind.JsonbException: Unable to serialize property 'context' from org.javamoney.moneta.FastMoney

root cause

javax.json.bind.JsonbException: Unable to serialize property 'amountType' from javax.money.MonetaryContext

root cause

javax.json.bind.JsonbException: Unable to serialize property 'annotatedInterfaces' from java.lang.Class

root cause

javax.json.bind.JsonbException: Unable to serialize property 'annotatedOwnerType' from sun.reflect.annotation.AnnotatedTypeFactory.AnnotatedTypeBaseImpl

root cause

javax.json.bind.JsonbException: Error getting value on: javax.money.MonetaryAmount

root cause

java.lang.IllegalAccessException: class org.eclipse.yasson.internal.model.ReflectionPropagation cannot access class sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl (in module java.base) because module java.base does not export sun.reflect.annotation to unnamed module @50c1e8e3

note The full stack traces of the exception and its root causes are available in the Payara Server
    5.2022.1 #badassfish logs.

Payara Server 5.2022.1 #badassfish

I know I need a Custom Serializer, but I tried for a day every possible way to make one but my App simply wont eat the Annotation
How do I make a Custom serializer for the org.javamoney.moneta.FastMoney Class so that I can simply annotate all fields that have this class with @JsonbTypeSerializer(FastMoneySerializer.class) like for example Invoice Item
@Getter
@Setter
@Convert(converter = PersistentFastMoney.class)
@Column(name = "price")
@JsonbProperty("price")
@JsonbTypeSerializer(FastMoneySerializer.class)
private FastMoney Price;

Is this possible somehow? Is there some documentation on how I would need to make the Serializer so it returns the JSON like this?
{
  "name": "Testing",
  "price": "CHF 20"
}

Thanks for any pointers and or Solutions I am really stuck and can't find a tutorial on how to make these Serializers work. If you have a Libarary with good documentation that would also help.

A: OK, I found a solution.
If you want to use jakarta.json your runtime needs to support it. I was using Pyara which says it supports Jakarta EE9 but somehow it does not. Switching to GlassFish solved that problem. The Correct Serializer was then done like this
package org.mypackage;

import jakarta.json.bind.serializer.JsonbSerializer;
import jakarta.json.bind.serializer.SerializationContext;
import jakarta.json.stream.JsonGenerator;
import org.javamoney.moneta.FastMoney;

public class FastMoneySerializer implements JsonbSerializer<FastMoney> {

    @Override
    public void serialize(FastMoney obj, JsonGenerator generator, SerializationContext ctx) {
        var str = obj.toString();
        generator.write(str);
    }
}

You can then add it to a property that has the FastMoney type like so:
package com.openflowlabs.faktura;

import jakarta.json.bind.annotation.JsonbAnnotation;
import jakarta.json.bind.annotation.JsonbProperty;
import jakarta.json.bind.annotation.JsonbTypeSerializer;
import jakarta.json.bind.serializer.JsonbSerializer;
import jakarta.json.bind.serializer.SerializationContext;
import jakarta.json.stream.JsonGenerator;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import org.eclipse.persistence.annotations.UuidGenerator;
import org.javamoney.moneta.FastMoney;

@Entity
@UuidGenerator(name = "INVOICE_ITEM_GEN")
@Table(name = "invoice_items")
public class InvoiceItem {
    @Getter
    @Setter
    @jakarta.persistence.Id
    @JsonbProperty("id")
    @GeneratedValue(generator = "INVOICE_ITEM_GEN")
    private String Id;

    @Getter
    @Setter
    @Column(name = "name")
    @JsonbProperty("name")
    private String Name;

    @Getter
    @Setter
    @Convert(converter = PersistentFastMoney.class)
    @Column(name = "price")
    @JsonbProperty("price")
    @JsonbTypeSerializer(FastMoneySerializer.class)
    private FastMoney Price;

    public InvoiceItem() {
    }

    public InvoiceItem(String name, String price) {
        this.setName(name);
        this.setPrice(FastMoney.parse(price));
    }
}