text:
Q: Microsoft Edge F12 and Microsoft Edge Dev Tools Preview crashes The Microsoft Edge F12 tool and the Microsoft Edge Dev Tool Preview app crash on opening. This problem does not occur on same website using new Microsoft Edge Chromium version.
I am writing this question with the intent on self answering it, after 7 lost hours of debugging
I am developing an Excel Add-in using the new Microsoft Edge WebView for office-addins, which just rolled out, and replaces IE11 as the embedded IFrame in Excel with Edge (see https://developer.microsoft.com/en-us/office/blogs/microsoft-edge-webview-for-office-add-ins/). After this last month roll out, the problem presented.
The crash is predictable, occurs after 5 seconds after activating the tool. It occurs when using F12 tools in Edge browser, and when using the standalone Dev Tools Preview to remote connect to the Edge browser running in MS Excel.
(I won't put app event logs because I have already solved it)

A: This is a Microsoft bug, not a coding bug.
It always occurs when using Typescript and defining a multidimensional array with only one element, and only in an async function
async myFunc(){
  let x:number[][] = [[9]]; //Edge F12 tool will crash simply by having this line
}

The problem does not occur in non async functions, and does not occur if the variable is defined as a class member. It does not occur if more than one element is defined. Workaround is to define the variable as private class member
public x:number[][] = [[9]]; //ok as member variable

let x:number[][] = [[9,2]]; //ok - even in async function

For those reading this who rightly ask "why would you want to define a multidimensional array with only 1 element". It is because MS Excel is a 2D array, and to set the value of cells the Excel API expects two dimensional arrays Excel.Range.values[][] =any[][]. So if you want to set the value of only one cell, you must supply a multidimensional array with only one value.
NB. I have not raised the bug with Microsoft as they are no longer supporting the Microsoft Edge Dev Tools preview, instead focusing on rolling out the Edge Chromium version, thus deprecating these tools. The problem does not occur in the Edge Chromium developer release, but I have no idea when Edge Chromium will be rolled out as the embedded browser in Excel (we only just left IE11 behind last month)

A: @JimbobTheSailor
Thank you for taking the time to report the issue and also coming back to provide the possible cause of the issue.
I know you have already spent a bunch of time on this issue, but I was hoping you could provide an example code file, or even npm package, that will cause the issue? I went and added your code and attempted to reproduce the issue, but I could not. GitHub Repo! By providing the entire package, or example, I can also see the different versions of TypeScript and other dependencies. You could also just list them here as well.
If possible, and don't mind grabbing it, could you provide the version of Windows you are using? START | RUN | WINVER . Also, the version of the DevTools Preview? Example:
C:\Program Files\WindowsApps\Microsoft.MicrosoftEdgeDevToolsPreview_18.924.1.0_x64__8wekyb3d8bbwe

To run my sample all you have to do is:
npm install
npm run build:dev
npm start

...or the yarn equivalent.
This will build, sideload the app, and boot Excel.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hadoop Input Formats - Usage I know different file formats in Hadoop ? By default hadoop uses text input format. what is advantage/disadvantage of using text input format.
What is advantage/disadvantage of avro over text input format.
Also please help me understand use case for different file formats(Avro, Sequence, TextInput, RCFile ).

A: I believe there are no advantages of Text as default other than its contents are human readable and friendly. You could easily view contents by issuing Hadoop fs -cat .
The disadvantages with Text format are

*

*It takes more resources on disk, so would impact the production job efficiency.

*Writing/Parsing the text records take more time

*No option to maintain data types incase the text is composed from multiple columns.
The Sequence , Avro , RCFile format have very significant advantages over Text format.
Sequence - The key/value objects are directly stored in the binary format through the Hadoop's native serialization process by implementing Writable interface. The data types of the columns are very well maintained, and parsing the records with relevant data type also done easily. Obvoiusly it takes lesser space compared with Text due to the binary format.
Avro -  Its a very compact binary storage format for hadoop key/value pairs, Reads/writes records through Avro serialization/deserialization. It is very similar to Sequence file format but also provides Language interoperability and cell versioning.
You may choose Avro over Sequence only if u need cell versioning or the data to be stored will used by few other applications written in different languages other than Java.Avro files can be processed by any languages like C, Ruby, Python, PHP, Java wherein Sequence files are specific only for Java.
RCFile - The Record Columnar File format is column oriented and it is a Hive specific storage format designed to make hive to support faster data load, reduce storage space.
Apart from this you may also consider the ORC and the Parquet file formats.


text:
Q: How to validate the integer field using xml validation using struts 1.3 Hi could any one help me out,How to validated the integer field using xml validation using struts1.3 here is my code.
   <field property="geozone" depends="integer">
                <arg0 key="PointFormBean.geozone" />
<!--                <arg1 key="${var:min}" resource="false"/>
                <arg2 key="${var:max}" resource="false"/>
                <var>
                    <var-name>min</var-name>
                    <var-value>1</var-value>
                </var>
                <var>
                    <var-name>max</var-name>
                    <var-value>15</var-value>
                </var>-->
            </field>

A: Try this:
<field property="geozone" depends="integer,intRange">
    <arg position="0" key="PointFormBean.geozone"/>
    <arg position="1" name="intRange" key="${var:min}" resource="false"/>
    <arg position="2" name="intRange" key="${var:max}" resource="false"/>
    <var><var-name>min</var-name><var-value>1</var-value></var>
    <var><var-name>max</var-name><var-value>15</var-value></var>
</field>


text:
Q: Could not find a declaration file for module implicitly has an 'any' type - while importing part of CommonJS module Currently, the project has a CommonJS module like in order to store the configuration values which are maintained only in one file:
module.exports = {
  classA: `classA`,
  classB: `classB`
  classC: `classC`
}

This allows later to reuse them for generating JS selectors by doing:
const CLASSES = require('./classes')

const SELECTORS = Object.keys(CLASSES).reduce((obj, key) => {
  const selectorKey = key.replace(`class`, `selector`)

  obj[selectorKey] = `.${CLASSES[key]}`

  return obj
}, {})

module.exports = SELECTORS

The selectors are later also used in the code logic and are also passed to PostCSS config which generates a list of variables to be used in .pcss files.
This is all super handy and helps the developing flow, plus CommonJS allows to import only specific value to the components when needed like:
import { classA } from './path/classes
It worked like a dream and it still does, however, importing it the same way in the typescript file doesn't satisfy the tslint constrains and it warns with an error:
Could not find a declaration file for module implicitly has an 'any' type:
Here is the tsconfig.json
{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "noImplicitThis": true,
    "baseUrl": ".",
    "types": [
      "webpack-env",
      "jest"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

So I wonder if there is a valid way to please TS gods and somehow declare the module types, or at least rewrite the presented logic while preserving the current functionality.
P.S: After talking with a duck I came to the conclusion that rewriting it into ts module will prevent the possibility to require the selectors in the postcss config since it doesn't support ES6 import

A: The solution I've found is to add "allowJs": true, option to tsconfig.js file


text:
Q: Can't find contacts in Time Machine I'm trying to restore lost contacts information from Time Machine. Where is the data stored on the HD? I've searched the Library, Documents and other likely places, but can't find the actual cards anywhere.

A: The Contacts database is stored in a single SQLite3 database per source. You can find a list of databases by running the following command:
find ~/Library/Application\ Support/AddressBook/ -name "AddressBook-v22.abcddb"


text:
Q: Resizable one way in grid layout javascript I have a problem with resizable an element in grid layout. When I resize meeting element. It's extend width of it's element both right and left. I only want extend width to the right. I try direction : 'ltr' in css but it's not working. This is my code CSS for resizable width.
  ul .chart-li-two-a {
    grid-column: 2/2;
    background-color: #0080ff;
    resize: horizontal;
    direction: "ltr";
  }

Here is sandbox code: codesandbox


text:
Q: iOS app with dynamic library injection I would like to implement Dynamic Library Injection. Below is what I do but without success:
1. create injection.dylib by compile injection.c:
#include <stdio.h>
#include <objc/objc.h>
id evil_say(id self, SEL op) {

       printf("Bawhawhawhaw! I'm Evil!\n");
       FILE *f= fopen("/tmp/sample.txt","w");
       fprintf(f, "OKOK");
       fclose(f);
       return self;
}

static void __attribute__((constructor)) initialize(void) {

       FILE *f= fopen("/tmp/sample.txt2","w");
       fprintf(f, "OKOK");
       fclose(f);
       class_replaceMethod( objc_getClass("SaySomething"), sel_registerName("say:"), evil_say, "@:" );
}

2. sign lib
ldid -S injection.dylib
3. Write sample HelloWorld iOS that:
#import "ViewController.h"

@interface SaySomething : NSObject - (void) say: (NSString *) phrase; @end
@implementation SaySomething
- (void) say: (NSString *) phrase {
    printf("%s\n", [ phrase UTF8String ]); }
@end

@interface ViewController ()

@end

@implementation ViewController

 (void)viewDidLoad {

    [super viewDidLoad];

    SaySomething *saySomething = [ [ SaySomething alloc ] init ];

    [ saySomething say: @"Hello, world!" ];

...

4. Build and run app by xcode7 --> HelloWorld app is installed and run
5. Copy injection.dylib into HelloWorld.app folder using iFunBox
6. Modify Info.plist in HelloWorld.app folder by adding Environment Variables (Dictionary) with 1 item:
  key=DYLD_INSERT_LIBRARIES

  value=/var/lib/mobile/<xxx-xxx....>/HelloWorld.app/injection.dylib

7. Open HelloWorld app on iPhone
But I could not find any sample.txt/sample.txt2 in /tmp folder of iPhone. It mean library not being loaded.
Could anybody tell me where is my fault?


text:
Q: ¿Hay alguna carpeta de "shutdown"? En Windows existe una carpeta llamada Inicio, o Startup en Inglés; en la ruta %APPDATA%\Roaming\Microsoft\Windows\Start Menu\Programs\Startup, la cual se ejecuta al iniciar el sistema operativo. Mi pregunta es si existe una carpeta que se ejecute al apagar el sistema.
Gracias

A: No como tal. Pero si necesitas realizar una acción o ejecutar un programa al apagar el equipo puedes crear una tarea con el Programador de tareas de Windows y usar como desencadenador el cierre de sesión.
Te dejo esta liga donde puedes ver más información al respecto. Espero te sea útil.


text:
Q: LAN not working after windows 8 installation I recently upgraded to Windows 8 but my LAN network is not working. In the network troubleshooting it shows this:

It worked well earlier.
I tried changing the DNS server to google's DNS (8.8.8.8) and it is still not working.

A: I had bumped into a similar problem. This solution worked for me.
Check your default gateway using ipconfig (type ipconfig in cmd). If your default gateway is set to 0.0.0.0 then you must remove it.
Type route delete 0.0.0.0, that should work.
If not type netsh int ip reset c:\resetlog.txt followed by netsh winsock reset c:\winsock.txt. Restart your computer, that should work.
Also disable ipv6 to be sure.
Reference: http://www.timdavis.com.au/general/windows-7-default-gateway-0-0-0-0-problem/

A: Try disabling IPv6 on the network adapter.


text:
Q: delete data from array I have this issue with deleting a data from an array(session).
Well, my code is:
$cart = $this->session->userdata('cart');
$sess_product_name = $cart['product_name'];
$sess_prod_id = $this->input->post('sess_prod_id');

foreach($sess_product_name as $key => $value) :
    if($key == $sess_prod_id) :
        unset($sess_product_name[$value]);
        $sess_product_name = array_values($sess_product_name);
    endif;
endforeach;

Even so, the array is not changing in any way :( please help
Thank you very much for helping!

A: $value is the value associated with the key.  If you wanted to remove that value, you would unset the associated key:
unset($sess_product_name[$key]);


text:
Q: Playframework pushing to Websocket I read through the WebSocket documentation of Play Framework, but haven't found the solution to my problem.
Problem description
I have an API (Play Framework) which receives data from Client 1 (C1) through a POST event. I have an other client that should then get automatically updated, if it is listening (read: has an open WebSocket to the API). How can I push the received data into the Websocket?
The documentation of the Play Framework only shows how to react to a received message through a Websocket, but not how to send data from the server.
Expectations for the solution
Could you please make a simple example for such a behavior? Maybe we can get it included in the documentation of Play Framework. I don't have a lot of experience with Akka.
Further Information
There are two ways of working with Websockets in Play Framework. One is with actors and the other is directly with Akka Streams. I think Akka Streams could be more straight-forward in this case, but I can live with both ways (or maybe a third one?).
If you need more information, just comment below!

A: You have to connect your clients like this:
First, In the routes file:
GET     /connectWebSocket           @myPackage.myController.webSocket

Then, your controller:
def webSocket: WebSocket = WebSocket.accept[String, String] { _ =>
  ActorFlow.actorRef(ActorReceivingMessagesFromPost.props())
}

After, you create an actor that receives messages from posts with a receive like this:
class ActorReceivingMessagesFromPost(out: ActorRef) extends Actor {
  override def receive: Receive = {
    case msg: String => out ! msg
  }
}

Let me know if you need more informations


text:
Q: Finding points satisfying inequalities I want to find a bunch of points $(x,y,z,u,v)$ s.t
$x^2-4u>0$ and $y^2-4v>0$ and $z^2-4uv>0$.
Here is what I did:
f[x_, y_, z_, u_, v_] := Max[x^2 - 4 u, y^2 - 4 v, z^2 - 4 u*v]
good[{x_, y_, z_, u_, v_}] :=
 If[f[x, y, z, u, v] < 0, "good", "notgood"]
tuples = Table[{RandomReal[{-10, 10}], RandomReal[{-10, 10}],
   RandomReal[{-10, 10}], RandomReal[{-10, 10}],
   RandomReal[{-10, 10}]}, {i, 1, 10000000}];
grouped = GroupBy[tuples, good];
goodones = grouped["good"];

This is terrible I feel. There must be a better way, is there?
Edit: One helpful observation is that if $(x,y,z,u,v)$ is a solution then so is $(x+x_1,y+y_1,z+z_1,u,v)$ for where $x,x_1$ have the same sign. same for the other two.


text:
Q: How to use $ref in swagger file properly while working with swagger-ui-express and swagger-jsdoc I started to use swagger with swagger-ui-express and swagger-jsdoc to auto document my existing API, which is written with nodejs and express (like described here - example).
I came across a problem when I tried to add a $ref to an existing JSON Schema file (that sits inside my project on the same directory as all my js files) on my annotation.
My directory looks like this
I tried to write the local path (./schema.json) and the absolute path, tried to use #, using many syntaxes and nothing worked.
My annotation looks like this:
/**
 * @swagger
 * /testing:
 *    get:
 *      description: This should show the json schema
 *      responses:
 *          200:
 *              description: "successful operation"
 *              schema:
 *                 $ref: "./schema.json"
 */

I expected the swagger ui to show me the JSON schema in my request section by. I get the following error -
Resolver error at paths./testing.get.responses.200.schema.$ref
Could not resolve reference: Tried to resolve a relative URL, without having a basePath. path: './schema.json' basePath: 'undefined'.

I looked the problem up online and couldn't find any clear answer. I saw a solution that suggested I should put my schema on a server and access it with an URL address but I prefer not to do it on this point.
Also, at some point, I saved the scheme in a variable and then put it in the $ref and it worked fine. The only problem was that the scheme included some inner refs to an element in the same file and Swagger couldn't resolve them.
Is there a way to work properly with $ref in swagger-ui-express?

A:
Is there a way to work properly with $ref in swagger-ui-express?

Yes, there is, you have to resolve references in your YAML files by your self first, and provide result to Swagger UI then. You can do it with json-refs and yamljs libraries.
Here is the code snippet below shows you how you can do it:
const yamljs = require('yamljs');
const { resolveRefs } = require('json-refs');

/**
 * Return JSON with resolved references
 * @param {array | object} root - The structure to find JSON References within (Swagger spec)
 * @returns {Promise.<JSON>}
 */
const multiFileSwagger = (root) => {
  const options = {
    filter: ["relative", "remote"],
    loaderOptions: {
      processContent: function (res, callback) {
        callback(null, yamljs.parse(res.text));
      },
    },
  };

  return resolveRefs(root, options).then(
    function (results) {
      return results.resolved;
    },
    function (err) {
      console.log(err.stack);
    }
  );
};

const swaggerDocument = await multiFileSwagger(
  yamljs.load(path.resolve(__dirname, "./openapi/v1.yaml"))
);

You can also check the repo with full example how this solution works with swagger-ui-express: https://github.com/chuve/swagger-multi-file-spec

A: got the same problem here and find your question.
I've just solved mine so I guess I might help.
First, have you tried:
schema:
      $ref: "schema.json"

without the . This is how they teach at the documentation.


text:
Q: How to animate polyline on android? How to draw animated polyline on android google map? I had already implement trail library for animation. I want to create polyline as on Lyft on android.

A: Create two arraylist of latlng then create polyline by given method
private fun createPolyLine() {

        val lineOptions = PolylineOptions()
        lineOptions.width(6f)
        lineOptions.color(ContextCompat.getColor(act!!, R.color.colorPrimary))
        lineOptions.startCap(SquareCap())
        lineOptions.endCap(SquareCap())
        lineOptions.jointType(JointType.ROUND)
        blackPolyLine = googleMap!!.addPolyline(lineOptions)

        val greyOptions = PolylineOptions()
        greyOptions.width(6f)
        greyOptions.color(Color.GRAY)
        greyOptions.startCap(SquareCap())
        greyOptions.endCap(SquareCap())
        greyOptions.jointType(JointType.ROUND)
        greyPolyLine = googleMap!!.addPolyline(greyOptions)

        animatePolyLine()
    }

after that create animation of these polylines
private fun animatePolyLine() {
        val animator = ValueAnimator.ofInt(0, 100)
        animator.duration = 1500
        animator.interpolator = LinearInterpolator()
        animator.addUpdateListener { animator ->
            val latLngList =
                blackPolyLine!!.points
            val initialPointSize = latLngList.size
            val animatedValue = animator.animatedValue as Int
            val newPoints = animatedValue * decodedPath.size / 100
            if (initialPointSize < newPoints) {
                latLngList.addAll(decodedPath.subList(initialPointSize, newPoints))
                blackPolyLine!!.points = latLngList
            }
        }
        animator.addListener(polyLineAnimationListener)
        animator.start()
    }

private var polyLineAnimationListener: Animator.AnimatorListener =
        object : Animator.AnimatorListener {
            override fun onAnimationStart(animator: Animator) {}
            override fun onAnimationEnd(animator: Animator) {
                val blackLatLng: MutableList<LatLng> = blackPolyLine!!.points
                val greyLatLng: MutableList<LatLng> = greyPolyLine!!.points
                greyLatLng.clear()
                greyLatLng.addAll(blackLatLng)
                blackLatLng.clear()
                blackPolyLine!!.points = blackLatLng
                greyPolyLine!!.points = greyLatLng
                blackPolyLine!!.zIndex = 2f
                animator.start()
            }

            override fun onAnimationCancel(animator: Animator) {}
            override fun onAnimationRepeat(animator: Animator) {}
        }

A:  private fun plotPolyline() {

    var polyline = "encoded_pyline"

    var list = PolyUtil.decode(polyline)

    val blackOptions = PolylineOptions()
    blackOptions.startCap(RoundCap())
    blackOptions.endCap(RoundCap())
    blackOptions.width(10.0f)
    blackOptions.color(Color.BLACK)
    blackOptions.zIndex(2.0f)

    var blackPolyline = googleMap.addPolyline(blackOptions)

    val greyOptions = PolylineOptions()
    greyOptions.startCap(RoundCap())
    greyOptions.endCap(RoundCap())
    greyOptions.width(8.0f)
    greyOptions.addAll(list)
    greyOptions.color(ContextCompat.getColor(this, R.color.gray_dark))
    var greyPolyline = googleMap.addPolyline(greyOptions)

    val valueAnimator = ValueAnimator.ofInt(0, 100)
    valueAnimator.duration = 1500
    valueAnimator.interpolator = LinearInterpolator()
    valueAnimator.addUpdateListener {
        val points: List<LatLng> = greyPolyline.getPoints()
        val percentValue = valueAnimator.animatedValue as Int
        val size = points.size
        val newPoints = (size * (percentValue / 100.0f)).toInt()

        val p = points.subList(0, newPoints)
        blackPolyline.points = p

    }

    valueAnimator.addListener(object: Animator.AnimatorListener{
        override fun onAnimationStart(animation: Animator?) {

        }

        override fun onAnimationEnd(animation: Animator?) {
            animation?.start()
        }

        override fun onAnimationCancel(animation: Animator?) {
        }

        override fun onAnimationRepeat(animation: Animator?) {
        }
    })

    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(list.get(0), 15.0f))
    valueAnimator.start()
}


text:
Q: In AWS security groups, what is the difference between setting a Custom TCP Rule on port 443 and setting an HTTPS rule (also on 443)? I'm creating a website and need to set up some boxes on AWS and create security groups for them. When creating a security group rule, I'm faced with the following options (abridged):
Type

*

*Custom TCP Rule

*...

*HTTPS

*...

So I'm wondering, what is the difference between setting a custom TCP rule on port 443 and setting a HTTPS rule (which is on port 443 by default)?

A: No difference. HTTPS is a short cut which translates to TCP/443. Suppose your HTTPS server uses a non-standard port, then you can use the custom TCP port to specify the non standard port.

A: It is not the same thing. TCP is layer 4 and HTTPS is layer 7.
You can see this try connecting SSL site without https as show below.
http://www.google.com:443
You can´t connect because you try TCP connection on port 443 although
using port 443 (SSL port).
If you change the http to https on site above you can connect it.
But if you select "SSL (secure TCP)" on port 443 you can connect it.
regards,


text:
Q: How can I create a nested value in TinyDB using python3? An example is this:
from tinydb import TinyDB, Query
from tinydb.operations import add

db = TinyDB('tinydb_practice.json')

db.insert({'Name':'Bella', 'Places':{}})
db.update(add('Places', {{'Country':'USA'}}))

for item in db:
  print(item)

What I want as my result is
{'Name':'Bella', 'Places':{{'Country':'USA'}}}

But I get this error
TypeError: unhashable type: 'dict'

TIA! :)

A: Places should be a list not a dict (or a set):
from tinydb import TinyDB, Query
from tinydb.operations import add

db = TinyDB('tinydb_practice.json')

db.insert({'Name':'Bella', 'Places':[]})  # <- replace {} by []
db.update(add('Places', [{'Country':'USA'}]))  # <- replace outer {} by []

for item in db:
    print(item)

Output:
{'Name': 'Bella', 'Places': [{'Country': 'USA'}]}


text:
Q: Get fully generated DOM elements inside iframe using selenium and phantomJS with python Ok, Im stuck. Im making a little web scraping python script using selenium and PhantomJS. The page that I working on has the data I want inside an iframe document that my web driver does not run.
<main Page Heads etc>

   <blah>

   <iframe 1 src="src1" ... etc etc>
    #document
      <tag>
      <tag>
      <iframe2 src="src2"><iframe2>
   <iframe1>

   <blah>

<end of webpage DOM>

I want to get the src of iframe2. I tried to run the src1 URL through my webdriver but all I get out is the raw page html, not the loaded webpage elements, iframe2 must be created by some script inside iframe1, but I can't get my webdriver to run the script.
Any ideas?
This what im doing to run the javascript on webpages to get the complied page DOM:
from selenium import webdriver

self.driver = webdriver.PhantomJS()
self.driver.get(url)
page = self.driver.page_source
soup = BeautifulSoup(page,'html.parser')

A: You can't get a full page_source. In the case of iframe, you should use the following command: switch_to.frame(iframe_element), so you can get an element inside
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC

self.driver = webdriver.PhantomJS()
self.driver.get(url)

WebDriverWait(self._driver, 50).until(
            EC.presence_of_all_elements_located
            ((By.XPATH,
              '//iframe[@id="iframegame"]'))
        )

iframe_element = self.driver.find_element_by_xpath('//iframe[@id="iframegame"]')

self.driver.switch_to.frame(iframe_element)

tag = self.driver.find_element_by_xpath('//tag')

And back again, you can get an outer element of iframe using the following command;
self.driver.switch_to.default_content()


text:
Q: Errors when running npm install -g create-react-app in ubuntu 20.04 So i'm trying to install react native in ubuntu 20.04, and i'm following this guide https://www.techomoro.com/install-and-setup-a-react-app-on-ubuntu/ , but when running "-g create-react-app" the terminal gives me these problems https://imgur.com/a/1tijndK , how do i solve them? i have node and npm installed (see the picture)

A: You npm version is suitable for this:
npx create-react-app your-app-name

npx command uses create-react-app without downloading it as global.
If you already added the create-react-app globally, uninstall it first.

A: #issue with npm
Try following command,
npx install create-react-app -g
npx create-react-app my-app
cd my-app
npm start

Sometimes the npm install doesn't work.
https://create-react-app.dev/docs/getting-started/

A: This seems like a an administrative access issues.
Trying running:
    $sudo npx create-react-app my-app

It will ask you for the administrators password, fill that in and it should be up and running.


text:
Q: Does MySQL Short Circuit the IF() function? I need to query data from a second table, but only if a rare set of conditions in the primary table is met:
SELECT ..., IF(a AND b AND c AND (SELECT 1 FROM tableb ...)) FROM tablea ...

a, b, and c conditions are almost always false, so my thinking is the subquery will never execute for most rows in the result set and thus be way faster than a join. But that would only true if the IF() statement short circuits.
Does it?
Thanks for any help you guys can provide.

A: With J. Jorgenson's help I came up with my own test case. His example does not try to short circuit in the condition evaluation, but using his idea I came up with my own test and verified that MySQL does indeed short-circuit the IF() condition check.
SET @var:=5;
SELECT IF(1 = 0 AND (@var:=10), 123, @var); #Expected output: 5
SELECT IF(1 = 1 AND (@var:=10), @var, 123); #Expected output: 10

On the second example, MySQL is properly short-circuiting: @var never gets set to 10.
Thanks for the help J. Jorgenson!

A: The answer is YES.
The IF(cond,expr_true,expr_false) within a mysql query is short-circuited.
Here a test, using @variables to prove the fact:
SET @var:=5;
SELECT IF(1 = 0, (@var:=@var + 1), @var ); -- using ':=' operator to modify 'true' expr @var
SELECT IF(1 = 1, @var, (@var:=@var + 1) ); -- using ':=' operator to modify 'false' expr @var
SELECT @var;

The result is '5' from all three SELECT queries.
Had the IF() function NOT short circuited, the result would be a '5' from SELECT #1, and '6' from SELECT #2, and a '7' from the last "select @var".
This is because the 'true' expression is NEVER executed, in select #1 and nor is the false expression executed for select #2.
Note the ':=' operator is used to modify an @var, within an SQL query (select,from, and where clauses).  You can get some really fancy/complex SQL from this.  I've used @vars to apply 'procedural' logic within a SQL query.
-- J Jorgenson --

A: It depends.
IF doesn't short-circuit such that it can be used to avoid truncation warnings with GROUP_CONCAT, for example in:
set @@group_concat_max_len = 5;

select if(true or @var:=group_concat('warns if evaluated'), 'actual result', @var);

the result will be 'actual result' but you'll get a warning:
Warning (Code 1260): Row 1 was cut by GROUP_CONCAT()

which is the same warning you get with less trivial GROUP_CONCAT expressions, such as distinct keys, and without the IF at all.

A: Try it in the SQL analyzer.  If you want to be on the safe side and not have to trust the database to work one way (and not to change that behavior ever in new versions), just make two queries and do the IF programmatically.


text:
Q: copy the object.keys to new object how can I copy one or all the Object.keys to new object literals
example:
  let obj = [
    {
      name: "value1",
      age: "value2",
      gender: "value3",
      group: "cat"
    },
    {
      name: "value1",
      age: "value2",
      gender: "value3",
      group: "cat"
    },
    {
      name: "value1",
      age: "value2",
      gender: "value3",
      group: "dog"
    },
    {
      name: "value1",
      age: "value2",
      gender: "value3",
      group: "dog"
    },

    ]

output is like this :
{
cat: { name: "value1", age: "value2"},
dog: { name: "value1", age: "value2"}
}

should we make the temporary object to duplicate it and then assigned it to newObj?
i do like to know with explaining so i would be understanding it,
that is just for example, and how if the groups have a lot of kind group, we should create a function for that, right?

A: You can loop through every items in your array, process the data, and assign the result to a new object :

let array_of_objects = [{
    name: "value1",
    age: "value2",
    gender: "value3",
    group: "cat"
  },
  {
    name: "value1",
    age: "value2",
    gender: "value3",
    group: "cat"
  },
  {
    name: "value1",
    age: "value2",
    gender: "value3",
    group: "dog"
  },
  {
    name: "value1",
    age: "value2",
    gender: "value3",
    group: "dog"
  },

]

let result = {};

array_of_objects.forEach(animal =>
  result[animal.group] = {
      name: animal.name,
      age: animal.age
    }
  );

console.log(result);

Explanations :

*

*We create a result object which will collect the data in the wanted format.

*The forEach method allows us to loop through the array. During every loop, an element is called animal.

*Then the object result receives its previous values thanks to the spread notation ...result plus new keys thanks to the [animal.group] part of the code. Note that this notation is between squares because the key needs to be evaluated.

Note : With this implementation, new cat values will for instance override the previous ones, but it's not totally clear in your question what you want to do when you have two cat in your dataset.

A: You could use Object.assign (one of the many alternatives):

const array_of_objects = [{ name: "value1", age: "value2", gender: "value3", group: "cat" }, { name: "value1", age: "value2", gender: "value3", group: "cat" }, { name: "value1", age: "value2", gender: "value3", group: "dog" }, { name: "value1", age: "value2", gender: "value3", group: "dog" }, ];

const result = {};
for (const obj of array_of_objects) result[obj.group] = Object.assign({}, obj);

console.log(result);

Object.assign will evaluate the (enumerable) properties from the object(s) given as second (third, ...) argument and store those in the object passed as first argument. The resulting object is returned and represents thus a (shallow) copy.
The same can be achieved with the more modern spread syntax.
If you only want to copy some specific properties, not all, then you can just use a simple assignment per key. That is not really challenging as an answer and I suppose you don't have a problem writing the following in the loop body:
const copy = {};
copy.name = obj.name;
// copy anything else here ...
result[obj.group] = copy; // store it in the overall result object

If you want something cooler, then we're back at ES6 syntax:
const {name, age} = obj;
result[obj.group] = {name, age};

A: You can do this fairly easily using Array#reduce() and object destructuring

const res = data.reduce((a, {group, gender, ...rest})=>{
   a[group] = {...rest}
   return a
},{})

console.log(res)
<script>
  const data = [{
      name: "value1",
      age: "value2",
      gender: "value3",
      group: "cat"
    },
    {
      name: "value1",
      age: "value2",
      gender: "value3",
      group: "cat"
    },
    {
      name: "value1",
      age: "value2",
      gender: "value3",
      group: "dog"
    },
    {
      name: "value1",
      age: "value2",
      gender: "value3",
      group: "dog"
    },

  ]
</script>


text:
Q: Swagger - Formdata with a form-urlEncoded Item
I'm trying to create a swagger document for my api and I'm a little stuck with something that I imagine is quite easy to achieve once you know how.
I have a endpoint that accepts a post as multipart/form-data (As it requires a file upload), however one of those items (pretend it's called "carParts" for the sake of this example), is a FormURLEncodedContent type that is a list of key/value pairs.
So the structure is something like:
carName:ford

carAge:20

carParts:wheels=4&horn=true&windscreen=broken
My problem is that I'm unsure how to express this ("carParts") in the swagger document.
The only way I can see to do it is to set the "carParts" item to a string type, but then I lose the point of swagger, in that I want "wheels", "horn" and "windscreen" to be explicit fields, not just a single form-urlEncoded string.
Is it possible to do this with swagger?
If not, I suppose the only other option is to change my api to just have the "carParts" items as a flat list rather than a structure (i.e. lose the "carParts" parent level and have the items just be other top level formdata items).
It seems the most straight forward way, but it's a shame if I need to modify the api to achieve this (Not a major issue, just doesn't feel right).

A: This is possible in OpenAPI 3.0, but not in OpenAPI/Swagger 2.0.
In OpenAPI/Swagger 2.0, form fields cannot be objects, so you'll have to define carParts as a string or as an array of primitives.
In OpenAPI 3.0, you can have objects in form fields, and you can specify how these objects are serialized. There are not many examples currently, but I think your case can be described as follows:
paths:
  /something:
    post:
      requestBody:
        required: true
        content:

          multipart/form-data:
            # Form fields (carName, etc.) are defined as object properties
            schema:
              type: object
              properties:
                carName:
                  type: string
                carAge:
                  type: string
                carParts:
                  type: object
                  properties:
                    wheels:
                      type: integer
                    horn:
                      type: boolean
                    windscreen:
                      type: string
            # By default, the "carParts" object will be serialized as application/json,
            # but we can override the serialization method to be form-urlencoded
            encoding:
              carParts:
                contentType: application/x-www-form-urlencoded

Relevant part of the Specification: Special Considerations for multipart Content.


text:
Q: Visualizing two different datasets amicably when they are measuring two different things I am working on a story map in AGOL that is comparing the percentage of a population that lives in a house that has been deemed transit dependent versus the concentration of a population that lives in a house that has been deemed transit dependent. Each of these are done by census tract.
The purpose of the story map is to show that while there are areas that have been deemed by the area density map as not as significant because of the overall size of the census tract there are areas that have significant portions that are not occupied by residents, but the overall percentage is high.
How do I ensure that these two scales are evenly distributed while at the same time retaining the simplicity of user interpretation (not using a standard deviation scale)
The below image is the scale that I am currently working with that measures percentage of the population versus residents by square mile.


text:
Q: MethodNotAllowedHttpException in RouteCollection.php line 218: Laravel Im having trouble posting my form to my database using laravel. When i click submit, it shows me the error MethodNotAllowedHttpException in RouteCollection.php line 218. My HTML code is shown below. I have defined the routes as shown below and I have also pasted my PostController which contains the store function.

Leave A Comment

                        <form method="post" action="store">

                                <input name="title" type="text" placeholder="Your Name" class="form-control c-square">

                                <textarea name="body" rows="8" name="message" placeholder="Write comment here ..." class="form-control c-square"></textarea>

                                <button type="submit" class="btn blue uppercase btn-md sbold btn-block">Submit</button>

                        </form>

This is my route page
 Route::resource('posts', 'PostController');

This is the PostController which contains the store function which is suppose to store the data into the database.
public function store(Request $request)
        {
            //Validate the data
            $this->Validate($request, array(
                'title'=>'required|max:255',
                'body'=>'required'
                ));

            //Store the data into the database
            $post = new Post;
            $post->title = $request->get('title');
            $post->body = $request->get('body');
            $post->save();

            //redirect to another page
            return redirect()->route('posts.show', $post->id);
        }

A: The problem is here:
<form method="post" action="store">

You should put posts here:
<form method="post" action="posts">

You can see all routes created with Route::resource() by using php artisan route:list command. Here, you need to look at URI created for posts.store route.
Also, you need to add CSRF token to your form:
<form method="post" action="posts">
    {{ csrf_field() }}

A: <form method="post" action="store"> will send you to the path store which you do not have, your form should post to the same url, like this:
<form method="post" action=".">

A: use
<form method="post" action="posts">


text:
Q: Is there a reliable, continuous source for dragon locations? I'm trying to gather bones and scales to make armor for one character, and I've come to realize that there's never really any dragons around when you want them to be.
Is there a reliable, continuous source (i.e.: radiant quest giver with a dragon obsession) for dragon locations?
Ideally, this would be a source that still works effectively in end-game scenarios.  Such as when you've completed all the major questlines (story, civil war, factions), all of the prominent side-quest lines (daedra, divine, etc.), and found and cleared all of the Word Walls.  It would really be perfect if the quest-giver only issued dragon quests but, if there isn't such a person, I suppose I could work with one that asked for other tasks in between now and then.

A: You could use the console if you wanted to, command: placeatme. Or just run around a lot.

A: The radiant Companions quest, Dragon Seekers will have you killing dragons. This is also the case with one of the random radiant Bounty quests (a quest given by an innkeeper, jarl, or steward), and with the radiant Blades quest, Dragon Hunting*.
Note that radiant quests are repeatable and randomly generated, so the quests above are a good, continuous source for dragon locations.
* Note: If you have received the "Paarthurnax" quest and have not finished it, then you will not be able to do the "Dragon Hunting" Blades quest, as well as any quest that the Blades (Delphine and Esbern) give or has given, until you finish it. See the "Paarthurnax" article on UESP for the repercussions of finishing or not finishing that quest. Those playing on the PC can install The Paarthurnax Dilemma mod to get around this issue.

A: Even though you can kill their guardians and get a Cleared Map tag under the location, exterior Word Walls will eventually respawn, both Dragon and Chest.
If you crisscross across Skyrim via Fast Travel, you should get more than enough Dragon Bones / Scales from previously cleared Word Walls that have since respawned.
If you're still looking for more dragons, you can still use the Word Walls, just wait for an in-game week (or however long it takes) then repeat your circuit across Skyrim.


text:
Q: Why isn't my onSaveInstanceState saving my EditText Value properly when going from landscape back to portrait So I have seen multiple examples of this done and for some reason I cannot get onSaveInstanceState to save the value of my EditText properly.
I have a very simple example that looks just like the image below.

first a TextView, then an EditText followed by a Button.
When clicking the Button it saves the value in EditText and then applies it to the TextView.
So the problem is it only works once, meaning I start in Portrait mode then turn my phone to Landscape and it saves then back to Portrait and it does not so the TextView appears blank.
My Example code is below:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="50dp"
    android:paddingLeft="50dp"
    android:paddingRight="50dp"
    android:paddingTop="50dp"
    tools:context="mydomain.com.savetest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Default Text"
        android:textSize="48sp"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:hint="choose a word"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SAVE WORD"
        android:id="@+id/bu"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

MainActivity.java
package mydomain.com.savetest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView mTextView;
    private EditText mEditText;
    private Button mButton;
    private String editTextValue;

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

        mTextView = (TextView) findViewById(R.id.textView);
        mEditText = (EditText) findViewById(R.id.editText);
        mButton = (Button) findViewById(R.id.button);

        editTextValue = mEditText.getText().toString();
        mTextView.setText(editTextValue);

        if(savedInstanceState != null){
            mTextView.setText( savedInstanceState.getString("text") ); //setting the saved value to the TextView
        }

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editTextValue = mEditText.getText().toString();
                mTextView.setText(editTextValue);
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putString("text", editTextValue); //saving EditText value
    }
}

So the whole goal of this is to get the TextView to save the word that was int the EditText and maintain it switching from portrait to landscape. As of now if I type lets say "Car" it will update the TextView with "Car" and will also have the value of Car even turning to Landscape mode, BUT when turning back to portrait the TextView value is gone and has nothing. I Cant seem to figure out whats going on here because I have set the value of EditText to TextView in the beginning on onCreate() so when the app starts again it should take the saved value just fine.

A: You have to get the current text directly from EditText instead of relying on a String variable being initialized in OnClickListener() once. It works only once because you've pressed the button once.. After the 2nd orientation change, the button wasn't pressed and hence String editTextValue is more likely null, because you would have to press the button after each orientation..
Change somethings as follows:
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    //don't save EditText value in a variable, instead directly get it from the EditText.
    outState.putString("text", mEditText.getText().toString());
}

also remove the variable initialization from OnClickListener() Its not needed
 editTextValue = mEditText.getText().toString(); // remove this.


text:
Q: Click back button on browser shows raw script There are some ajax calls in a page. What i have done is used history api to update the history. In the page /test i make a ajax request which updates the history and url is set to /test?query=true. On the pop state the ajax call is made according to the current url.
// Called in click event for the ajax call to create the history.
      var stateObj = { query: 'query' };
      history.pushState(stateObj, null, ?query=true);

// Called on the popstate
window.onpopstate = function(event) {
    $.ajax({
        method: 'get',
        url: window.location.href,
        dataType: 'script'
    });
}

Now when i have the state pused and url updated to /test?query=true i go to some other page /test2 and click browser back button the browser shows me the raw js code from my js.erb file.


text:
Q: React input validation with onChange I have a numeric input, which I want to validate with an onChange, but when said input is cleared, react throws ReferenceError: value is not defined which is understandable - it has nothing to validate.
I'm using this approach [Answer]
I'm using functional components and here is my code snippet:
   const [formData, setFormData] = React.useState({
        userTeamChosen: "",
        eventNumber: 0,
        value: 0,
        ethValue: 0})

    function handleNumeric(event) {
        const { name, checkedValue, min, max } = event.target
        value = Math.max(Number(min), Math.min(Number(max), Number(value)));
        setFormData(prevFormData => {
            return {...prevFormData,[name]: checkedValue}})}

    <input
        type="number"
        name="value"
        value={formData.value}
        onChange={handleNumeric}
        min="5"
        max="10000000"/>

How should I change my validation, to keep in onChange, but without erroring, when the input is empty?
Thanks in advance!

A: Looks like you were very close to solving this one yourself :D
The only errors I noticed were the value variables not being declared or defined anywhere, to solve this I just added formData so that react would know that it's the formData's value being used and not some random value
function handleNumeric(event) {
    const { name, checkedValue, min, max } = event.target
    formData.value = Math.max(Number(min), Math.min(Number(max), Number(formData.value)));
    setFormData(prevFormData => {
        return {...prevFormData,[name]: checkedValue}})}

A: There is no a checkedValue property in the number input element, Use valueAsNumber or value instead.
function handleNumeric(event) {
    const { name, valueAsNumber, min, max } = event.target
    const result = Math.max(+min, Math.min(+max, !Number.isNaN(valueAsNumber) ? valueAsNumber : +min));
    setFormData(prevFormData => {
        return {...prevFormData,[name]: result}})}

A: A number input is considered valid when empty. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number. So if you empty the input and try to check valueAsNumber it will return NaN. You can check for this case using isNaN():
    function handleNumeric(event) {
        const { name, checkedValue, min, max } = event.target
        if (isNaN(checkedValue)) checkedValue = 0;
        value = Math.max(Number(min), Math.min(Number(max), Number(checkedValue)));
        setFormData(prevFormData => {
            return {...prevFormData,[name]: checkedValue}})}

Other than that, your solution should be working fine in all other cases. Placing a required attribute on the number input may help as well since it will ask the browser to prevent users from emptying the input.

A: You should call

 function handleNumeric(event) {
        const { name, checkedValue, min, max } = event.target
        formData.value = Math.max(Number(min), Math.min(Number(max), Number(formData.value)));
        setFormData(prevFormData => {
            return {...prevFormData,[name]: checkedValue}})}


text:
Q: Check how many times a char appears in a string Simply trying to find how many times a given character appears in a string but I can't solve it any other way then this simple for-loop. Is there a method that would solve this quicker or  more eloquently other than using Regex?
function countCharacter(str, char) {

  var count = 0;
  for(var i = 0; i < str.length; i++){
    if(str.charAt(i) === char)
      count++;
  }
 return count;
}

A: There are many possible ways are available in the market.
I am adding a few of them.
Method 1:
str = "The man is as good as his word"
str.split('a')
output: (4) ["The m", "n is ", "s good ", "s his word"]
str.split('a').length - 1
output: 3

Method 2:
str = "The man is as good as his word"
str.split('').map( function(char,i)
    { if(char === 'a')
        return i;
    }
).filter(Boolean)
Output: (3) [5, 11, 19]

str.split('').map( function(char,i)
    { if(char === 'a')
        return i;
    }
).filter(Boolean).length

ouput: 3

Edit: As per comment we can also make use of filter().
    str.split('').filter(function(char, i){
        if(char == 'a'){
            return i;
        }
    })
    output: (3) ["a", "a", "a"]

str.split('').filter(function(char, i){
    if(char == 'a'){
        return i;
    }
}).length
output: 3

A: ----edited by adding more cases from answers----
there are several ways, you can use split/for/regex/reduce/indexOf like this:
function countCharacter_reduce(str, ch) {
  return Array.prototype.reduce.call(str, (prev, cur) => cur === ch && ++prev && prev, 0);
}

function countCharacter_split(str, ch) {
  return str.split(ch).length - 1;
}

function countCharacter_for(str, ch) {
  for (var count = 0, ii = 0; ii < str.length; ii++) {
    if (str[ii] === ch)
      count++;
  }
  return count;
}

function countCharacter_regex(str, ch) {
  return str.length - str.replace(new RegExp(ch, 'g'), '').length;
}

function countCharacter_indexOf(str, char) {
  var start = 0;
  var count = 0;
  while ((start = str.indexOf(char, start) + 1) !== 0) {
    count++;
  }
  return count;
}

performance of them by running 1,000,000 times on counting '/' in a string.
-- case1: running 1000000 times on ( 'this/is/a/path/with/extension', '/' )
countCharacter_reduce: 2389.880ms
countCharacter_regex: 496.251ms
countCharacter_split: 114.709ms
countCharacter_for: 152.012ms
countCharacter_indexOf: 90.330ms

-- case2: running 1000000 times on ( '////////////', '/' )
countCharacter_reduce: 1138.051ms
countCharacter_regex: 619.886ms
countCharacter_split: 121.945ms
countCharacter_for: 74.542ms
countCharacter_indexOf: 204.242ms

Conclusion ('>' means 'has better performance'):
for|split|indexOf > regex > reduce.
furthermore,
if the string contains more searching characters (like case2),
for>split>indexOf,
otherwise (like case1)
indexOf > split > for.
BTW: you can change the for indexOf method to fit multi-characters search (example is single character)

A: I guess this involves regex which you wanted to avoid but it's pretty quick:
function countCharacter(str, char) {
    return str.length - str.replace(new RegExp(char,"g"),"").length;
}

You can also try the str.split(char).length-1 approach suggested by Jaromanda.
Or, go all out with some fun recursion (pass 0 to startingFrom):
function countCharacter(str, char, startingFrom) {
    var idx = str.indexOf(char, startingFrom);
    return idx == -1 ? 0 : 1 + countCharacter(str, char, idx + 1);
}

You can get rid of the annoying extra argument at the cost of some efficiency:
function countCharacter(str, char) {
    var idx = str.indexOf(char);
    return idx == -1 ? 0 : 1 + countCharacter(str.substr(idx+1), char);
}

And here's a version optimized for speed (this is about 3 times faster on my browser than your original and much faster than the regex versions, according to jsperf):
function countCharacter(str, char) {
   var start = 0;
   var count = 0;
   while((start = str.indexOf(char, start)+1) !== 0) {
       count++;
   }
   return count;
}

Note that the indexOf approaches will generally be substantially faster than manually iterating through the string. See jsperf

A: using reduce:
function countCharacter(str, char) {
    return str.split('').reduce((a, x) => x === char ? ++a : a, 0);
}

A: Here you go. One line code
"hello".match(new RegExp('l','g')).length

replace 'l' with any char here, new RegExp('l','g').
that is
str.match(new RegExp(char,'g')).length

A: Have you thought of using the split() method? How about this -
function myFunction(str, char) {
    return string.split(char).length - 1
}

Let me know what you think of this solution.


text:
Q: Unable to use eclipse CDT to debug I am using eclipse mars to try to debug an application. When I use Run->Debug
The console shows following error message:
Python Exception <type 'exceptions.ImportError'> No module named gdb:
gdb: warning:
Could not load the Python gdb module from `/usr/local/share/gdb/python'.
Limited Python support is available from the _gdb module.
Suggest passing --data-directory=/path/to/gdb/data-directory.

This thread mentioned a way might fix the problem but I can not find where should I put the ./gdb -data-directory ./data-directory in eclipse.
Thanks
Rong


text:
Q: Get all filesystem tags Since OSX Mavericks supports file tags. Is there any API to access these programmatically? How can I get a list of all system tags? And manipulate them?
I tried already:

*

*NSFileManager class

*File System Programming Guide

*File Metadata Search Programming Guide

yet none of those mention the existance of tags.

A: You can find all system tags in this path:
~/Library/SyncedPreferences/com.apple.finder.plist
But the default the plist file doesn't exist. You can make it appear by adding a new tag. By the way, do you find other way to get all system tags?

A: Don't know whether this is what you are looking for:
see this thread for adding tags programmatically How can I add OS X "tags" to files programmatically?
also if you look at the NSURL reources page http://goo.gl/fwHMWk  it says about getting names of tags attached to the resource, returned as an array of NSString values using the NSURLTagNamesKey.

A: You can read finder user defaults
defaults read com.apple.Finder FavoriteTagNames

(
    "",
    Red,
    Orange,
    Yellow,
    Green,
    Blue,
    Purple,
    Gray
)


text:
Q: Почему в моей анимации, transform: scaleY(), начинает действовать сразу после запуска анимации? Ядро должно растягиваться по оси X после того, как дойдет до 600 пикселей. Я выставил кейфрейм с разницей в один процент до финального, чтобы ядро растянулось очень быстро, будто от удара об стену. Но по какой-то причине, оно начинает растягиваться с самого первого кадра. Почему так и как исправить?

@keyframes cannon
{
  0%
  {
  background-color: #333300;
  height: 50px;
  width: 150px;
  transform:translateX(-15px);
  }
  4%
  {
    transform: rotate(-50deg);
    background-color: #333300;
    height: 50px;
    width: 150px;
  }
  6%
  {
    transform: rotate(5deg);
    background-color: #333300;
    height: 50px;
    width: 150px;
  }
  12%
  {
    transform: rotate(-3deg);
    background-color: #333300;
    height: 50px;
    width: 150px;
  }
  20%
  {
    transform: rotate(1deg);
    background-color: #333300;
    height: 50px;
    width: 150px;
  }
  21%
  {
    transform: rotate(0deg);
    background-color: #333300;
    height: 50px;
    width: 150px;
  }
  100%
  {
    transform: rotate(0deg);
    background-color: #333300;
    height: 50px;
    width: 150px;
  }
}

@keyframes anima
{
  0%
  {
    background-color: #006600
  }

  99%
  {
    left: 600px;
    background-color: #006600
  }
  100%
  {
    left: 600px;
    transform: scaleY(3);
    background-color: #006600
  }

}
#cannon
{
  position: absolute;
  top: 50px;
  left: 50px;
  animation-name: cannon;
  animation-duration: 6s;
  margin: 0;
  z-index: 1;

}

#ball
{
  height: 30px;
  width: 30px;
  border-radius: 10px;
  animation-timing-function: linear;
  position: absolute;
  top: 61px;
  left: 75px;
  animation-name: anima;
  animation-duration: 6s;
  z-index: 0;

}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>

A:

@keyframes anima
{
  0%
  {
    background-color: #006600
  }

  80%
  {
    transform: scaleY(1);
    left: 600px;
    background-color: #006600
  }
  100%
  {
    left: 600px;
    transform: scaleY(3);
    background-color: #006600
  }
}


text:
Q: Spinning 3D Scatterplots inside a Shiny app I'm writing a new Shiny app, and I would like to plot a spinning 3D scatterplot using plot3d() like this one:
# Spinning 3d Scatterplot
library(rgl)
plot3d(wt, disp, mpg, col="red", size=3)

I'm trying to use something similar to what was done here:
shinyRGL examples, with the options renderWebGL({}) and webGLOutput(). But I keep getting this error:

Error in match(x, table, nomatch = 0L) :
    'match' requires vector arguments

and I couldn't figure it out why.
This is an example of the dataset I'm using now:
n=100
taxi <- data.frame(conversion=c(rep(1,20),rep(0,80)),
         day = sample(1:7, n, TRUE),
         hour = sample(0:23,n, TRUE),
         source= sample(1:4, n, TRUE),
         service= sample(1:5, n, TRUE),
         relevancy= sample(1:4, n, TRUE),
         tollfree= sample(c(0,1), n, TRUE),
         distance= sample(0:15, n, TRUE),
         similarity= sample(seq(0,1,0.01), n, TRUE),
         simi.names= sample(c('[0,0.25)','[0.25,0.5)','[0.5,0.75)','[0.75,1]'), n, TRUE),
         dist.names= sample(c('[0,1)','[1,2)','[2,3)','[3,4)','[4,15]'), n, TRUE),
         week= sample(1:7, n, TRUE),
         rel= sample(c(1,4), n, TRUE))

and I have this for ui.R:
shinyUI(navbarPage("",
               tabPanel("Data",
                        sidebarLayout(
                          sidebarPanel(
                            selectInput("dataset", h5("Choose a dataset:"), choices = c("taxicabs", "liquor stores")),
                            radioButtons("discrete", h5("I want to discretize:"), choices = c("similarity", "distance","similarity & distance","none"),
                                         inline=F, selected = "none"),
                            radioButtons("agg", h5("I want to aggregate:"), choices = c("day in weekdays/weekends", "relevancy in binary relevancy",
                                                                                "day in weekdays/weekends &  relevancy in binary relevancy","none"),
                                         inline=F, selected = "none"),
                            checkboxGroupInput("checkGroup", label = h5("Dataset Features:"),
                                               choices = c("day","hour","source","service","relevancy","tollfree","distance","similarity"), inline = F,
                                               selected = c("day","hour","source","service","relevancy","tollfree","distance","similarity"))
                          ),
                          mainPanel(
                            numericInput("obs", label = h5("Number of observations to view"), 15, min = 10, max = 20, step = 1),
                            tableOutput("view"),
                            tableOutput("var")
                          )
                        )
               ),
               tabPanel("Model",
                        h3("Best logistic model with logit link and variable selection via stepwise AIC "),
                        verbatimTextOutput("model"),
                        downloadButton('downloadReport',label = 'Download coefficients'),
                        h3("MSE"),
                        tableOutput("measures"),
                        h3("Response fit"),
                        plotOutput('plot')
               ),
               tabPanel("Visualize Fit on Features",
                        fluidRow(
                          column(4, selectInput("featureDisplay_x",
                                                label = h3("X-Axis Feature"),
                                                choices = NULL)),
                          column(4, selectInput("featureDisplay_y",
                                                label = h3("Y-Axis Feature"),
                                                choices = NULL))
                        ),
                        fluidRow(
                          column(4,
                                 plotOutput("distPlotA")
                          ),
                          column(4,
                                 plotOutput("distPlotB")
                          ),
                          column(4,
                                 webGLOutput("webGL")
                          )
                        )
               )

))

and this for server.R
options(rgl.useNULL=TRUE)
library(shiny)
library(reshape2)
library(ggplot2)
library(dplyr)
library(rgl)
library(shinyRGL)
source("webGLParser.R")

shinyServer(function(input, output, session) {
datasetInput <- reactive({
switch(input$dataset,
       "taxicabs" = taxi,
       "liquor stores" = liq)
})

observe({
choices <- c("day", "hour", "source", "service", "relevancy", "tollfree", "distance", "similarity")
if (grepl("day in weekdays/weekends", input$agg))  {
  choices[1] <- "week"
}
if (grepl("relevancy", input$agg))  {
  choices[5] <- "rel"
}
if (grepl("similarity", input$discrete)) {
  choices[8] <- "simi.names"
}
if (grepl("distance", input$discrete)) {
  choices[7] <- "dist.names"
}
updateCheckboxGroupInput(session, "checkGroup", choices = choices,
                         inline = F, selected = choices)
})

datasetagg <- reactive({
cg <- input$checkGroup
dis <- input$discrete
cg_not_d_or_s <- cg[!(cg %in% c("distance", "similarity"))]
if(input$discrete == "similarity & distance") {
  #all discrete
  right_join(
    datasetInput() %>%
      select_(.dots = cg) %>%
      group_by_(.dots = cg) %>%
      summarise(count=n()),
    datasetInput() %>%
      filter(conversion==1) %>%
      select_(.dots = cg) %>%
      count_(vars = cg)
  ) %>% mutate(prop.conv = n/count)
} else if(input$discrete == "distance") {
  cg_not_dis <- cg[cg != "similarity"]
  # one continuous
  right_join(
    datasetInput() %>%
      group_by_(.dots = cg_not_dis) %>%
      summarise_(.dots = setNames(c("mean(similarity)", "n()"),
                                  c("simi.mean", "count"))) %>%
      select_(.dots = c(cg_not_dis, "simi.mean", "count")),
    datasetInput() %>%
      filter(conversion==1) %>%
      select_(.dots = cg_not_dis) %>%
      count_(vars = cg_not_dis)
  ) %>% mutate(prop.conv = n/count)
} else if(input$discrete == "similarity") {
  cg_not_dis <- cg[cg != "distance"]
  # one continuous
  right_join(
    datasetInput() %>%
      group_by_(.dots = cg_not_dis) %>%
      summarise_(.dots = setNames(c("mean(distance)", "n()"),
                                  c("dist.mean", "count"))) %>%
      select_(.dots = c(cg_not_dis, "dist.mean", "count")),
    datasetInput() %>%
      filter(conversion==1) %>%
      select_(.dots = cg_not_dis) %>%
      count_(vars = cg_not_dis)
  ) %>% mutate(prop.conv = n/count)
} else if(input$discrete == "none") {
  # two
  right_join(
    datasetInput() %>%
      select_(.dots = cg) %>%
      group_by_(.dots = cg_not_d_or_s) %>%
      summarise(dist.mean=mean(distance), simi.mean=mean(similarity), count=n()),
    datasetInput() %>%
      filter(conversion==1) %>%
      select_(.dots = cg) %>%
      count_(vars = cg_not_d_or_s)
  ) %>% mutate(prop.conv = n/count)
}
})

# head of the table
output$view <- renderTable({
head(datasetagg(), n = input$obs)
})

output$var <- renderPrint({
if(sum(sapply(droplevels(datasetagg()),function(x)length(levels(x)))==1)==0) {
  paste(' *** ' )
} else if (sum(sapply(droplevels(datasetagg()),function(x)length(levels(x)))==1)>=1){
  paste('***Warning: ' ,names(which(sapply(droplevels(datasetagg()),function(x)length(levels(x)))==1)), 'have just 1 level and should not be selected fo the model.' )
}
})

name <- reactive({
names.datasetagg <- names(datasetagg())
names.datasetagg[names.datasetagg == 'hour'] <- paste('I((0.2034*sin(-0.298*as.numeric(',names.datasetagg[names.datasetagg == 'hour'],')+21.679)+0.3177))')
names.datasetagg <- as.formula(paste0('cbind(n,count) ~ ',paste(names.datasetagg[! (names.datasetagg %in% c("n","count","prop.conv"))],collapse = '+')))
})

fit <- reactive({
step(glm(name(), family=binomial(logit), weights = count, data=datasetagg()),
   scope=~., trace=0, direction='both', k=2)
})

# model
output$model <- renderPrint({
summary(fit()) #best model glm.step.aic.l
})

# measures
output$measures <- renderPrint({
sqrt((sum((fit()$fitted.values-datasetagg()[,'prop.conv'])^2 * datasetagg()[,'count']))/sum(datasetagg()[,'count']))
})

  # download report
output$downloadReport <- downloadHandler(
filename = "mycoefficients.json",

content = function(file) {
  write.table(coefficients(fit()), file, sep="\t")
})

 # plot fit
output$plot <- renderPlot({
ggplot(data.frame(datasetagg(),pred=fit()$fitted.values), aes(x=prop.conv)) +
  geom_histogram(aes(y=..density..),
                 binwidth=.02,
                 colour="black", fill="white") +
  geom_density(aes(x=pred),alpha=.2, fill="#E4002B")+xlab("Proportion of convertions")
})

# graphs
observe({
updateSelectInput(session, "featureDisplay_x",
                  choices =ifelse(input$checkGroup=='distance',"dist.mean",ifelse(input$checkGroup=='similarity',"simi.mean",input$checkGroup)),
                  selected=input$checkGroup[1])
updateSelectInput(session, "featureDisplay_y",
                  choices =ifelse(input$checkGroup=='distance',"dist.mean",ifelse(input$checkGroup=='similarity',"simi.mean",input$checkGroup)),
                  selected=input$checkGroup[6])
})

# dataset for prediction
a <- data.frame(matrix(c(1,18,1,1,1,0,5,0.25,'[0,0.25)','[0,1)',1,1),nrow=1))
names(a) <- c('day','hour','source','service','relevancy','tollfree','dist.mean','simi.mean','simi.names','dist.names','week','rel')
a[,c('dist.mean','simi.mean',"hour")] <- lapply(a[,c('dist.mean','simi.mean',"hour")],function(x) as.numeric(as.character(x)))

xvarData <- reactive({
col <- input$featureDisplay_x
b <- a[names(a) %in% names(datasetagg())[!(names(datasetagg()) %in% c('count', 'n', 'prop.conv'))]]
b <- b[-which(names(b) %in% col)]

sel <- c(names(datasetagg())[!(names(datasetagg()) %in% c('count', 'n', 'prop.conv'))],'mean')
pred <- predict(fit(),newdata = data.frame(datasetagg() %>%  group_by_(.dots = col) %>% summarise(mean = mean(prop.conv)) %>%
                                           cbind(b) %>%
                                             select(one_of(sel)))
                ,type="response")

datasetagg() %>%  group_by_(.dots = col) %>% summarise(mean = mean(prop.conv)) %>%
  cbind(b) %>%
  select(one_of(sel)) %>%
  mutate(pred=pred) %>%
  select_(.dots = c(col,'mean','pred'))
})

p1 <- function(data){
ggplot(melt(data(),id.vars = input$featureDisplay_x),aes_string(x=input$featureDisplay_x,y='value',colour='variable'))+
  scale_colour_manual(values=c("#7A99AC","#E4002B"),labels=c("Average", "Predict"),name  =" ")+
  geom_point() + ylab("proportion of conversions") + ylim(0, 1)
}
  output$distPlotA <- renderPlot(function() {
 plot=p1(xvarData)
 print(plot)
})

yvarData <- reactive({
col <- input$featureDisplay_y
b <- a[names(a) %in% names(datasetagg())[!(names(datasetagg()) %in% c('count', 'n', 'prop.conv'))]]
b <- b[-which(names(b) %in% col)]

sel <- c(names(datasetagg())[!(names(datasetagg()) %in% c('count', 'n', 'prop.conv'))],'mean')
pred <- predict(fit(),newdata = data.frame(datasetagg() %>%  group_by_(.dots = col) %>% summarise(mean = mean(prop.conv)) %>%
                                             cbind(b) %>%
                                             select(one_of(sel)))
                ,type="response")

  datasetagg() %>%  group_by_(.dots = col) %>% summarise(mean = mean(prop.conv)) %>%
  cbind(b) %>%
  select(one_of(sel)) %>%
  mutate(pred=pred) %>%
  select_(.dots = c(col,'mean','pred'))
})

p2 <- function(data){
ggplot(melt(data(),id.vars = input$featureDisplay_y),aes_string(x=input$featureDisplay_y,y='value',colour='variable'))+
  scale_colour_manual(values=c("#7A99AC","#E4002B"),labels=c("Average", "Predict"),name  =" ")+
  geom_point() + ylab("proportion of conversions") + ylim(0, 1)
 }
  output$distPlotB <- renderPlot(function() {
plot=p2(yvarData)
print(plot)

})

xyvarData <- reactive({
colx <- input$featureDisplay_x
coly <- input$featureDisplay_y
b <- a[names(a) %in% names(datasetagg())[!(names(datasetagg()) %in% c('count', 'n', 'prop.conv'))]]
b <- b[-which(names(b) %in% c(colx,coly))]

sel <- c(names(datasetagg())[!(names(datasetagg()) %in% c('count', 'n', 'prop.conv'))],'mean')
pred <- predict(fit(),newdata = data.frame(datasetagg() %>%  group_by_(.dots = colx,coly) %>% summarise(mean = mean(prop.conv)) %>%
                                             cbind(b) %>%
                                             select(one_of(sel)))
                ,type="response")

  datasetagg() %>%  group_by_(.dots = colx, coly) %>% summarise(mean = mean(prop.conv)) %>%
  cbind(b) %>%
  select(one_of(sel)) %>%
  mutate(pred=pred) %>%
  select_(.dots = c(colx,coly,'mean','pred'))
})

output$webGL <- renderWebGL(function() { # the error is here!!!
  output$webGL <- renderWebGL(function() {
rgl::plot3d(xyvarData()[,1],xyvarData()[,2],xyvarData()[,'mean'],col="#7A99AC",zlab = "proportion of conversions")
rgl::plot3d(xyvarData()[,1],xyvarData()[,2],xyvarData()[,'pred'],col="#E4002B",add=T)
})
})

})

I'm sorry for the long code, I just want it to make sure it was reproducible.
Any suggestions? Thanks for the help!
EDIT: I also tried with plotly without success. I got the templates from here: plotly templates for Shiny and I'm using this at UI.R:
graphOutput("ScatterPlot")

and this at Server.R:
  output$ScatterPlot <- renderGraph(function() {
## Create your Plotly graph
trace1 <- list(
  x = xyvarData()[,1],
  y = xyvarData()[,2],
  z = xyvarData()[,'mean'],
  mode = "markers",
  name = "trace0_y",
  marker = list(
    size = 12,
    line = list(
      color = "rgba(217, 217, 217, 0.14)",
      width = 0.5
    ),
    opacity = 0.8
  ),
  type = "scatter3d"
)
trace2 <- list(
  x = xyvarData()[,1],
  y = xyvarData()[,2],
  z = xyvarData()[,'pred'],
  mode = "markers",
  name = "trace1_y",
  marker = list(
    color = "rgb(127, 127, 127)",
    size = 12,
    symbol = "circle",
    line = list(
      color = "rgb(204, 204, 204)",
      width = 1
    ),
    opacity = 0.9
  ),
  type = "scatter3d"
)
data <- list(trace1, trace2)
layout <- list(
  autosize = FALSE,
  width = 500,
  height = 500,
  margin = list(
    l = 0,
    r = 0,
    b = 0,
    t = 65
  )
)

# define data
data <- list(trace1, trace2)
# define layout information
layout <- list(
  autosize = FALSE,
  width = 500,
  height = 500,
  margin = list(
    l = 0,
    r = 0,
    b = 0,
    t = 65
  )
)

# This sends message up to the browser client, which will get fed through to
# Plotly's javascript graphing library embedded inside the graph
return(list(
  list(
    id="trendPlot",
    task="newPlot",
    data=data,
    layout=layout
  )
))
})

Instead of webGLOutput() and renderWebGL({}).

A: Ok, I just got it. Thanks to Joe Cheng, I decided to use threejs and work neatly!
Now, I have at UI.R
uiOutput("ScatterPlot")

And at Server.R
  output$plott <- renderScatterplotThree({

  col <- c(rep("#7A99AC",table(xyvarData()[,'variable'])[[1]]),rep("#E4002B",table(xyvarData()[,'variable'])[[2]]))
  scatterplot3js(xyvarData()[,1],xyvarData()[,2],xyvarData()[,'value'], color=col, size=0.5,
             axisLabels=c(input$featureDisplay_x,"prop.conversions",input$featureDisplay_y),zlim=c(0,1))

})
output$ScatterPlot <- renderUI({
  scatterplotThreeOutput("plott")
})

Instead of webGLOutput() and renderWebGL({}).


text:
Q: CMake build error: Qt5PrintSupportConfig.cmake missing I am trying to build build a C++ toolkit called MITK with CMake. But I am getting this Qt5 related error. I am using the open source version of Qt 5.7.1. I can't find any file with the name Qt5PrintSupportConfig.cmake inside the Qt5 folder. The closest thing I found was windowsprintersupport.dll inside the folder printsupport. What could be the probem?
CMake Error at C:/Qt5.7.1/5.7/winrt_x64_msvc2015/lib/cmake/Qt5/Qt5Config.cmake:26 (find_package):
Could not find a package configuration file provided by "Qt5PrintSupport" with any of the following names:

    Qt5PrintSupportConfig.cmake
    qt5printsupport-config.cmake

Add the installation prefix of "Qt5PrintSupport" to CMAKE_PREFIX_PATH or
set "Qt5PrintSupport_DIR" to a directory containing one of the above files.

If "Qt5PrintSupport" provides a separate development package or SDK, be sure it has been installed.
Call Stack (most recent call first): CMakeLists.txt:211 (find_package)

A: You downloaded the wrong Qt online installer.
The one which you installed is from here: https://www.qt.io/download/
The one which you want is here: https://www.qt.io/download-open-source/ for the latest version or here https://download.qt.io/archive/online_installers/2.0/ for older versions.
I am not sure what the difference is but the one you probably installed is the normal version while the one you need is the unified version, whatever that means. Once you installed it, check this directory: C:\Qt\5.7\msvc2015_64\lib\cmake\Qt5PrintSupport since now it should include the Qt5PrintSupportConfig.cmake file.


text:
Q: Unexpected behavior when converting a character array to a string So I have this simple class, it takes a character array and parses it into a JSON object. It then stores that object internally and provides a getter.
class JSONContainer {
public:
    explicit JSONContainer(const char* const json) {
        std::string t(json);

        _json = new nlohmann::basic_json(json);
    }

    ~JSONContainer() {
        delete _json;
    }

    nlohmann::json *j() {
        return _json;
    }

private:
    nlohmann::json* _json;
};

If I instantiate the class with something simple like ...
{"data": [100,100]}

it works but if this string grows to the length of ~1000+ the incoming character array gets corrupted when I try to parse json to a string.
                      // incoming json {"data": [100,100,100,100,100...
std::string t(json);  // turns into "ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ..." after this line

I have no idea what could be causing this. The one thing I though to check was the existence of the null terminator at the end of json and I always found it.
Appreciate the help!
Additional context for comments ...
This is the method calling the constructor above ...
std::shared_ptr<void> JSONSerDes::deserialize(const char *serializedData) {
    auto *ct = new JSONContainer(serializedData);
    return std::shared_ptr<void>(ct);
}

and then going up the stack to the main function, note this line deserializedData = t->deserialize(serializedData); ...
...
    // declare intermediate data
    const char* serializedData;
    std::shared_ptr<void> deserializedData;

    // for each data set size, run each test
    for (const int testSize: sizeTestsB) {
        // generate the test data, imitate data coming from python program
        PyObject* td = data(testSize);

        for (const std::unique_ptr<SerDesTest>& t: tests) {
            // log the start
            startTest(t->type(), testSize, currentTest, totalTests);

            // mark start, ser/des mark end
            start = std::chrono::steady_clock::now();

            serializedData = t->serialize(td);                                      // Python -> Redis
            checkpoints.push_back(checkpoint(t->type(), testSize,  "PythonToRedis", start));

            deserializedData = t->deserialize(serializedData);            // Redis -> Container
            checkpoints.push_back(checkpoint(t->type(), testSize,  "RedisToContainer", start));
...

This is the function used to turn the python object into a character array. dumps is a method from pythons json module. I may be misunderstanding what the lifecycle of the character array is.
const char* JSONSerDes::serialize(PyObject * pyJson) {
    // convert pyobject to boost python object
    boost::python::object d = boost::python::extract<boost::python::object>(pyJson);

    // call the dumps function and capture the return value
    return boost::python::extract<const char*>(dumps(d));
}

A: I figured out what was wrong. When this handle
boost::python::object rv = dumps(d);

falls out of scope the data seems to get deleted, making me thing the "extracted" pointer was just referencing the internal data, not data copied out out as the provided type.
I just changed my serialize method to copy the data over to a new buffer I allocated on the heap.
const char* JSONSerDes::serialize(PyObject * pyJson) {
    // convert pyobject to boost python object
    boost::python::object d = boost::python::extract<boost::python::object>(pyJson);

    // capture the return value of the return value
    boost::python::object rv = dumps(d);
    const char* prv = boost::python::extract<const char*>(rv);
    size_t prvLen = strlen(prv);

    // copy and return
    char* rvBuffer = new char[prvLen + 1];
    rvBuffer[prvLen] = '\0';
    strncpy(rvBuffer, prv, strlen(prv));

    // call the dumps function and capture the return value
    return rvBuffer;
}


text:
Q: How to navigate by using withRouter in reactJS while clicking on button react-router 6.2.1 How to navigate by using withRouter in reactJS while clicking on button react-router 6.2.1.
I am using react "react-router": "^6.2.1","react-router-dom": "^6.2.1",
I am getting error by
export 'withRouter' (imported as 'withRouter') was not found in 'react-router-dom'
Here is my code.
import React, { Component } from "react";
import { withRouter } from 'react-router-dom';

class myTab extends Component {
constructor(props) {
    super(props);
        this.state = {};
}

createNew = () =>{
    this.props.history.push(`/new/`);
}

render() {
    return (

                <button type="create" class="btn btn-primary" width="300"  onClick={this.createNew}> New </button>

    );
  }
}

export default withRouter(myTab);

Even though I am downgrading react router to 5.2 I am getting the same errror.
What options i have to fix this.


text:
Q: DbDataController in MVC4 UpdateEntity failing I have a datamodel like
ModelA which contains a Collection.
ModelB contains a Collection as a backreference. That is failing because of cyclic references if I query with Include("ModelB"). Not good but I solved that via setting ModelB.List=null for each element.
The problem now is submitting a changed ModelA tree: I am adding ModelB-entities to ModelA.ModelB[]. Now the UpdateEntity function is complaining the it could not add elements of type ModelB which are declared static. The JSON deserializer is creating static arrays.
How is it possible with the combination of upshot/MVC4 to submit datamodels which are not completely flat? As it is not possible right now to create your own DTO objects where you might figure out something I am stuck now...
After investigating the error a bit better, I think the problem is the cyclic backreference:
The ModelA->ModelB->ModelA is breaking the storage of the data. "Could not add data of type ModelA to type ModelB".
As I mentioned the backreference was set to Null because the cyclic ref serialisation problem...
I hope the will be some easier way on doing more manually with DTO objects where I have mroe control.
Please see also: MVC 4, Upshot entities cyclic references for the beginning of the journey...

A: To solve the cyclic backreference, you can use the ignoreDataMember attribute:
public class Customer
{
    [Key]
    public int CustomerId { get; set; }

    public string Name { get; set; }
    public string Address { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }

    public virtual ICollection<Delivery> Deliveries { get; set; }
}

public class Delivery
{
    [Key]
    public int DeliveryId { get; set; }
    public string Description { get; set; }
    public bool IsDelivered { get; set; }

    [IgnoreDataMember]
    public virtual Customer Customer { get; set; }
    public virtual int CustomerId { get; set; }
}

I posted a working solution to your problem in a different question: https://stackoverflow.com/a/10010695/1226140


text:
Q: Mixing SFP's with different speeds I need to install new SFP's in a location; however, I need them to connect to existing switches and I'm not sure what SFP type they are.  All I know is I've got MM Fiber.
If I installed Cisco GLC-SX-MM 1000Base SFP's, would that cause an issue if the other end of that fiber was connected to a 100Base SFP, or do I need to have matching speeds on both ends?

A:
If I installed Cisco GLC-SX-MM 1000Base SFP's, would that cause an issue if the other end of that fiber was connected to a 100Base SFP? Or do I need to have matching speeds on both ends?

Your speeds must match

A: There are some handy links in this other serverfault question which might help.
How compatible are sfp's really?

A: It depends on what you mean by cause an issue. It won't break anything but you won't get a link either. They must be the same. SFPs are hot-swappable so you can remove it to inspect the label without damaging it. Additionally, you can do a show interface status to have the switch tell you the model SFP that is installed in a port.
Not only can you not mix speeds but you should stay away from mixing sfp models as well.


text:
Q: React - Warning: Cannot update a component (`PrivateRoute`) while rendering a different component (`Modules`) Getting the following error on all child components.

react-dom.development.js:86 Warning: Cannot update a component
(PrivateRoute) while rendering a different component (Example). To
locate the bad setState() call inside Examples,

I've found lots of examples of the same error but thus far no solutions
React Route Warning: Cannot update a component (`App`) while rendering a different component (`Context.Consumer`)
Can Redux cause the React warning "Cannot update a component while rendering a different component"
The PrivateRoute wraps the component to redirect if not logged in.
export default function PrivateRoute() {
  const session: ISessionReducer = useSelector((state: RootState) => state.core.session);

  useEffect(() => {
    if (!session.jwt) <Navigate to="/login" />;
  }, [session]);

  return <Outlet />;
};

A: It is happening because useEffect runs after the component is rendered. So what's happening in this case is that your Outlet component is getting rendered first before your code in useEffect runs. So if the jwt token doesn't exist then it will try to redirect but it won't be able to because your Outlet will already be rendered by then.
So I can give you the solution of what I use to check if the jwt token exist.
1.) I create a custom hook for checking if the token exists.
2.) And then I use that custom hook in my privateRoute component to check if the user is loggedIn.
useAuthStatus.js
import { useState, useEffect } from 'react'
import { useSelector } from 'react-redux'

export const useAuthStatus = () => {
  const [loggedIn, setLoggedIn] = useState(false)
  const [checkingStatus, setCheckingStatus] = useState(true)

  const { user } = useSelector((state) => state.auth)

  useEffect(() => {
    if (user?.token) {
      setLoggedIn(true)
    } else {
      setLoggedIn(false)
    }

    setCheckingStatus(false)
  }, [user?.token])

  return { loggedIn, checkingStatus }
}

PrivateRoute component
import { Navigate, Outlet } from 'react-router-dom'
import { useAuthStatus } from '../../hooks/useAuthStatus'
import CircularProgress from '@mui/material/CircularProgress'

const PrivateRoute = () => {
  const { loggedIn, checkingStatus } = useAuthStatus()

  if (checkingStatus) {
    return <CircularProgress className='app__modal-loader' />
  }

  return loggedIn ? <Outlet /> : <Navigate to='/login' />
}

export default PrivateRoute


text:
Q: Django [WinError 10053] when loading up server Whenever I start up my Django server i get the errors shown below. The weird thing is that sometimes the [WinError 10053] doesn't show up and I can develop normally but when it does show up the project seems to malfunction and .css and .js files also don't get loaded.
I have already looked into other stackoverflow questions that seemed related such as setting the correct code page to use with postgres or the python bug mentioned here https://bugs.python.org/issue27682. But I'm using python 3.9 so that bug should be fixed.
Does anyone know how to fix this? The project works just fine on the computers of some other people and everything that we compared seemed the same (settings, pycharm configuration,...).
Exception occurred during processing of request from ('127.0.0.1', 59986)
----------------------------------------
Exception occurred during processing of request from ('127.0.0.1', 55047)
Traceback (most recent call last):
  File "D:\DataDownloads\lib\socketserver.py", line 683, in process_request_thread
    self.finish_request(request, client_address)
Traceback (most recent call last):
  File "D:\DataDownloads\lib\socketserver.py", line 683, in process_request_thread
    self.finish_request(request, client_address)
  File "D:\DataDownloads\lib\socketserver.py", line 360, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "D:\DataDownloads\lib\socketserver.py", line 360, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "D:\DataDownloads\lib\socketserver.py", line 747, in __init__
    self.handle()
  File "D:\Documents - data drive\StepDB\gitlab\site\Site\venv\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle
    self.handle_one_request()
  File "D:\Documents - data drive\StepDB\gitlab\site\Site\venv\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request
    self.raw_requestline = self.rfile.readline(65537)
  File "D:\DataDownloads\lib\socket.py", line 704, in readinto
    return self._sock.recv_into(b)
ConnectionAbortedError: [WinError 10053] De software op uw hostcomputer heeft een verbinding verbroken
  File "D:\DataDownloads\lib\socketserver.py", line 747, in __init__
    self.handle()
  File "D:\Documents - data drive\StepDB\gitlab\site\Site\venv\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle
    self.handle_one_request()
  File "D:\Documents - data drive\StepDB\gitlab\site\Site\venv\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request
    self.raw_requestline = self.rfile.readline(65537)
----------------------------------------
  File "D:\DataDownloads\lib\socket.py", line 704, in readinto
    return self._sock.recv_into(b)
ConnectionAbortedError: [WinError 10053] De software op uw hostcomputer heeft een verbinding verbroken
----------------------------------------
----------------------------------------
Exception occurred during processing of request from ('127.0.0.1', 64741)
Traceback (most recent call last):
  File "D:\DataDownloads\lib\socketserver.py", line 683, in process_request_thread
    self.finish_request(request, client_address)
  File "D:\DataDownloads\lib\socketserver.py", line 360, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "D:\DataDownloads\lib\socketserver.py", line 747, in __init__
    self.handle()
  File "D:\Documents - data drive\StepDB\gitlab\site\Site\venv\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle
    self.handle_one_request()
  File "D:\Documents - data drive\StepDB\gitlab\site\Site\venv\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request
    self.raw_requestline = self.rfile.readline(65537)
  File "D:\DataDownloads\lib\socket.py", line 704, in readinto
    return self._sock.recv_into(b)
ConnectionAbortedError: [WinError 10053] De software op uw hostcomputer heeft een verbinding verbroken
----------------------------------------
----------------------------------------
Exception occurred during processing of request from ('127.0.0.1', 59454)
Traceback (most recent call last):
  File "D:\DataDownloads\lib\socketserver.py", line 683, in process_request_thread
    self.finish_request(request, client_address)
  File "D:\DataDownloads\lib\socketserver.py", line 360, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "D:\DataDownloads\lib\socketserver.py", line 747, in __init__
    self.handle()
  File "D:\Documents - data drive\StepDB\gitlab\site\Site\venv\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle
    self.handle_one_request()
  File "D:\Documents - data drive\StepDB\gitlab\site\Site\venv\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request
    self.raw_requestline = self.rfile.readline(65537)
  File "D:\DataDownloads\lib\socket.py", line 704, in readinto
    return self._sock.recv_into(b)
ConnectionAbortedError: [WinError 10053] De software op uw hostcomputer heeft een verbinding verbroken
--------------------------------------