text:
Q: in flutter, how do I save data from a list of autogenerated textfields In my app I have a list of bedrooms that a person can select, if a user selects 1 and 2 bedrooms, two textfields are generated from those selecttions
   _apartmentBedrooms.length > 0
                  ? Container(
                      child: ListView.builder(
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemCount: _apartmentBedrooms.length,
                        itemBuilder: (context, index) {
                          _controllers.add(new TextEditingController());
                          print(_controllers[index]);
                          return BlocBuilder<AddPropertyBloc, AddPropertyState>(
                            builder: (context, state) {
                              return Padding(
                                padding: const EdgeInsets.only(left: 15, right: 15, top: 10),
                                child: Container(
                                  padding: EdgeInsets.only(right: 15, left: 10),
                                  height: 40,
                                  decoration: BoxDecoration(
                                    color: ColorConfig.smokeLight,
                                    borderRadius: BorderRadius.circular(5),
                                  ),
                                  child: Padding(
                                    padding: const EdgeInsets.only(bottom: 5.0),
                                    child: TextFormField(
                                      controller: _controllers[index],
                                      onFieldSubmitted: (value) {
                                        // BlocProvider.of<AddPropertyBloc>(context).add(EnteredPriceEvent(price: value));
                                        print(_controllers[index].text);
                                        prices.add(_controllers[index].text);
                                        print(prices);
                                      },
                                      keyboardType: TextInputType.number,
                                      style: TextStyle(
                                        fontFamily: FontConfig.regular,
                                        fontSize: Sizeconfig.small,
                                        color: ColorConfig.dark,
                                      ),
                                      decoration: InputDecoration(
                                        hintText: _apartmentBedrooms[index].toString() + " bedroom Price*",
                                        hintStyle: TextStyle(
                                          fontFamily: FontConfig.regular,
                                          fontSize: Sizeconfig.small,
                                          color: ColorConfig.dark,
                                        ),
                                        border: InputBorder.none,
                                      ),
                                    ),
                                  ),
                                ),
                              );
                            },
                          );
                        },
                      ),
                    )
                  : Text("choose bedrooms first"),

I have a list of textEditingControllers that are generated for each bedroom selected. The problem is if I use onChanged it ends up adding to the list infinite items from any changed item, when I use onfieldsubitted and I change any value, they get added as new items on list which I dont want.  I want save the prices for each bedroom whether changed or just added. How can I achieve that.

A: You can simply generate the Controller when there is no controller for the index by using a Map. Something like this:
Map<int, TextEditingController> _mapControllers = Map();

TextEditingController _controllerOf(int index) {
    var item = _mapControllers[index];
    if(item == null) {
       item = TextEditingController();
       _mapControllers[index] = item;
    }
    return item;
}

where you can use it like this:
TextFormField(
    controller: _controllerOf(index),
    ...
)

Then, you can get the text from controllers by something like this:
List<String> _textsOf(Map<int, TextEditingController> mapControllers) {
    // Sort map by index of the builder.
    var sortedKeys = mapControllers.keys.toList()..sort();

    List<String> texts = [];
    for(var key in sortedKeys) {
       texts.add(mapControllers[key].text);
    }

    return texts;
}

Please be noted, I haven't test the code yet.


text:
Q: How to insert a line break in a string literal ES6 Hello I have a method where I have to print address in this format:-
AddressLine1,
City, State

In other words I want a line break after AddressLine1.
So I have a method like this:-
const getAddress = pursuit => {
  if(pursuit.address!=null){
    const addressLine1 = pursuit.address.addressLine1;
    const cityState = `${pursuit.address.addressCity}, ${pursuit.address.addressState.value}`;
    return `${addressLine1},\n
            ${cityState}`;
  }
  return '';
};

But it doesn't give me the desired result.

A: You are having issues because you are already inserting a line break and leading whitespace in your template string. To achieve your desired result, you can just have the \n, that is, everything on a single line:
const getAddress = pursuit => {
  if(pursuit.address!=null){
    const addressLine1 = pursuit.address.addressLine1;
    const cityState = `${pursuit.address.addressCity}, ${pursuit.address.addressState.value}`;
    return `${addressLine1},\n${cityState}`;
  }
  return '';
};

A shorter and runnable example:

const part1 = 'A long text that'
const part2 = 'continues below';
const longText = `${part1}\n${part2}`;

console.log(longText);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hyperlink in a datatemplatecolumn has issues with updating CurrentItem of DataGrid I have a DataGrid with rows and columns. Each row corresponds to an item in my data collection. For one of my columns, I want to have a hyperlink with text of the name of my data item, and when I click on the hyperlink, it will execute a command for THAT hyperlink's item (the row it is on)
Hope that makes sense so far.
My issue: How do I bind the hyperlink's CommandParameter to use the current row's data item? I'm running into an issue where if I have some random cell selected (say row 3 column 2) and I click a hyperlink in row 1 column 1, it will say the current item is the item in row 3 not row 1!!!
This is my xaml code:
<DataGridTemplateColumn Width="80">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock>
                <Hyperlink Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}, Path=DataContext.NavigateToFormCommand}"
                   CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}, Path=CurrentItem}">
                    <TextBlock Text="{Binding dataName}" />
                </Hyperlink>
            </TextBlock>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

If I click the cell the hyperlink is in, and THEN click the hyperlink, everything will work fine. But that's not a really good workflow...if the user clicks the hyperlink it should have the right item...

A: I've solved my own issue, thanks for the help guys (lol)
Anyways, just for the fact that this might help someone later down the road, I didn't use CurrentItem since it doesn't seem to be updating correctly when I click a hyperlink. Instead, I gave the data I needed for the command as a command parameter.
So, the command actually only used the name of my data item, so instead of passing the whole data item (current item), I passed the name instead, and it works fine now.
<Hyperlink Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}, Path=DataContext.NavigateToFormCommand}"
                   CommandParameter="{Binding dataName}">


text:
Q: Booting an emulator with modified/custom userdata.img file I have been trying to boot an emulator with user data from a real device. When we create an Android emulator, by default it uses the userdata.img file from AVD location. In my case, C:\Users\User.Android\avd\emulator.avd\userdata.img
I want to load my userdata such as pictures, music from my real phone into an emulator. I created a dd image of data partition(I named it userdata.img) from a real device and replaced the original userdata.img file from my emulator.avd location. I also made sure that there is enough disk space while creating this emulator(The size of the image taken from real device is 800MB and DISK SIZE given to emulator is 1000MB).
When I launch the emulator with these modifications, it is not loading with newly added image(It keeps loading for hours and hours but not reaching the home screen). Please guide what are the other steps I need to consider to load it.
Real device is SONY C1505 model running JellyBean(Android 4.1.1). Emulator is also created using JellyBean(Android 4.1).

A: It could be that the data partition doesn't have enough space - try running the emulator yourself with the option -partition-size 1024
You could also use -show-kernel to see kernel logs to identify the problem


text:
Q: Deploy NodeJS Express on amplify I am trying to deploy an app on AWS Amplify.
The app is React front and and NodeJS Express backend.
The frontend works fine, but the backend is just stuck without any reasonable explanation
My YML file is
version: 1
backend:
  phases:
    build:
      commands:
        - npm run build-backend
    postBuild:
        commands:
        - cd ..
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
        - npm run build-frontend
  artifacts:
    baseDirectory: ./client/build
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

build backend-script :
"build-backend": "cd server && npm run start",

npm run start script:
"start": "npm install && node index.js"

The build is getting stuck on the npm install and after 10-20 minutes just "gives up" without the following log
2021-04-22T11:49:20.693Z [INFO]: > server@1.0.0 start /codebuild/output/src650104622/src/myBlog/server
                                 > npm install && node index.js
2021-04-22T11:49:26.976Z [INFO]: > bcrypt@5.0.0 install /codebuild/output/src650104622/src/myBlog/server/node_modules/bcrypt
                                 > node-pre-gyp install --fallback-to-build

Thanks

A: I came across this thread while looking for a solution for my project. And because there are no more answers here, I'll tell you what I could find myself.
Amplify works fine with SSG web applications (Gatsby, etc.), with SSR (React, NextJS, NuxtJS, etc.) and with simple NodeJS and ExpressJS applications (which only run on requests because Amplify uses Lambda-functions to handle it). So:

*

*If you need a simple ExpressJS application for your API you can
use the following serverless Ampl solution:
https://docs.amplify.aws/guides/api-rest/express-server/q/platform/js/

*If you need a socket.io application (or another constantly
running application) you need to use AWS Fargate (uses
docker images) or AWS EC2 (works on simple virtual machine
with access by SSH) solutions.
P.S. If you have any other information on this subject, please post it here.


text:
Q: Bounce webkit animation This is hard to explain, bit I'll give it a shot.
I currently have an image background that endlessly slides from right to left, like a conveyor belt. The image just repeats when it runs out.
I'm trying to to get the image/animation to bounce (reverse direction) before it repeats. So the image slowly slides one way, then slowly back the other way.
CSS:
#bg {
    -moz-animation: bg 60s linear infinite;
    -webkit-animation: bg 60s linear infinite;
    -ms-animation: bg 60s linear infinite;
    animation: bg 60s linear infinite;
    -moz-backface-visibility: hidden;
    -webkit-backface-visibility: hidden;
    -ms-backface-visibility: hidden;
    backface-visibility: hidden;
    -moz-transform: translate3d(0,0,0);
    -webkit-transform: translate3d(0,0,0);
    -ms-transform: translate3d(0,0,0);
    transform: translate3d(0,0,0);

    background: #348cb2 url("images/cns-lagoon-sunrise.jpg") bottom left;
    background-repeat: repeat-x;
    height: 100%;
    left: 0;
    opacity: 1;
    position: fixed;
    top: 0;
}

@-moz-keyframes bg {
    0% {
        -moz-transform: translate3d(0,0,0);
        -webkit-transform: translate3d(0,0,0);
        -ms-transform: translate3d(0,0,0);
        transform: translate3d(0,0,0);
    }

    100% {
        -moz-transform: translate3d(-2250px,0,0);
        -webkit-transform: translate3d(-2250px,0,0);
        -ms-transform: translate3d(-2250px,0,0);
        transform: translate3d(-2250px,0,0);
    }
}

@-webkit-keyframes bg {
    0% {
        -moz-transform: translate3d(0,0,0);
        -webkit-transform: translate3d(0,0,0);
        -ms-transform: translate3d(0,0,0);
        transform: translate3d(0,0,0);
    }

    100% {
        -moz-transform: translate3d(-2250px,0,0);
        -webkit-transform: translate3d(-2250px,0,0);
        -ms-transform: translate3d(-2250px,0,0);
        transform: translate3d(-2250px,0,0);
    }
}

@-ms-keyframes bg {
    0% {
        -moz-transform: translate3d(0,0,0);
        -webkit-transform: translate3d(0,0,0);
        -ms-transform: translate3d(0,0,0);
        transform: translate3d(0,0,0);
    }

    100% {
        -moz-transform: translate3d(-2250px,0,0);
        -webkit-transform: translate3d(-2250px,0,0);
        -ms-transform: translate3d(-2250px,0,0);
        transform: translate3d(-2250px,0,0);
    }
}

@keyframes bg {
    0% {
        -moz-transform: translate3d(0,0,0);
        -webkit-transform: translate3d(0,0,0);
        -ms-transform: translate3d(0,0,0);
        transform: translate3d(0,0,0);
    }

    100% {
        -moz-transform: translate3d(-2250px,0,0);
        -webkit-transform: translate3d(-2250px,0,0);
        -ms-transform: translate3d(-2250px,0,0);
        transform: translate3d(-2250px,0,0);
    }
}

#bg {
    background-size: 2250px auto;
    width: 6750px;
}

I've tried animation-direction: alternate; but that just reverses the whole animation :(
Before I bother my friend (again) for help, I though I'd reach out here. Can anyone help?

A: If you do 2D translation in only x direction, you can use translateX instead of translate3d for simplicity. But translate3d will work as well if you prefer.
To answer your question, I will show only standard css (withoud prefixes). You can easily add prefixes. Apply these changes:
@keyframes bg {
    0% {
        transform: translateX(0);
    }
    50% {
        transform: translateX(-2250px);
    }
    100% {
        transform: translateX(0);
    }
}

I just copied the value -2250px from your code. You will probably need to adapt that value to your needs.


text:
Q: Filtering properties and placeholders in spring How can I avoid repetition with spring placeholders? Usually I load all the properties and later use them one by one, repeating everything 3 times (properties file, property name from xml, placeholder name):
<context:property-placeholder location="classpath:/spring/application.properties,
                                        classpath:/spring/${env}.properties" />

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="properties">
            <value>
                user = ${db.user}
                password = ${db.passwd}
            </value>
        </property>
</bean>

I can do:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="properties" ref="allProperties"/>
</bean>

However, it's not a good solution because:

*

*If I have many components then there can be some properties clash

*I don't want passing passwords

*I also don't want to split my configuration files per each component. I want to have 1 global file and 1 file per each environment. Splitting properties would make it hard to maintain

So the question is:
Is there anything that would let me choose properties (by prefix) that should be passed? Something like:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="properties">
            <bean class="...PropertiesFilter">
                <property name="prefix" value="c3p0"/>
                <property name="src" ref="allProperties"/>
            </bean>
        </property>
</bean>

I know, it's not hard to write but maybe spring already has something like that (with better syntax).


text:
Q: Building JAR file with IntelliJ, OpenJFX and Gradle What is in 2021 the best way to create an executable jar file with Gradle in IntelliJ using OpenJFX? Every solution I found is very complex and uses workarounds. This is my current build.gradle file
plugins {
    id 'java'
    id 'application'
    id 'org.openjfx.javafxplugin' version '0.0.9'
}

tasks.withType(JavaCompile) {
    options.encoding = "UTF-8"
}

repositories {
    mavenCentral()
}

javafx {
    version = "15.0.1"
    modules = [ 'javafx.controls', 'javafx.fxml' ]
}

mainClassName = 'com.company.crawl.main.Main'

group 'com.company'
version '1.0-SNAPSHOT'

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.6'
    compile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '9.2.0.jre15'
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.11'
    compile group: 'org.apache.commons', name: 'commons-csv', version: '1.8'
}

jar {
    from configurations.compile.collect {zipTree it}
    manifest.attributes "Main-Class": "com.company.crawl.main.Main"
}

If I run gradle :jar, the jar file includes the dependencies but not the openjfx sdk. What do I have to do to run the jar using the openjfx sdk?
UPDATE 1
changed the jar path to this:
jar {
    manifest {
        attributes 'Main-Class': 'com.company.crawl.main.Main'
    }
    from {
        configurations.runtimeClasspath.collect {it.isDirectory() ? it : zipTree(it)}
    }
}

after rebuilding the jar, I get the error: "JavaFX runtime components are missing". I don't know why because in the jar file the javafx folders are included. After that I added the VM options:
--module-path /path/to/javafx-sdk/lib --add-modules=javafx.controls,javafx.fxml

and the jar file runs. So what am I doing wrong?


text:
Q: Remote to docker host daemon.json set up problem I have a docker desktop installed on my windows client but I want to connect to a Linux host server where I have docker and some containers running
When I do what is described here or in the docs and create a daemon.json
root@Docker:/etc/docker# systemctl daemon-reload
root@Docker:/etc/docker# systemctl restart docker.service
Job for docker.service failed because the control process exited with error code.
See "systemctl status docker.service" and "journalctl -xe" for details.
root@Docker:/etc/docker# dockerd
INFO[2022-05-21T22:15:44.911000210Z] Starting up
WARN[2022-05-21T22:27:16.421785866Z] Binding to IP address without --tlsverify is insecure and gives root access on this machine to everyone who has access to your network.  host="tcp://0.0.0.0:2376"
WARN[2022-05-21T22:27:16.421811753Z] Binding to an IP address, even on localhost, can also give access to scripts run in a browser. Be safe out there!  host="tcp://0.0.0.0:2376"
WARN[2022-05-21T22:27:17.421973948Z] Binding to an IP address without --tlsverify is deprecated. Startup is intentionally being slowed down to show this message  host="tcp://0.0.0.0:2376"
WARN[2022-05-21T22:27:17.422102835Z] Please consider generating tls certificates with client validation to prevent exposing unauthenticated root access to your network  host="tcp://0.0.0.0:2376"
WARN[2022-05-21T22:27:17.422151726Z] You can override this by explicitly specifying '--tls=false' or '--tlsverify=false'  host="tcp://0.0.0.0:2376"
WARN[2022-05-21T22:27:17.422199210Z] Support for listening on TCP without authentication or explicit intent to run without authentication will be removed in the next release  host="tcp://0.0.0.0:2376"
INFO[2022-05-21T22:27:32.427159372Z] parsed scheme: "unix"                         module=grpc
INFO[2022-05-21T22:27:32.427252568Z] scheme "unix" not registered, fallback to default scheme  module=grpc
INFO[2022-05-21T22:27:32.427313370Z] ccResolverWrapper: sending update to cc: {[{unix:///run/containerd/containerd.sock  <nil> 0 <nil>}] <nil> <nil>}  module=grpc
INFO[2022-05-21T22:27:32.427344997Z] ClientConn switching balancer to "pick_first"  module=grpc
INFO[2022-05-21T22:27:32.434202191Z] parsed scheme: "unix"                         module=grpc
INFO[2022-05-21T22:27:32.434266723Z] scheme "unix" not registered, fallback to default scheme  module=grpc
INFO[2022-05-21T22:27:32.434321187Z] ccResolverWrapper: sending update to cc: {[{unix:///run/containerd/containerd.sock  <nil> 0 <nil>}] <nil> <nil>}  module=grpc
INFO[2022-05-21T22:27:32.434350739Z] ClientConn switching balancer to "pick_first"  module=grpc
INFO[2022-05-21T22:27:32.442793741Z] [graphdriver] using prior storage driver: overlay2
INFO[2022-05-21T22:27:32.460473338Z] Loading containers: start.
INFO[2022-05-21T22:27:32.677853303Z] Default bridge (docker0) is assigned with an IP address 172.17.0.0/16. Daemon option --bip can be used to set a preferred IP address
INFO[2022-05-21T22:27:33.205926671Z] Loading containers: done.
WARN[2022-05-21T22:27:33.222645712Z] Not using native diff for overlay2, this may cause degraded performance for building images: running in a user namespace  storage-driver=overlay2
INFO[2022-05-21T22:27:33.222936503Z] Docker daemon                                 commit=75249d8 graphdriver(s)=overlay2 version=20.10.8
INFO[2022-05-21T22:27:33.222997151Z] Daemon has completed initialization
INFO[2022-05-21T22:27:33.260295863Z] API listen on /var/run/docker.sock
INFO[2022-05-21T22:27:33.271850141Z] API listen on [::]:2376

a reboot of the docker service throws an error.
though dockerd is starting up manually, then I am stuck in the console
While I am still not able to connect from my windows machine. Even after setting
set DOCKER_HOST=tcp://<Ubuntu-Docker_Host-IP>:2376

and restarting docker desktop, with "docker ps -a" it only shows me local containers.


text:
Q: Plotting a 3D vector field on 2D plane I want to visualize vector field that is of the form
$(v_1(x,y), v_2(x,y), v_3(x,y))$,
i.e. there is a three component vector that depends on only two coordinates $x$ and $y$ in the real plane. There are Mathematica functions VectorPlot[] and VectorPlot3D[] but both of them assume that the dimensionality of the space is the same as the number of vector components. In the latest version of Mathematica there also seems to be something called SliceVectorPlot3D[], but I don't have this in my Mathematica so I would prefer to use some other way. Furthermore, if it matters at all, the vectors are normalized so that I only care about the direction of the vector at a given point on the plane.
How do I do this?
EDIT: Here's an example of something I would like to get:

A: You can just do this with graphics primitives:
v = Flatten[
   Table[ { x , y  , { Sin[x ] , Cos[ y] , 2} } , {x, -Pi,
     Pi, .5} , {y, -Pi, Pi, .5}], 1];
Graphics3D[{Red,
    Arrow[Tube[{{#[[1]], #[[2]],
        0}, {#[[1]] + #[[3, 1]], #[[2]] + #[[3, 2]], #[[3,
          3]]}}]]} & /@ v, Axes -> True]

A: Another take, using ListPointPlot3D:
Define vector field on the x-y plane:
f[x_, y_] = {.3 Sin[x], .3 Cos[y], 1}

Define grid on the x-y plane where the vector tails will be placed:
data = Flatten[Table[{x, y, 0}, {x, -Pi, Pi, Pi/4}, {y, -Pi, Pi, Pi/4}], 1]

Plot with ListPointPlot3D using a replacement rule to convert points to vectors:
ListPointPlot3D[data] /. Point[a_] :> (Arrow[Tube[{#, # + f @@ Most@#}, .05]] & /@ a)

Easily extendable to arbitrary surfaces (just add some z[x,y] instead of 0 in the data specification.
z[x_, y_] = .3 Sin[x] + .3 Cos[y];
data = Flatten[Table[{x, y, z[x, y]}, {x, -Pi, Pi, Pi/4}, {y, -Pi, Pi, Pi/4}], 1];
ListPointPlot3D[data] /. {Point[a_] :> (Arrow[Tube[{#, # + f @@ Most@#}]] & /@ a)};
ListPlot3D[data];
Show[{%, %%}, PlotRangePadding -> {.3, .3, {.1, .9}}]

A: @J.M. is right. Define each vector as a function (eg v1[x_,y_]:=x+y) and then use ParametricPlot3D[] parametrized for x and y.
Example:
v1[x_, y_] := Sin[x]*y;
v2[x_, y_] := Cos[x]*y;
v3[x_, y_] := x;
ParametricPlot3D[{v1[x, y], v2[x, y], v3[x, y]},
 {x, -2 \[Pi], 2 \[Pi]}, {y, -2 \[Pi], 2 \[Pi]}]


text:
Q: CakePHP - What is the best approach to create an Admin Section I am looking for an insight into the best approach to create an administrator section in CakePHP. I've looked at plugins like BrowniePHP as well as others, but I am not entirely satisfied with using plugins. So I am trying to create my own which will encompass the things I need. I;ve looked at some tutorials, but cant find the right answer.
I am currently creating a vast application, which is about 10% done, but I now feel the need to have an admin section before moving on.
Basically I would like a section where I can add new articles, approve comments, deny user access, etc. This section should only be accessible by an administrator.
Also, this administrator section must be able to save to any other model.
I am still learning CakePHP and any detailed instruction would be appreciated.

A: to create an admin-section the first thing you have to do is to manually edit the core.php within /app/config and write the setting Routing.prefixes. This line should be around line 88 somewhere and you just have to uncomment it.
In case you can't find it, it should look like this:
Configure::write('Routing.prefixes', array('admin'));

So now you can write your admin-functions within your controllers like this:
function admin_edit($id = null) {
    //your admin function
}

You don't need access to every model since your writing these function within your controllers like every other "normal" action.
You just have to connect a route to handle the admin-actions:
Router::connect('/admin/:controller/:action/*', array('admin' => true, 'prefix' => 'admin', 'controller' => 'pages'));
// 'admin' => true is a variable for you so you can check if it's an admin-action which is requested
// 'prefix' => 'admin' means that you can write function with this prefix like above

You can then access these actions via the url http://yourapp.com/admin/controller/action
If you now use the Auth-Component you can write methods for checking if a user is allowed to access these methods.
For further information please read these manual-entrys:
Prefix-Routing
Authentication (Auth-Component)


text:
Q: Vue.js project structure for two SPA applications with shared components I'm starting a project using Vue.js library. Project contains three applications:

*

*b2c (http://somedomain.com)

*admin (http://admin.somedomain.com)

*shared components between b2c and admin (stores, components, model etc)

How should I set up project structure and webpack configuration to prevent code duplication using shared components. Moreover I would like to use npm run build to produce build\admin and build\b2c and keep building/publishing simple (without additional repositories like nuget etc).
Thanks for providing any reference materials or templates.

A: Here is an example using ES6 modules (you can use webpack's modules for sure, but i prefer this way). For example you have this structure
/assets
/-js
/--components
/---shared
/---admin
/---b2c
/--directives
/--stores
/--models
/b2c.js
/admin.js

So in your b2c.js you need to use it in this way.
import Vue from 'Vue';

import component from './components/shared/SomeComponent.vue';

/*or var component = require('./components/shared/SomeComponent.vue'); if you want to use webpack here*/

import b2cOnly   from './components/b2c/SomeComponent.vue';

let app = new Vue({
  el: '#app',
  components: {component, b2cOnly}
});

And similar admin.js
import Vue from 'Vue';

import component from './components/shared/SomeComponent.vue';

import adminOnly   from './components/admin/SomeComponent.vue';

let app = new Vue({
  el: '#app',
  components: {component, adminOnly}
});

Then you can easily bundle it with vue-loader (or vueify if you using browserify, like i am https://github.com/vuejs/vueify)
http://vue-loader.vuejs.org/en/start/tutorial.html
Here is an example of webpack.config.js from docs
// webpack.config.js
module.exports = {
  // other options ...
  module: {
loaders: [
  {
    // use vue-loader for *.vue files
    test: /\.vue$/,
    loader: 'vue'
  },
  {
    // use babel-loader for *.js files
    test: /\.js$/,
    loader: 'babel',
    // important: exclude files in node_modules
    // otherwise it's going to be really slow!
    exclude: /node_modules/
  }
]
},
  // if you are using babel-loader directly then
  // the babel config block becomes required.
  babel: {
    presets: ['es2015'],
    plugins: ['transform-runtime']
  }
}

Then, you can include yours compiled admin.js and b2c.js somewhere in your project.


text:
Q: How should I deal with these SNMP mib file parsing errors? I am trying to use the mib files supplied by Cisco to make sense the info obtainend by polling my switch via SNMP. It's a SG300-52P, the files can be found here.
After I placed the files in one of netsnmp's default mib directories, there were multiple errors when I tried to decode one of the description to its numeric value to verify that the mib files work. I thought about resolving the issues, but they were too numerous, so I decided to just try and get the simplest of these files to work with netsnmp. I placed only the SNMPv2-SMI file in one of netsnmp's default mib directories (because that came up in the errors and is a short file with no dependencies; I've appended the content for easy reference) and ran the following command:
snmptranslate -m SNMPv2-SMI zeroDotZero

However, this returns the following two erros:
Expected LAST-UPDATED (SMI): At line 35 in /home/buildmanager/.snmp/mibs/SNMPv2-SMI.my
zeroDotZero: Unknown Object Identifier (Sub-id not found: (top) -> zeroDotZero)

After some googling and guessing, I went ahead and checked the file with this online mib file validator here, which objected that
Line 34:
2   `SMI' should start with a lower case letter
1   syntax error, unexpected MODULE_IDENTITY, expecting OBJECT

I have no Idea what to make of these messages, googling them revealed nothing I could make sense of. Does this mean my file actually has errors? It's a file officially supplied by Cisco, and it's very basic - I can't imagine that would be the case.
I've made sure that there is no interfering SNMPv2-SMI anywhere else on my system, so I'm sure that this is the file netsnmp is using. I suspect there is something here that I did not understand about SNMP and these mib files in general, so please point me at the right direction or tell me where and how to look for answers. Thanks!
Contents of SNMPv2-SMI:
-- file: SNMPv2-SMI.my
-- Changes:
--      Converted to SMIC format.
-- dperkins@scruznet.com

SNMPv2-SMI DEFINITIONS ::= BEGIN

org             OBJECT IDENTIFIER ::= { iso 3 }
dod             OBJECT IDENTIFIER ::= { org 6 }
internet        OBJECT IDENTIFIER ::= { dod 1 }
directory       OBJECT IDENTIFIER ::= { internet 1 }
mgmt            OBJECT IDENTIFIER ::= { internet 2 }
mib-2           OBJECT IDENTIFIER ::= { mgmt 1 }
transmission    OBJECT IDENTIFIER ::= { mib-2 10 }
experimental    OBJECT IDENTIFIER ::= { internet 3 }
private         OBJECT IDENTIFIER ::= { internet 4 }
enterprises     OBJECT IDENTIFIER ::= { private 1 }
security        OBJECT IDENTIFIER ::= { internet 5 }
snmpV2          OBJECT IDENTIFIER ::= { internet 6 }

-- transport domains
snmpDomains     OBJECT IDENTIFIER ::= { snmpV2 1 }

-- transport proxies
snmpProxys      OBJECT IDENTIFIER ::= { snmpV2 2 }

-- module identities
snmpModules     OBJECT IDENTIFIER ::= { snmpV2 3 }

-- macros

SMI MODULE-IDENTITY
SMI OBJECT-IDENTITY
SMI OBJECT-TYPE
SMI NOTIFICATION-TYPE

-- types

SMI Counter32
SMI Counter64
SMI Gauge32
SMI Integer32
SMI IpAddress
SMI Opaque
SMI TimeTicks
SMI BITS
SMI Unsigned32

zeroDotZero    OBJECT-IDENTITY
    STATUS     current
    DESCRIPTION
            "A value used for null identifiers."
    ::= { 0 0 }

END

A: That SNMPv2-SMI file you quoted has been modified from the original/standard to use special syntax that is specific to the SMIC compiler (those "SMI" keywords like "SMI Counter32"), per the comments at the beginning:
--      Converted to SMIC format.

This is broken syntax (no longer valid SMIv1 or SMIv2) according to any other parser/compiler, hence the errors. You should only add MIBs to net-snmp that you need that are not already provided by it (as SNMPv2-SMI should be), and should use standard syntax, not compiler-specific extensions (unless they are implemented in comments).


text:
Q: Is there some how to navigate to a page and pass parameters without use the address bar in Blazor? This is present in many modern SPA libraries/frameworks...
I will supply an example using React (But it could be Angular or Vue),  you can do something like...
this.props.router.push({
  pathname: '/login-successfully',
  state: {
    userId: 'john',
    name: 'John Doe
  }
})

and then on the initialization of the "other-page" you will have:
const {state} = useLocation();
const { userId, name } = state;

and you can render things like

Welcome Back, {name}!

Such feature is very useful in many scenarios, but by reading the documentation of routing in Blazor at https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/routing?view=aspnetcore-5.0 I cannot find anything. The NavigationManager just have those parameters:
public void NavigateTo (string uri, bool forceLoad = false);

Is there some equivalent approach that I can use ? I know a workaround by creating a singleton class, store the data over there and display on the login-successfully page, but I really hope to find something better as solution.

A: Okay, my first answer got me a thumbs down, as apparently the decades-old standard of passing data in the URL was "rubbish" (actual quote) so let me explain what I actually do in this kind of case.  I'm not actually a big fan of passing data in a query string either, especially since in Blazor you rarely need to.
I wasn't joking when I said that I wouldn't navigate among pages that share a large amount of data.  I consider each page a separate site, with its own loading and saving of information to the database.  Unless I'm passing something very simple, like an ID in the URL, I would use components to switch sub-functions.
(Not tested code, but you can get the idea)
Main page:
main.razor
@if (IsDoingSomethingWithData)
{
     <MyDoingSomethingWithDataComponent ID=variable_ID Name=variable_Name State=variableState />
}
else
{
     <input @bind=variable_state />

     <input @bind=variable_ID />

     <input @bind=variable_name />

     <button @onclick="ToggleDoingSomething">Next</button>
}

@code {
     string variable_state;
     string variable_ID;
     string variable_name;
     bool IsDoingSomethingWithData;
     void ToggleDoingSomething(){
          IsDoingSomethingWithData = !IsDoingSomethingWithData;
     }
}

Component: MyDoingSomethingWithDataComponent
(i.e. the stuff that you would have navigated to, but in Blazor don't need to)

Hello, @variable_name

Your ID is: @variable_ID

I understand that you live in state: @variable_state

@code{
[Parameter]
string ID;

[Parameter]
string Name;

[Parameter]
string State;
}

If you actually make a project and do this-- use named parameters to initialize a component-- you'll see that it never gets hit, and upon inspection of the page, none of the component has been rendered, UNTIL you set IsDoingSomethingWithData = true;
Magic!


text:
Q: ODM Command Line Build For Classic Rule Projects I am using ODM 8.10 and want to automate building rule app files. The code is currently configured in the old Classic Rule Project, and we are trying to avoid migrating to Decision Services at this time. I have found build jars for Decision Services but nothing so far for Classic Rule Projects. There must be a way to do this as the rule app jar files are created in the eclipse IDE when you deploy/export a ruleApp. I am trying to find out the jar files the IDE uses and the commands it calls to execute the rule app builds.

A: Re: "There must be a way to do this"
But you will not necessarily have access to it. The ODM product developers have experience, source code, documentation, and other tools that you do not have access to.
Having said that, there is an build/deploy API that you may be able to access via ANT. I haven't used it since switching to Decision Services when that became feasible in ODM 8.7. Standard practice before that time was to automate deployments via Ant and a "headless" version of Eclipse. If the latest online docs don't describe it, you might try the older docs.
WARNING: Classic Rule Projects are a dead end! Not only will all your effort building them in a non-standard way be wasted, I believe that it will likely be more trouble than just migrating to Decision Services (which is not usually that difficult).


text:
Q: Problem installing github-cli-2.20.2-r0 on Alpine Linux v3.17 running on WSL-2 I am trying to install the github-cli-2.20.2-r0 on Alpine Linux v3.17 running on WSL-2
I have the following repositories on my system:
cat /etc/apk/repositories
http://dl-cdn.alpinelinux.org/alpine/latest-stable/main
http://dl-cdn.alpinelinux.org/alpine/latest-stable/community
http://dl-cdn.alpinelinux.org/alpine/edge/main
http://dl-cdn.alpinelinux.org/alpine/edge/community
http://dl-cdn.alpinelinux.org/alpine/edge/testing

I did an apk search for the githb cli
    apk search github
        foliate-2.6.4-r1
        github-cli-2.20.2-r0
        github-cli-zsh-completion-2.20.2-r0
        py3-pygithub-1.57-r0
        github-cli-bash-completion-2.20.2-r0
        tootle-1.0-r2
        github-cli-doc-2.20.2-r0

Then tried an install

    sudo apk add github-cli-2.20.2-r0
        ERROR: unable to select packages:
          github-cli-2.20.2-r0 (no such package):
            required by: world[github-cli-2.20.2-r0]

What am I doing wrong?

A: Removing the version worked for me:

sudo apk add github-cli


text:
Q: Coerce field to Bag datatype in Pig Say I'm loading in a bag into Pig without a schema file. I know that each tuple in the bag contains 1 field, which is also a bag, e.g.
{
  ({1, 2, 3}),
  ({3,4,5}),
  ({1,2})
}

I would like to cast each tuple's first argument into a bag. How can I do so?
data = LOAD '/path/to/data' AS (f:bytearray);
data2 = FOREACH data GENERATE (bag)f;  -- this doesn't work

A: data = LOAD '/path/to/data' AS (f:bag{(n:int)});


text:
Q: How to QComboBox Items arranged in given order, or reversely given order or a to z or z to a in PyQt5? My aim is to rearrange combo box items in

*

*Alphabetically ascending order (A to Z),

*Alphabetically Descending Order(Z to A).

*Given Order ( As per the list, no change, that is the first item is America, the Second is Russia and the Last                         One is India)

*Given Order in reverse order  (Item in reverse order, that is the First item is India, the second one is      France and the Last One is America)

Here is my code. Mouse right-click in combo box will show my option. Based on user selection, items in Qcombo Box will rearrange. How to get it?
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QPushButton, QVBoxLayout,QMenu,QDesktopWidget,QMainWindow
from PyQt5.QtCore import Qt,QPoint,pyqtSignal,QSize

class CheckableComboBox(QComboBox):

    def __init__(self):
        super().__init__()

        self.setEditable(True)
        self.lineEdit().setReadOnly(True)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showMenu)

        self.setStyleSheet("QComboBox QAbstractItemView::item {border: none;padding-left: 5px;}")
        self.lineEdit().installEventFilter(self)
        self.closeOnLineEditClick = True
        self.double_click = None

    def showMenu(self,pos):
        menu = QMenu()
        atoz_action = menu.addAction("A to Z - Ascending Order")
        ztoa_action = menu.addAction(("Z to A - Descending Order"))
        copy_action1 = menu.addSeparator()
        copy_action2 = menu.addAction(("Given Order"))
        copy_action3 = menu.addAction(("Given Order - Reverse"))

        mainwindow_geomentry = QDesktopWidget().screenGeometry()
        widget_qpoint = (self.mapToGlobal(QPoint()))
        widget_qpoint_x = widget_qpoint.x()

        xpos = mainwindow_geomentry.width() - (self.size().width()+menu.sizeHint().width())
        xx =  xpos - widget_qpoint_x

        if xx <= 0 :
            aa = 0-(menu.sizeHint().width())
        else:
            aa = self.size().width()

        action = menu.exec_(self.mapToGlobal(QPoint(aa-2,0)))

        if action == atoz_action:
            self.model().sort(0)
            self.setCurrentIndex(0)
        elif action == ztoa_action:
            print("bbbbbbbbbb")

class MyApp(QWidget):

    def __init__(self):
        super().__init__()

        mainLayout = QVBoxLayout()
        self.setLayout(mainLayout)

        self.data = ['America', 'Russia', 'China', 'Germany', 'France', 'India']

        self.combo = CheckableComboBox()
        self.combo.setMinimumSize(600,40)

        btn = QPushButton('Print Values')
        btn.clicked.connect(self.getValue)

        mainLayout.addWidget(self.combo)
        mainLayout.addWidget(btn)

        self.combo.addItems(self.data)

    def getValue(self):
        print(self.combo.currentData())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyleSheet('''QWidget {font-size: 20px;}''')
    myApp = MyApp()
    myApp.show()
    app.exit(app.exec_())

I will try to solve it in ascending order(first case)  by self. model().sort(0). Its work. But I was Struck with another three cases. I can't able to solve it.

A: QComboBox uses a Qt model for its items (the default is a QStandardItemModel), so you can use sort() to change the sorting depending on your needs.
Since you also need to reverse the original order, a possible solution is to add a custom data field (using setItemData()) that simply stores the source index.
Then it's just a matter of choosing the sortRole and order.
class CheckableComboBox(QComboBox):

    def __init__(self):
        super().__init__()

        self.setEditable(True)
        self.lineEdit().setReadOnly(True)

        self.setStyleSheet("""
            QComboBox QAbstractItemView::item {
                border: none;
                padding-left: 5px;
            }
        """)

    def contextMenuEvent(self, event):
        model = self.model()
        for i in range(model.rowCount()):
            if self.itemData(i) is None:
                self.setItemData(i, i)

        menu = QMenu()
        atoz_action = menu.addAction("A to Z - Ascending Order")
        ztoa_action = menu.addAction(("Z to A - Descending Order"))
        copy_action1 = menu.addSeparator()
        originalAction = menu.addAction(("Given Order"))
        reverseAction = menu.addAction(("Given Order - Reverse"))

        action = menu.exec_(event.globalPos())
        if action in (atoz_action, ztoa_action):
            model.setSortRole(Qt.DisplayRole)
        else:
            model.setSortRole(Qt.UserRole)

        if action in (atoz_action, originalAction):
            order = Qt.AscendingOrder
        else:
            order = Qt.DescendingOrder

        model.sort(self.modelColumn(), order)

Note that I replaced the showMenu function with a more appropriate override of customContextMenu, and I also removed the repositioning because it used an unreliable computation (and an obsolete class, QDesktopWidget) which placed the menu in odd and confusing places.


text:
Q: How to hide a linux pc from network? I installed a Linux virtual machine in my windows machine, but I don't want my network admin see the Linux VM. Is there any way to hide it?

A: That depends on how you allow your VM to access the network.
If you allow the VM to access the network through NAT it should be pretty hard to spot as it doesn't get an IP-address. (It sort of hides behind the host's network.)
Note that a competent network admin can probably find it anyway if he went out of his way to find it.

A: firewall the machine, reject icmp packets so it wont ping, and only allow inbound connections which are related and established to outbound ones. This should be good enough, more or less.
maybe also setup port knocking if you want to get in from outside.


text:
Q: Why is "Future() is Future" false? I am very confused that this is not working as I expected:
from concurrent.futures import Future

f = Future()

print(type(f))

if f is Future:
   print("Future")
else:
   print("Other")

The output is:
<class 'concurrent.futures._base.Future'>
Other

While I was expecting:
<class 'concurrent.futures._base.Future'>
Future

What is going on? Why isn't f is Future true?

A: If you take a look at the Python documentation:

6.10.3. Identity comparisons
The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. Object identity is determined using the id() function. x is not y yields the inverse truth value.

Thus, is does not check if an object is an instance of a class but if two objects have the same identity. For that you use the builtin function isinstance(instance, class):
if isinstance(f, Future):


text:
Q: Alternative to cartridge heater for 10mm deep hole? I am designing my own version of a heater block for a 3D printer hot end. I had originally intended to use a 40W cartridge heater but the shortest length available I can find is 20mm and the geometry of the block only allows for a 10mm deep hole.
The heater cartridge is to be used in conjunction with a thermistor using PID control to maintain a constant temperature (approx. 200°C). Both of these elements being encased in the same aluminium block.
Is there an alternative I could use to a heater cartridge which would fit these requirements? I am unsure if a resistor could withstand this?

A: I reckon a Scope soldering iron heater element might be a fit.
The heater element is carbon slug set into a copper stud at one end (the other end contactsthe soldering iron tip). It runs at about 4V and 25A at full power.


text:
Q: No tests to execute from MSTest I have read No tests to execute msTest
I'm trying to run a unit test (MS unit tests) from the command line. It's my first time attempting this.
My command works fine (no syntax errors), which is

mstest /testcontainer:C:\Users\me\source\repos\Test03\UnitTestProject1\bin\debug\UnitTestProject1.dll

The problem is I always get the following response in the console

Loading C:\Users\me\source\repos\Test03\UnitTestProject1\bin\debug\UnitTestProject1.dll...
  Starting execution...
  No tests to execute.

My unit test is simply
namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void AddPositive()
        {
            var bll = new ConsoleApp1.Bll();
            var result = bll.Add(2, 5);
            Assert.IsTrue(result == 7);
        }
     }

Why does it not find the test as I've followed the instructions from https://msdn.microsoft.com/en-us/library/ms182489.aspx#testcontainer?
The solution as a whole targets 4.6.1 , I'm using VS 2017 Enterprise

A: If you want to use mstest.exe, you need following reference in your project file:
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />

If you have instead (which seems to be the default for newly created test projects):
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll</HintPath>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll</HintPath>
</Reference>

you need to use vstest.console.exe
Please note that VSTest.Console.exe is optimized for performance and is used in place of MSTest.exe in Visual Studio 2012.

A: I ran into the same problem and it took me some time to figure out. The actual solution is in the comments.
My Tests are getting discorvered using vstest.console.exe:
Visual Studio Enterprise 2017:

"C:\Program Files (x86)\Microsoft Visual
  Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe"

See https://learn.microsoft.com/en-us/visualstudio/test/vstest-console-options for further info.


text:
Q: Why postman form-data return empty request when uploading file to laravel? Why postman form-data methode return empty request when uploading file to laravel ?
Hello, I trying to send an image to laravel server using postman form-data but the image does not exist in the request and the request is totally empty
this is my controller :

i'm totally blocked here !!

A: send the request as such :

And it will work

A: Problem solved, I was using PUT method then i replace it with POST and it did work perfectlly


text:
Q: mod_rewrite select everything I have a problem with URL rewriting. This is the rule
RewriteRule ^(.*)-(.*)-(.*)\.html$ file.php?name=test&a=$1&b=$2&c=$3

The rule work's fine on a link like this:
test-11-abc.html

But I have a problem if the third variable have a dash like:
test-11-ab-c.html

The rewrite doesn't work.

A: Try this:
RewriteRule ^(.*?)-(.*?)-(.*)\.html$ file.php?name=test&a=$1&b=$2&c=$3

You need to make the first 2 matches non-greedy, because they're gobbling up the first -.


text:
Q: arraylist seems to be empty out side the function Hi i have an array list which is defined in the beginning of the class and i try too put objects inside it so that i can use it for a custom arrayAdapter for a listview but when i want to use it seems to be empty outside the response Listener i tested it with two Toasts forst one runs with no problem second one throws IndexOutOfBoundsException here's my code i have put comments beside those two Toasts they are in getUserGamesInfo function (sry for the mess that has happened to the code when i pasted it here that happened):
public class account_games_info extends Fragment {

HashMap<String, String> info = new HashMap<>();

String Playerscores, Rivalscore;
String[] array = null;
ListView listView;
ArrayList<gameHistory_object> scoreList=new ArrayList<gameHistory_object>;//*************
gameHistory_object gameHistory_object;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    get_user_games_ids();//a functio that calls getUserGamesInfo but i didnt bring it here

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View games_info = inflater.inflate(R.layout.fragment_account_games_info, container, false);
    listView = (ListView) games_info.findViewById(R.id.listView);

    return games_info;
}

private void getUserGamesInfo(String gameID) {

    final String MY_PREFS_NAME = "username and password";
    SharedPreferences prefs = getActivity().getSharedPreferences(MY_PREFS_NAME,
            MODE_PRIVATE);
    final String id = prefs.getString("userID", null);

    info.put("action", "sendGameInformation");
    info.put("userID", id);
    info.put("gameID", gameID);

    JSONObject jsonObject = new JSONObject(info);
    final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
            url, jsonObject, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {

                gameHistory_object = new gameHistory_object();
                if (id.equals(response.getString("playerOneID"))) {

                    Playerscores = response.getString("playerOneTotalScore");
                    Rivalscore = response.getString("playerTwoTotalScore");

                    gameHistory_object.setRivalUsername(response.getString("playerTwoUsername"));
                    gameHistory_object.setPlayerScore(Playerscores);
                    gameHistory_object.setRivalScore(Rivalscore);

                } else {

                    Playerscores = response.getString("playerTwoTotalScore");
                    Rivalscore = response.getString("playerTwoTotalScore");

                    gameHistory_object.setRivalUsername(response.getString("playerOneUsername"));
                    gameHistory_object.setPlayerScore(Playerscores);
                    gameHistory_object.setRivalScore(Rivalscore);

                }
                   scoreList.add(gameHistory_object);
                 //first toast which runs with no problem

                 Toast.makeText(getActivity(),"inside $$$"+scoreList.get(0).getRivalUsername(),Toast.LENGTH_SHORT).show();

            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (Playerscores.equals("")) {
                playerScore_view.setText("");
            } else {
                playerScore_view.setText(Playerscores);
                rivalScore_view.setText(Rivalscore);
            }

        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

     //second toast with outofboundexecption

    Toast.makeText(getActivity(),"outside
      $$$"+scoreList.get(0).getRivalUsername(),Toast.LENGTH_SHORT).show();

    AppController.getInstance().addToRequestQueue(jsonObjectRequest);

}

A: Your arraylist is not initialized any where in your code hence the IndexOutOfBoundsException.
Do this in your variable declaration:
ArrayList<gameHistory_object> scoreList = new ArrayList <>();

A: *

*You never initialize your scoreList :
ArrayList<gameHistory_object> scoreList;

should be
ArrayList<gameHistory_object> scoreList = new ArrayList();

*You access the 0th item of your scoreList before it's been put there. The JsonObjectRequest you start is asynchronous. Your code will start the asynchronous request, then continue to the part where you try to make your toast, but the request has not yet ended (the onResponse part), thus your list is empty.


text:
Q: Django: How to allow a Suspicious File Operation / copy a file I want to do a SuspiciousFileOperation which django disallows by default.
I am writing a command (to run via manage.py importfiles) to import a given directory structure on the real file system in my self written filestorage in Django.
I think, this is my relevant code:
def _handle_directory(self, directory_path, directory):
    for root, subFolders, files in os.walk(directory_path):
        for filename in files:
            self.cnt_files += 1
            new_file = File(directory=directory, filename=filename, file=os.path.join(root, filename),
                 uploader=self.uploader)
            new_file.save()

The backtrace is:
Traceback (most recent call last):
  File ".\manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 399, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 242, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 285, in execute
    output = self.handle(*args, **options)
  File "D:\Development\github\Palco\engine\filestorage\management\commands\importfiles.py", line 53, in handle
    self._handle_directory(args[0], root)
  File "D:\Development\github\Palco\engine\filestorage\management\commands\importfiles.py", line 63, in _handle_directory
    new_file.save()
  File "D:\Development\github\Palco\engine\filestorage\models.py", line 157, in save
    self.sha512 = hashlib.sha512(self.file.read()).hexdigest()
  File "C:\Python27\lib\site-packages\django\core\files\utils.py", line 16, in <lambda>
    read = property(lambda self: self.file.read)
  File "C:\Python27\lib\site-packages\django\db\models\fields\files.py", line 46, in _get_file
    self._file = self.storage.open(self.name, 'rb')
  File "C:\Python27\lib\site-packages\django\core\files\storage.py", line 33, in open
    return self._open(name, mode)
  File "C:\Python27\lib\site-packages\django\core\files\storage.py", line 160, in _open
    return File(open(self.path(name), mode))
  File "C:\Python27\lib\site-packages\django\core\files\storage.py", line 261, in path
    raise SuspiciousFileOperation("Attempted access to '%s' denied." % name)
django.core.exceptions.SuspiciousFileOperation: Attempted access to 'D:\Temp\importme\readme.html' denied.

The full model can be found at GitHub. The full command is currently on gist.github.com available.
If you do not want to check the model: the attribute file of my File class is a FileField.
I assume, this problem happens, because I am just "linking" to the file found. But I need to copy it, huh? How can I copy the file into the file?

A: In Django, SuspiciousFileOperation can be avoid by read the file from external dir and make a tmp file within the project media then save in the appropriate file filed as below
import tempfile

file_name="file_name.pdf"
EXT_FILE_PATH = "/home/somepath/"
file_path = EXT_FILE_PATH + file_name
if exists(file_path):
    #create a named temporary file within the project base , here in media

    lf = tempfile.NamedTemporaryFile(dir='media')
    f = open(file_path, 'rb')
    lf.write(f.read())
    #doc object with file FileField.

    doc.file.save(file_name, File(lf), save=True)
    lf.close()

A: I haven't faced similar problem but related issue. I have recently upgraded Django 1.8 to 1.11.
Now I am getting the following error if try to save a file in a model having FileField field:

SuspiciousFileOperation at /api/send_report/
  The joined path (/vagrant/tmp/test_file.pdf) is located outside of the base path component (/vagrant/media)

My model where I want to save the file:
class Report(BaseModel):
    file = models.FileField(max_length=200, upload_to=os.path.join(settings.REPORTS_URL, '%Y/week_%W/'))
    type = models.CharField(max_length=20, verbose_name='Type', blank=False, default='', db_index=True)

I am trying following codes to save the file from tmp folder which is not located in MEDIA_ROOT:
from django.core.files import File

filepath = "/vagrant/tmp/test_file.pdf"
file = File(open(filepath, "rb"))
report_type = "My_report_type"
report = Report.objects.create(
    file=file,
    type=report_type,
)

What I have done to solve the issue:
import os
from django.core.files import File

filepath = "/vagrant/tmp/test_file.pdf"
file = File(open(filepath, "rb"))
file_name = os.path.basename(file.name)
report_type = "My_report_type"
report = Report.objects.create(
    type=report_type,
)
report.file.save(file_name, file, save=True)

Hope it will help someone.

A: Analyzing this part of stacktrace:
File "C:\Python27\lib\site-packages\django\core\files\storage.py", line 261, in path
    raise SuspiciousFileOperation("Attempted access to '%s' denied." % name)

leads to the standard Django FileSystemStorage. It expects files to be within your MEDIA_ROOT. Your files can be anywhere in the file system, therefore this problem occurs.
You should pass file-like object instead of a path to your File model. The easiest way to achieve that would be to use Django File class, which is a wrapper around python file-like objects. See File object documentation for more details.
Update:
Ok, I am suggesting here a route taken from the docs:
from django.core.files import File as FileWrapper

def _handle_directory(self, directory_path, directory):
    for root, subFolders, files in os.walk(directory_path):
        for filename in files:
            self.cnt_files += 1
            new_file = File(
                 directory=directory, filename=filename,
                 file=os.path.join(root, filename),
                 uploader=self.uploader)
            with open(os.path.join(root, filename), 'r') as f:
                file_wrapper = FileWrapper(f)
                new_file = File(
                    directory=directory, filename=filename,
                    file=file_wrapper,
                    uploader=self.uploader)
                new_file.save()

If it works it should copy the file to the location provided by your secure_storage callable.

A: Check if there is slash before your filepath
file_item = models.FileField(upload_to=content_file_name)

def content_file_name(username, filename):
    return '/'.join(['content', username, filename])

Note here "content"  not "/content". That was the problem for me.


text:
Q: How does netTiers pass data? I have generated code using netTiers. Everything works fine, but I want to do some modifications.
Eg: I have a column[dataType varchar] (in a table) to store imageURL. For the same netTiers generates a TextBox. I want to replace the TextBox with a FileUpload, save the image in a folder and insert the URL into the DB.
The problem I am facing here is that I have no clue how netTiers is passing the data. Where is the insert query? They have nothing in the button click also :O . I tried searching the button's ID in the entire solution, but there was not a single occurrence .
Can you guys please point me to a good article or any useful resource? I am trying to get a grip at it but it seems it's gonna take some time.

A: Insert query is in Data layer in Procedure.xml
Data is passing between layers. First read documentation (no matter it is not complete) from nettiers web page. You have to understand how business, data and service layers works, and than you will understand presentation layer.
If you don't like how presentation layer is generated, you can generate it yourself, and use only business, data and service layars.


text:
Q: Number of roots of a quadratic equation modulo 325 Any Help solving this question ?

a) Find ONE solution $\overline x\in\Bbb Z/325\Bbb Z$ such that $x^2\equiv-1\pmod{325}$.  (Hint: CRT and lifting.)
b) How many solutions $\overline x$ to the above equation are there, and why?

A: $325=5^2\cdot 13$ so let's solve $x^2\equiv -1\pmod{25}$, $x^2\equiv -1\pmod{13}$.
Case $1$: $\mod{25}$
If $x^2\equiv -1\pmod{25}$, then $x^2\equiv -1\pmod 5$ so $x\equiv\pm2\pmod 5$
$$(5k+2)^2=25k^2+20k+4\equiv 20k+4\equiv-1\pmod{25}\implies 4k\equiv -1\pmod 5\\\implies k\equiv 1\pmod 5$$
$$(5k-2)^2=25k^2-20k+4\equiv -20k+4\equiv-1\pmod{25}\implies 4k\equiv 1\pmod 5\\\implies k\equiv 4\pmod 5$$
So we have $x^2\equiv-1\pmod{25}\implies x\equiv\pm7\pmod{25}$
Case $2$: $\mod 13$
We see upon inspection that $x^2\equiv -1\pmod{13}\implies x=\pm 5$
See if you can use CRT to find all solutions to $x^2\equiv -1\pmod{325}$

A: We can prove by using  Discrete Logarithm and Linear Congruence Theorem that $x^2\equiv a\pmod m$ has zero or two solutions if $m$ has  a primitive root.
Now, $\displaystyle  x^2\equiv-1\pmod{325}\equiv-1\pmod{25}$
$\displaystyle x^2\equiv-1\equiv49\pmod{25}\equiv7^2\implies x\equiv\pm7\pmod{25}\ \ \ \  (1)$
Again, $x^2\equiv-1\pmod{325}\equiv-1\pmod{13}$
$\displaystyle x^2\equiv-1\pmod{13}\equiv25\equiv5^2\implies x\equiv\pm5\pmod{13}\ \ \ \  (2)$
Now apply CRT on $(1),(2)$ to find four in-congruent solutions


text:
Q: change surrounding tags for a given text by RegExp I try to create function that find text in my htmlString (it minify) and then change the tag that wrap the text to h2
 var htmlString = `

title

Lorem ipsum dolor quas!

Lorem ipsum dolor

hi

hi 123

hi
Lorem ipsum dolor, sit.
`
const changeTagByText = (html) => {
let text = "hi"

// replace the tags

return html
}

console.log(changeTagByText(html))

output excepted:

title

Lorem ipsum dolor quas!

Lorem ipsum dolor

hi

hi 123

hi
Lorem ipsum dolor, sit.

A:

var htmlString = `
title

Lorem ipsum dolor quas!

Lorem ipsum dolor

hi

hi 123

hi
hiLorem ipsum dolor, sit.
`
const changeTagByText = (html, word) => {
  var re = new RegExp('(<[a-zA-Z]+>)'+ word +'(</[a-zA-Z]+>)', 'g')
  return html.replace(re, '
'+ word +'
');
}
console.log(changeTagByText(htmlString, 'hi'))

You can do it more dynamically by expand changeTagByText to take two params one for the html and the other one for the text you want to replace.
RegExp help to create dynamic regex pattern.


text:
Q: Can I use a design attribute's value in another design attribute datasource? Let's say I have the following design attribute file for a Lightning Component:
<design:component>
<design:attribute
        name="selectedPage"
        label="Selected page"
        description="Use if you want only one specific page to be displayed"
/>
<design:attribute
        name="recordId"
        label="Record"
        datasource="apex://MyItemsPickList"
        description="Select an item"
/>

I want to populate the selectedPage datasource by fetching values based off of what is selected in my recordId field. Is that possible?
Let's say the recordId will fetch a list of books. I select one of those books. Now I want my selectedPage to use that recordId to fetch the book record and populate itself with all the pages of the book (let's I assume I only have about 10 pages so it doesn't sound ridiculous).

A: No, this is not possible right now. Each option has to be calculated independent of other selected attributes.


text:
Q: what initializations i need to do in .lcf(linker file) and other files before generation RAM.bin image file for MPC5604E controller I am trying to load the RAM.bin image on SRAM of MPC5604E controller through serial boot (using autobaud mode for LINFLEX0). I am using an sample LED toggle program to generate  RAM.bin image file and tried to load through serial boot, it is loaded successfully and LED toggle working fine(when watchdog is enabled),but if we disable the watchdog and then load and execute it,LED toggle is not working. So I assume there may be some issue  related to initialization in .lcf(linker file) and some other files before generating the RAM.bin file through code warrior for serial booting.
Can anybody help me with these initializations because i don't know what to do ? So that my RAM.bin image file can execute successfully.
MPC5604E.lcf :::
       /* lcf file for MPC5604E processors                                         */
       /*                                                                          */
       /*              512KB Flash, 96KB SRAM                                      */

      MEMORY
      {
            resetvector:           org = 0x00000000,   len = 0x00000008
            init:                  org = 0x00000020,   len = 0x00000FE0
            exception_handlers:    org = 0x00001000,   len = 0x00001000
            internal_flash:        org = 0x00002000,   len = 0x000FE000

            internal_ram:          org = 0x40000000,   len = 0x00016000
            heap  :                org = 0x40016000,   len = 0x00001000
            stack :                org = 0x40017000,   len = 0x00001000

         }

         /* This will ensure the rchw and reset vector are not stripped by the linker*/
         FORCEACTIVE { "bam_rchw" "bam_resetvector" }

        SECTIONS
        {
          .__bam_bootarea LOAD (0x00000000): {} > resetvector

       GROUP : {
        .init LOAD (0x00000020) : {}
       .init_vle (VLECODE) LOAD (_e_init) : {
       *(.init)
       *(.init_vle)
       }
     } > init

     GROUP : {
     .ivor_branch_table (VLECODE) LOAD (0x00001000) : {}
      .__exception_handlers  (VLECODE) LOAD (_e_ivor_branch_table) : {}
      } > exception_handlers

     GROUP  : {
     .text : {}
     .text_vle (VLECODE) ALIGN(0x08): {
        *(.text)
      *(.text_vle)
     }
      .rodata (CONST) : {
       *(.rdata)
       *(.rodata)
      }
      .ctors : {}
      .dtors : {}
      extab : {}
      extabindex : {}
      } > internal_flash

      GROUP : {
       .__uninitialized_intc_handlertable ALIGN(2048) : {}
       .data   : {}
       .sdata  : {}
       .sbss   : {}
       .sdata2 : {}
       .sbss2  : {}
       .bss    : {}
       } > internal_ram
      }

      /* Freescale CodeWarrior compiler address designations */

     _stack_addr = ADDR(stack)+SIZEOF(stack);
     _stack_end  = ADDR(stack);
     _heap_addr  = ADDR(heap);
     _heap_end   = ADDR(heap)+SIZEOF(heap);

    /* Exceptions Handlers Location (used in Exceptions.c IVPR initialization)*/

    EXCEPTION_HANDLERS    = ADDR(exception_handlers);

   /* L2 SRAM Location (used for L2 SRAM initialization) */

   L2SRAM_LOCATION = 0x40000000;


text:
Q: How to Limit the DOM manipulation in jQuery - appending elements I am following the "best practices" concerning the DOM manipulation topic. I am having a problem though. Before, my code was:
for(var i=0;i<size;++i){
    var $li = $('
',{some propertie..}).data(some values);
    $ul.append($li);
}

After reading a bit of performance tips, I concluded that I need to replace this into:
var str_html = '';
for(var i=0;i<size;++i){
    var li  = '
...
';
    str_html += li;
}
$ul.append(str_html);

My question is, how can I add the data parameters in this second approach, the same way I was doing in the first one (for each li element)?
Thanks!

A: Since jQuery 1.4.3 you can set data attributeshave a read. This would look like:
var str_html = '';
for(var i=0;i<size;++i){
   var li  = '
...
';
   str_html += li;
}
$ul.append(str_html);

jQuery will automatically pull all data- attributes into the elements data-expando. So you could access the above example with:
$('li').data('somevalue') // === foobar

You actually can put in any type of data into such an attribute, even JSON decoded object-string literals (which automatically get parsed by jQuery):
'
...
';

is translated into
$('li').data('somevalue').foo // === Barrrr

A: I would suggest you look into the jquery template API.

A: Have a look at DocumentFragment (the blog post is written by Resig himself, so the template API mentioned will most likely use DocumentFragment).
It is the best way to append DOM Elements without using innerHTML. Although innerHTML will almost always be the fastest method.
If $ul is an already existing Element in the DOM Tree, you might speed things up by removing it from the tree, adding LI elements to it, and re-append it. This will however not guarantee better performance: using a profiling tool is the only way to measure the impact.


text:
Q: LS7366R with multiple level-translated signals For one of our projects, we are using two LS7366R ICs for interfacing with our two encoders.
Our encoders operate at 5 V and we are supplying 5 V VCC to the LS7366 chips as well. However, our control unit is a Raspberry Pi running at 3.3 V. So, what I wanted to know: is it okay if I just use the level translators and connect it to the Pi ?
Have a look at the schematic below. The idea is that both counter ICs U9 and U15 will be connected to the same MISO, MOSI and SCK signals (which are subsequently connected to level translators). The slave select signals are different though.
Encoder - LS7366 Connections:

LS7366 - Level Translators:

Can anyone confirm that the MOSI/MISO lines will not behave in any unexpected way? Is there a better way of achieving such a functionality in our design?

A:
Can anyone confirm that the MOSI/MISO lines will not behave in any
unexpected way \$\color{red}{\text{OR}}\$ is there a better way of achieving such a
functionality in our design ?

This is the \$\color{red}{\text{OR}}\$ answer...
It seems to me like you are going to a helluva lot of trouble using voltage level translators (i.e. the SN74LVC2T45D) when the LS7366R (quadrature counter devices) can work at the same logic level as your MCU (RaPi). Yes, you need to run your encoders at 5 volts but their outputs (index, A and B) can be dropped to 3.3 volt logic levels using simple resistor dividers. This then means you don't need four TI chips: -

Take the simple route.


text:
Q: Usage analytics limitations for my azure server using Application Insights I've built a web API that receives GET requests and processes an image based on specifications passed in like image Url, text to be drawn over it, quality, size, etc.
I have a few questions about using Application Insights, which seems to be built right into my Visual Studio IDE and also Azure.. This question was sparked after viewing this source in my research for the right form of usage analytics:
https://learn.microsoft.com/en-us/azure/application-insights/app-insights-overview
Questions:
1) Does it require any new code to be used?
2) Can it track individual parameters (image, size, etc.) so we can see, for example, which images are used most often, what sizes images are requested at, etc.?
3) Can we also use it to log custom events that don't neatly map to separate methods or api endpoints? (e.g. log each time we draw a text field, measure a string, load a font, or pull an image from blob storage)
I would really appreciate an answer that could cover my more broad concerns like these about choosing a usage analytics tool. Any suggestions as to what other tools Azure has for these sorts of requirements would also be great.
Thanks for taking the time to read!

A: Regarding to the first question the answer is: It depends. How and where is you web api hosted. In IIS? On Azure? Using self hosting?
According to the documentation found here https://learn.microsoft.com/en-us/azure/application-insights/app-insights-monitor-performance-live-website-now these are your options:

You can instrument a live web app with Azure Application Insights, without having to modify or redeploy your code. In your apps are hosted by an on-premises IIS server, you install Status Monitor; or if they're Azure web apps or run in an Azure VM, you can install the Application Insights extension. (There are also separate articles about instrumenting live J2EE web apps and Azure Cloud Services.)

But when it comes to your other questions, you will need to add some code by using the SDK. You can then track custom traces (log messages for example), custom metrics (like counts of image sizes). See https://learn.microsoft.com/en-us/azure/application-insights/app-insights-api-custom-events-metrics:

The Azure Application Insights core telemetry API lets you send custom events and metrics, and your own versions of standard telemetry. This API is the same API that is used by the standard Application Insights data collectors.

Using this SDK you can add custom properties to any telemetry item you collect, next to the properties provided by the event definition.
Now, not only will AI present you with a dashboard to get a quick glance of your app status, it also has a very powerful query tool you can use: https://learn.microsoft.com/en-us/azure/application-insights/app-insights-analytics
So yes, I would say that everything you describe can be done with AI. Since you can expirement with it for free I would say give it a go since getting it up and running is quite easy.


text:
Q: What happens to fourier transform of the sampled output of pure sinusoidal input of 26kHz if sampled with 44.1kHz sample frequency? Because pure sinusoidal signal only contains impulses, I was wondering what happens to the fourier transform of the sample output from the sinusoidal input of $26$kHz if the sampling is done with sample frequency of $44.1$kHz.

A: Because the sampling rate is less than two samples per cycle, the input will be aliased down to $26-44.1=-18.1$ kHz.  If the wave is a sine wave, the minus sign just inverts the signal.   If $t$ is a multiple of $1/(44.1$ kHz), $\sin (2\pi t 26$ kHz$)=\sin (-2\pi t 18.1$ kHz).  If you have a large duration, you will see (almost all the) energy in frequencies near to $-18.1$ kHz.  If you don't have an integral number of cycles, the discontinuity between the start and end of the interval will make other artifacts.


text:
Q: Probability of a character string of N letters having neighbouring identical characters? We try to send a message in a very noisy environment. The messages are coded with a four-letter alphabet. By convention, only the messages without lonely letters are considered to be meaningful. A letter is lonely if the next and previous letters are different (the first letter is lonely if the next is different and the last letter is lonely if the previous is different). At least how long does the message have to be if we want to have the chance of having a meaningful message to be less then $$10^{-10}$$
because of the noise? The noise changes the letters to other letters in the alphabet. Every letter appears independently with an equal chance.
My thoughts: The phrasing of the problem is a bit messy but here's how I understood it so far:
We make random character strings out of a four-letter alphabet. Every letter appears independently with an equal chance. The chance of having at least two identical letters next to each other in a string of lenght N is p(N). We are looking for N given that $$1-p(N)\leq 10^{-10}$$
So the key is to find p(N). Can you help me a bit with that?


text:
Q: How to change mesh uvs in maya script? I have a rigged model in maya and this model uses 2 materials, as well as 2 uv sets. Because materials have just different textures I merged textures into one and also wanted to make those 2 materials into one. The problem is that I have 2 uv sets(1 set is using uvs with textures positions with values 0-1 and secondary too but from other texture).
That what I want to do: multiplicate uv.x from 1st uv set by 0.5, and for second uv set I wanted to change: uv.x * 0.5 + 0.5. So I'll be able to use 1 atlas made from 2 textures and use only 1 material. How can I do this? Can you tell me on which functions in Maya-python should I look at? I've tried to find something n google but havent seen any solution.

A: You're looking for the cmds.polyEditUV command to manipulate the UVs.  The q=True flag lets you ask for a value and the e=True flag lets you set one. You'll need to explicitly tell the command which uvSet to work with if you have more than one.


text:
Q: Google App Engine, custom domain and SSL error I'm trying to setup Google App Engine with custom domain and SSL.
I've added the certificates to Google Apps and added the custom domains to Google App Engine.
I can successfully access http://domain.com and https://domain-com.appspot.com but when I try to access https://www.domain.com I got the following error: This webpage is not available
The domain is lonardiDOTorg
Any suggestions?

A: After some research, my findings show that this isn't supported for the moment being.
Issue 10802 on the Google App Engine issue tracker seems to confirm that it isn't yep available at the moment.
This stackoverflow post seems to contain the different workarounds that other users have used.
I hope this helps.

It is very challenging to help with this kind of issue without being able to inspect the domain and app itself.
Are there any privacy concerns in sharing the domain name so that we can see if the page is being returned by Google or by your DNS provider? It may be possible that the DNS records aren't set correctly.
Keep in mind that as this configuration is done on the Google Apps side, the Apps team may be able to assist if you have a Apps for Business account. This could help get assistance without sharing any information.
Apps Help Center: https://support.google.com/a/answer/2644334
Apps Contact Page: https://support.google.com/a/answer/2644334#contact=1


text:
Q: Purpose of ARM parallel instructions ASX and SAX? Can someone explain when it's beneficial to use the parallel add/subtract ARM instructions ASX and/or SAX? In what situation/algorithm would one need to exhange the halfwords, then add AND subtract the upper/lower halfwords? Below is the explanation of each:

ASX

*

*Exchange halfwords of Rm, then Add top halfwords and Subtract bottom halfwords.

SAX

*

*Exchange halfwords of Rm, then Subtract top halfwords and Add bottom halfwords.

A: Like Russ Schultz said in a comment it would be useful audio encoded with L+R and L-R channels.  It would be used something like:
ldr r1, [r0]      ; R1 = (L-R):(L+R)
shasx r1, r1, r1  ; R1 = ((L-R)+(L+R))/2:((L+R)-(L-R))/2
                  ;    = (2L/2):(2R/2)
                  ;    = L:R
ror r1, r1, #16   ; R1 = R:L
str r1, [r0]

The swapping of the third operand's top and bottom halfwords is necessary so the two different components can be added/subtracted with each other. Without the exchange you'd get ((L-R)+(L-R))/2:((L+R)-(L+R))/2 = (2(L-R)/2):(0/2) = (L-R):0.


text:
Q: Google Chrome does not display the cover page when loading a carousel video I wrote? I wrote a static website that has a video carousel function and uses the poster attribute, but the cover will not be displayed when Google Chrome loads, and the loading is very slow, but the cover will flash when it is refreshed. Will not be displayed. However, this problem does not occur in Firefox, and the loading speed is also OK. Ask everyone what is going on? ?

$(function(){
var click=0;
var right=0;      //解决第一次右边点击没反应
$('.video>div:last-child').click(function(){    //当点击左边按钮
for(var i=0; i<5; i++){
document.getElementsByTagName('video')[i].pause();}
click+=1;
if(click>=6)click=1;
right=1;
$('.video li:nth-of-type('+(((click+0)<=5) ? (click+0) : (click+0-5))+')').attr('class','video5');
$('.video li:nth-of-type('+(((click+1)<=5) ? (click+1) : (click+1-5))+')').attr('class','video1');
$('.video li:nth-of-type('+(((click+2)<=5) ? (click+2) : (click+2-5))+')').attr('class','video2');
$('.video li:nth-of-type('+(((click+3)<=5) ? (click+3) : (click+3-5))+')').attr('class','video3');
$('.video li:nth-of-type('+(((click+4)<=5) ? (click+4) : (click+4-5))+')').attr('class','video4');
})
$('.video>div:first-child').click(function(){  //当点击右边按钮
for(var i=0; i<5; i++){
document.getElementsByTagName('video')[i].pause();}
click-=1;
if(click<=0)click=5;
if(!right)click=4;  //解决第一次右边点击没反应
right=1;
$('.video li:nth-of-type('+(((click+0)<=5) ? (click+0) : (click+0-5))+')').attr('class','video5');
$('.video li:nth-of-type('+(((click+1)<=5) ? (click+1) : (click+1-5))+')').attr('class','video1');
$('.video li:nth-of-type('+(((click+2)<=5) ? (click+2) : (click+2-5))+')').attr('class','video2');
$('.video li:nth-of-type('+(((click+3)<=5) ? (click+3) : (click+3-5))+')').attr('class','video3');
$('.video li:nth-of-type('+(((click+4)<=5) ? (click+4) : (click+4-5))+')').attr('class','video4');
})
})
//播放完后

//控制条
function mouseOver1() {
  var video=document.getElementById("v001");
  video.controls=true;
}
function mouseOut1() {
  var video=document.getElementById("v001");
  video.controls=false;
}
function mouseOver2() {
  var video=document.getElementById("v002");
  video.controls=true;
}
function mouseOut2() {
  var video=document.getElementById("v002");
  video.controls=false;
}
function mouseOver3() {
  var video=document.getElementById("v003");
  video.controls=true;
}
function mouseOut3() {
  var video=document.getElementById("v003");
  video.controls=false;
}
function mouseOver4() {
  var video=document.getElementById("v004");
  video.controls=true;
}
function mouseOut4() {
  var video=document.getElementById("v004");
  video.controls=false;
}
function mouseOver5() {
  var video=document.getElementById("v005");
  video.controls=true;
}
function mouseOut5() {
  var video=document.getElementById("v005");
  video.controls=false;
}
.Lunbo-video{
    /* background-color:#dc2626; */
    padding-top:0px;
    padding-bottom:50px;
}
.Lunbo-video .Lunbo-video-title{
    margin:20px auto 50px;
}

.Lunbo-video .Lunbo-video-title .Lunbo-video-h1{
    font-size:30px;
    color:#ef7700;
    height:50px;
    line-height:50px;
}
.Lunbo-video .Lunbo-video-title .Lunbo-video-h3{
    font-size:30px;
    color:#ef7700;
    text-align: center;
}
.Lunbo-video .Lunbo-video-cont{
    margin-bottom:50px;
    height: 100%;
}
.Lunbo-video li{
    list-style: none;
}
.video{
    width:80%;
    margin:0 auto;
    overflow: hidden;
    zoom:1;
    border-bottom: 1px solid #e6e6e6;
     background: #ffffff;
}
.video>div{
    float: left;
    height: 509px;
}
.video>div:first-child {
    width: 5%;
    display:flex;
    align-items:center;
    justify-content:center;
    /* background: url('image\left.png') center center/cover no-repeat; */
}
.Lunbobutton{
    width: 100%;
    height: auto;
}
.video>div:last-child {
    width: 5%;
    display:flex;
    align-items:center;
    justify-content:center;
    /* background: rgb(240, 13, 114); */
    /* background: url('image\right.png') center center no-repeat; */
}
.video>div:nth-of-type(2){
    width: 90%;
}
.video ul{
    position: relative;
}
.video li{
    transition: all .6s;
    position: absolute;
    background: url(../images/video-bg.png) center center no-repeat;
    background-size: 100% 100%;}
/*.video li>div{padding: 1% 1% 4%;}*/
.video li video{
    width:100%;
    height:100%;
}
.video li h3{
    text-align: center;
    margin-top: 2px;
    color: #1766d7;
}

.video1{
    width:18%;
    height: auto;
    /* top: 143px; */
    left: 0;
    z-index: 1;
    }/*创建5个播放框初始位置*/
.video2{
    width: 37%;
    height: auto;
    /* top: 86px; */
    left: 8%;
    z-index: 2;
}
.video3{
    width: 64%;
    height: auto;
    /* top: 0px; */
    left: 17%;
    z-index: 3;
}
.video4{
    width: 37%;
    height: auto;
    /* top: 86px; */
    left: 54%;
    z-index: 2;
}
.video5{
    width:18%;
    height: auto;
    /* top: 143px; */
    left: 82%;
    z-index: 1;}

急救小视频

<video id="v001" onmouseover="mouseOver1()" onmouseout="mouseOut1()" src="video/zhixi.mp4" preload="auto" poster="images/t1zhixi.png"></video>

<video id="v002" onmouseover="mouseOver2()" onmouseout="mouseOut2()" src="video/yundao.mp4" preload="auto" poster="images/t2yundao.jpg"></video>

<video id="v003" onmouseover="mouseOver3()" onmouseout="mouseOut3()" src="video/yundao.mp4" preload="auto" poster="images/t3yundao.png"></video>

<video id="v004" onmouseover="mouseOver4()" onmouseout="mouseOut4()" src="video/zhixi.mp4" preload="auto" poster="images/t4.png"></video>

<video id="v005" onmouseover="mouseOver5()" onmouseout="mouseOut5()" src="video/zhixi.mp4" preload="auto" poster="images/t1zhixi.png"></video>


text:
Q: Update Label when 2 SKSpriteNodes collide I want to add 1 point to the topLbl whenever the ball collides with the main. How would I do that? Thanks!
import SpriteKit
import GameplayKit

class GameScene: SKScene, SKPhysicsContactDelegate {
    var ball = SKSpriteNode()
    var main = SKSpriteNode()
    var topLbl = SKLabelNode()
    var score = [Int]()

    override func didMove(to view: SKView) {
        startGame()
        self.physicsWorld.contactDelegate = self
        topLbl = self.childNode(withName: "topLabel") as! SKLabelNode
        ball = self.childNode(withName: "ball") as! SKSpriteNode
        main = self.childNode(withName: "main") as! SKSpriteNode
        ball.physicsBody?.applyImpulse(CGVector(dx: 8, dy: 8))
        let border = SKPhysicsBody(edgeLoopFrom: self.frame)
        border.friction = 0
        border.restitution = 1
        self.physicsBody = border
    }

    func startGame() {
        score = [0]
        topLbl.text = "\(score[0])"
    }

    func addScore(byTouch : SKSpriteNode){
        if byTouch == main {
            score[0] += 1
        }
        print(score)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in: self)

            main.run(SKAction.moveTo(x: location.x, duration: 0))
            main.run(SKAction.moveTo(y: location.y, duration: 0))
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        main.run(SKAction.moveBy(x: 4444, y: 4444, duration: 0))
    }

    override func update(_ currentTime: TimeInterval) {
        // Called before each frame is rendered
    }

    func didBegin(contact: SKPhysicsContact) {
        if (contact.bodyA.categoryBitMask == 1 && contact.bodyB.categoryBitMask == 2) {
            if ball == contact.bodyA.node as! SKSpriteNode  {
                    score[0] += 1
            }
        } else if (contact.bodyA.categoryBitMask == 2 && contact.bodyB.categoryBitMask == 1) {
            if ball == contact.bodyB.node as! SKSpriteNode {
                score[0] += 1
            }
        }
    }
}


text:
Q: Unable to import test results to jira via rest api i'm using the following curl command to import the output.xml file into jira test execution key and receiving error as below. I'm sure the test execution key is existing in jira and the project id is also correct. Any pointers?
curl -H "Content-Type: multipart/form-data" -u userid:pass -F "file=@output.xml" "https://server/rest/raven/latest/import/execution/robot?projectKey=PROJKEY+and+testExecKey=TESTEXNKEY" -o error.txt

The error i receive is as below
The User "userid" does not have permission to create issues

Why does it try to create new issue while the issue already exists? And why does it say the user doesn't have access when the access is there?

A: You probably mean Xray add-on and you probably use the same request per their documentation. The problem seems to be with your parameter syntax. It should be .../robot/?projectKey=PROJKEY&testExecKey=TESTEXNKEY (i.e. & instead of +and+).
Plus I would explicitly specify it's a POST request: curl -X POST ....
But their error message is not clear, anyway. I don't have Xray available right now, but if you keep having troubles, I would recommend checking with their support.


text:
Q: Move Workspaces Overview to Top in GNOME (like MacOS) I'm wondering if there's a way to move the Workspaces Overview (GNOME) to the top, like in MacOS. If you don't know what I mean by "workspaces overview," I'm talking about when you go into Activities Overview and you can see the workspaces/desktops on the right, like in the following screenshot:

All I want to do is to move that to the top instead of the right.
Maybe something to edit in the GNOME Theme CSS file? A GNOME Extension? Whatever working solution you have I will accept.
Thanks in advance!

*

*Ubuntu 20.04

*GNOME Version: 3.36.8


text:
Q: Meaning of "...Manny, who liked a bit now and again and again." Context: Female student Manny locked the door & say this words to her professor before she kissed him.

Student: I'm not a student anymore.
Professor: I do not think I want to know what that means.
Student: There once was a girl named Manny Who liked a bit now and
  again, Not now and again, But now and again And again. Cute?

A: "A bit" = sex (as already in the comments)
"Not now and again" - "now and again" normally refers to occasionally, which is "Not" the meaning here
"But now" - now as in "at the present moment"
"and again And again" - meaning having "a bit" multiple times


text:
Q: Unable to boot (or reinstall) Kubuntu 16.04 after upgrade After doing some updates/upgrades (unfortunately I don't remember names of the packages) I am not able to boot into Kubuntu. It freezes on the "Breathing kubuntu logo".
When I hit escape, I can see following errors (I had to type them here manually, so it is possible, that I might make some typos):
[9.436029] [drm.intel_set_pch_fifo_underrun_reporting [1915]] *ERROR* uncleared pch fifo underrun
[9.436050] [drm.intel_pch_fifo_underrun_irq_handler [1915]] *ERROR* PCH transcoder A FIFO underrun

umount: Can't umount /cdrom: Device or resource busy
/init: line 7: can't open /dev/sr0: No medium found
(...) these two lines repeat quite a few times

[55.219834] SQUASHFS error: Unable to read fragment cache entry [aa3e07]
[55.220432] SQUASHFS error: Unable to read page, block aa3e07, size[7096]
(...) these two lines repeat quite a few times (just with different ...timecodes? in the square brackets at the beginning)

Bus error

[79.692133] SQUASHFS error: zlib decompression failed, data probably corrupt
[79.692701] SQUASHFS error: squashfs_read_data failed to read block 0xaa3e07
[55.219834] SQUASHFS error: Unable to read fragment cache entry [aa3e07]
[55.220432] SQUASHFS error: Unable to read page, block aa3e07, size[7096]

[79.753474] Kernel panic - not syncing: Attempt to kill init! exitcode 0x00000007
[79.753474]
[79.754639] CPU: 3 PID: 1 Comm: init Not tainted 4.4.0-31-generic #50-Ubuntu
[79.755230] Hardware name: LENOVO Lenovo G580/Product Name, BIOS SECN33WW (V2.03) 06/06/2012
[79.755836] 0000000000000086 00000000e62afd6d ffff88013a3f7c50 ffffffff813f1143
[79.756416] ffffffff81cb2b50 ffff88013a3f7ce8 ffff88013a3f7cd8 ffffffff8118bde7
[79.757006] ffff880000000010 ffff88013a3f7ce8 ffff88013a3f7c80 00000000e62afd6d
[79.757605] Call Trace:

(here I got lazy to hand-copy all timestamps and hexa information, I can provide it, if needed, information, that I skipped, is marked in {curly brackets})
[{timestamp}]  [<{16 hexa digits}>] dump_stack+0x63/0x90
[{timestamp}]  [<{16 hexa digits}>] panic+0x{hexa}/0x{hexa}
[{timestamp}]  [<{16 hexa digits}>] ? perf_event_exit_task+0x{hexa}/0x{hexa}
[{timestamp}]  [<{16 hexa digits}>] do_exit+0x{hexa}/0x{hexa}
[{timestamp}]  [<{16 hexa digits}>] do_group_exit+0x{hexa}/0x{hexa}
[{timestamp}]  [<{16 hexa digits}>] get_signal+0x{hexa}/0x{hexa}
[{timestamp}]  [<{16 hexa digits}>] do_signal+0x{hexa}/0x{hexa}
[{timestamp}]  [<{16 hexa digits}>] ? force sig_info_fault+0x{hexa}/0x{hexa}
[{timestamp}]  [<{16 hexa digits}>] ? __probe_kernel_read+0x{hexa}/0x{hexa}
[{timestamp}]  [<{16 hexa digits}>] ? mm_fault_error+0x{hexa}/0x{hexa}
[{timestamp}]  [<{16 hexa digits}>] exit_to_usermode_loop+0x{hexa}/0x{hexa}
[{timestamp}]  [<{16 hexa digits}>] prepare_exit_to_usermode+0x{hexa}/0x{hexa}
[{timestamp}]  [<{16 hexa digits}>] retint_user+0x{hexa}/0x{hexa}

[79.765834] Kernel Offset: disabled
[79.766446] ---[ end Kernel panic - not syncing: Attempt to kill init! exitcode=0x00000007
[79.766446]

After that, I tried to do a fresh installment of Kubuntu 16.04 from USB.
In the boot manager from USB I've chosen to "Install Kubuntu".
It went as follows:
/dev/sda5: clean, 448332/1509600 files, 3769787/6054443 blocks
~.mount
ureadahead.service
{list of many .services}
systemd-rfkill.service
dev-disk-by\x2dpath-pci\x2d0000:00:1f.2\x2data\x2d1\x2dpart7.swap
dev-disk-by\x2did-wwn\x2d0x50004cf20a67e83f\x2dpart7.swap
dev-disk-by\x2did-ata\x2dST1000LM024_HN\x2dm101MBB_S2SMJ9CD547736\x2dpart7.swap
dev-sda7.swap
dev-disk-by\x2duuid-df2bfbbd\x2de7ca\x2d4e37\x2d9b35\x2de51a38e0ab13.swap
systemd-fsckd.service
fsckd-cancel-msg:Press Ctrl+C to cancel all filesystem checks in progress
fsckd:1:0,0:Checking in progress on 1 disk (0,0% complete)
(... more similar fsckd output)
fsckd:1:14,3:Checking in progress on 1 disk (14,3% complete)

At this moment it freezes for a while, than it resumes to boot up (the "typical loading output" with [  OK  ] at the beginning of the line.
(...)
[  OK  ] Started Run snappy firstboot setup.
Welcome to emergency mode! After logging in, type "journalctl -xb" to view
system logs, "systemctl reboot" to reboot, "systemctl default" or ^D to
try again to boot into default mode.
Press Enter for maintenance
(or press Control-D to continue):

After pressing Ctrl+D it repeated this exact message.
I have found some strategies, that have worked for other users, like typing "acpi=off" in the boot manager or disabling UEFI, but nothing helps. I also tried to repair my boot using the Boot Repair bootable USB. The "repair" happened without errors, but nothing has changed. Starting Kubuntu in recovery mode doesn't work either.
I thought, that maybe my HDD was broken, but dual booting into Windows 10 (installed on the same physical drive (just on another partition)) works just fine.
(I'm sorry for my english.)

A: I finally tried to install Kubuntu 16.10 from Live USB and it worked for me almost perfectly. I formatted my root partition and kept my /home partition, so I had to reinstall all my programs (without formating the / partition the installation didn't work).
After installing 16.10 I had to solve this issue:
"Welcome to emergency mode!" Think it is a fsck problem.
The solution provided by kyodake worked for me just fine.
Now I'm curious, if it would work before upgrading to 16.10...