text:
Q: Jacoco coverage report in gitlab-ci for Android project reports "No class files specified" I set up a Jacoco coverage report for our Kotlin Android project, which is supposed to run in gitlab-ci as job. I followed this article to generate the gradle tasks.
The coverage report works perfectly if run locally. But if the same gradle task is executed in the gitlab runner, it always produces empty reports with the message "No class files specified".
What's different in the pipeline when it comes to class files?
Maybe one of you is able to spot the issue.
jacoco.gradle:
apply plugin: 'jacoco'

android {
    testOptions {
        unitTests.all {
            jacoco {
                includeNoLocationClasses = true
            }
        }
    }

    jacoco {
        version = '0.8.4'
    }
}

project.afterEvaluate {
    def buildTypes = android.buildTypes.collect { type ->
        type.name
    }
    def productFlavors = android.productFlavors.collect { flavor ->
        flavor.name
    }
    if (!productFlavors) productFlavors.add('')
    productFlavors.each { productFlavorName ->
        buildTypes.each { buildTypeName ->
            def sourceName, sourcePath
            if (!productFlavorName) {
                sourceName = sourcePath = "${buildTypeName}"
            } else {
                sourceName = "${productFlavorName}${buildTypeName.capitalize()}"
                sourcePath = "${productFlavorName}${buildTypeName}"
            }
            def testTaskName = "test${sourceName.capitalize()}UnitTest"

            task "${testTaskName}Coverage" (type:JacocoReport, dependsOn: "$testTaskName") {
                group = "Reporting"
                description = "Generate Jacoco coverage reports on the ${sourceName.capitalize()} build."
                classDirectories = fileTree(
                    dir: "$project.buildDir/tmp/kotlin-classes/${sourcePath}",
                    excludes: ['**/R.class'] #List of excludes is reduced for this question
                )
                def coverageSourceDirs = [
                    "$project.buildDir.parent/src/main/java",
                    "$project.buildDir.parent/src/$productFlavorName/java",
                    "$project.buildDir.parent/src/$buildTypeName/java"
                ]

                additionalSourceDirs = files(coverageSourceDirs)
                sourceDirectories = files(coverageSourceDirs)
                executionData = files("${project.buildDir}/jacoco/${testTaskName}.exec")

                reports {
                    xml.enabled = true
                    html.enabled = true
                }
            }
        }
    }
}

gitlab-ci.yml: (unrelated jobs and stages removed)
image: docker:latest

variables:
    BUILDER_VERSION: "68e9780a"
    GRADLE_ARGS_CI: "--no-daemon --stacktrace"

stages:
    - build
    - test

.build-template: &build_definition
    stage: build
    image: our-docker-registry.com/android-builder:$BUILDER_VERSION
    tags:
        - frontend
    only:
        - merge_requests
        - develop
        - schedules

.test-template: &test_definition
    stage: test
    image: our-docker-registry.com/android-builder:$BUILDER_VERSION
    tags:
        - hermine-frontend
    only:
        - merge_requests
        - develop
        - schedules

build:dev:debug:
    <<: *build_definition
    script:
        - echo "Starting SCRIPT in job $CI_JOB_NAME"
        - ./gradlew $GRADLE_ARGS_CI :app:assembleDevDebug
    artifacts:
        paths:
            - app/build/outputs/apk/dev/debug
            - app/build/tmp/
        expire_in: 1 week

test:dev:debug:
    <<: *test_definition
    script:
        - echo "Starting SCRIPT in job $CI_JOB_NAME"
        - ./gradlew $GRADLE_ARGS_CI -Pci --console=plain :app:testDevDebugUnitTest
        - ./gradlew $GRADLE_ARGS_CI -Pci --console=plain :app:testDevDebugUnitTestCoverage
    artifacts:
        paths:
            - app/build/reports/tests/testDevDebugUnitTest
            - app/build/jacoco #execution file
            - app/build/reports
        expire_in: 1 day

Screenshot of my Android Studio build folder:


text:
Q: how to give space between two row? I want to give space between the two-row in HTML file
which place add the code for space between the two row

      <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css">

      <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css">

      <input type="checkbox" class="custom-control-input" name="status" value="0">
      viaxors Payment 1

      <input type="checkbox" class="custom-control-input" name="auth" value="0">
      In Noxitix 2

      <input type="checkbox" class="custom-control-input" name="auth" value="0">
      Soctixitx 3

      <input type="checkbox" class="custom-control-input" name="auth" value="0">
      Enjogs 4

      <input type="checkbox" class="custom-control-input" name="auth" value="0">
      Nedd Monons Duk 5

      <input type="checkbox" class="custom-control-input" name="auth" value="0">
      Escalation 6

output:

how to give the space between two rows in the HTML file?
help?

A: In HTML, you can use
 to add an empty line, you can try it.

A: Taking into consideration that a row starts here (according to your code):

Then add the following to it:

You can choose either margin-top or margin-bottom (If you wish space from above of below). In addition, play with the amount of px, and choose how much is good enough space for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Continuously Rotate Image OnTouchEvent In Android I'm new to Android development and am trying to figure out how to continuously rotate an image using the onTouchEvent.  I am using the following code to rotate the image 10 degrees when the onTouchEvent detects a screen touch and vice versa, but I want the image to keep rotating in 10 degree intervals as long as the onTouchEvent occurs.  Thanks!
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction()==MotionEvent.ACTION_DOWN) {
            degrees=degrees+10;
            make(degrees);
            }
        else if(event.getAction()==MotionEvent.ACTION_UP) {
            degrees=degrees-10;
            make(degrees);
            }
        return super.onTouchEvent(event);
        }
}

A: Use:
degrees = (degrees + 10) % 360;

// ...

if(degrees < 10) degrees += 360;
degrees = (degrees - 10) % 360;

A: From what I understand, is you want to start rotating an image when the user puts his / her finger on the screen, and stop rotating when the user takes off the finger from the screen.
If that's correct, you'd need to start a thread or a handler on the background that would keep.
May be something like:
// flag to tell if the rotation should continue
private boolean keepRotating = false;
// instance variable to keep the current rotation degrees
private int degrees = 0;
// rotation interval in milliseconds
private static final int INTERVAL = 100;

@Override
public boolean onTouchEvent(MotionEvent event)
{
    switch (event.getAction())
    {
        case MotionEvent.ACTION_DOWN:
            startRotating();
            break;
        case MotionEvent.ACTION_UP:
            stopRotating();
            break;
    }

    return super.onTouchEvent(event);
}

public void startRotating()
{
    if (!keepRotating)
    {
        keepRotating = true;

        final Handler handler = new Handler();

        handler.postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                if (keepRotating)
                {
                    degrees = (degrees + 10) % 360;
                    make(degrees);

                    handler.postDelayed(this, INTERVAL);
                }
            }
        }, INTERVAL);
    }
}

public void stopRotating()
{
    keepRotating = false;
}

public void make(int degrees)
{
    Log.i(this.getClass().toString(), "Rotation : " + degrees);

    // Your rotation logic here based on the degrees parameter
    // ...
}

A: Use the below code
public void startMoving() {
    rotateAnimation1 = null;
    try {
        if (duration < 1500) {
            rotateAnimation1 = new RotateAnimation(0, 360,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation1.setInterpolator(new LinearInterpolator());
            rotateAnimation1.setDuration(duration);
            rotateAnimation1.setRepeatCount(0);
            imgBottle.startAnimation(rotateAnimation1);

            flagSpinAvailable = false;

            rotateAnimation1.setAnimationListener(new AnimationListener() {
                public void onAnimationStart(Animation anim) {
                };

                public void onAnimationRepeat(Animation anim) {
                };

                public void onAnimationEnd(Animation anim) {
                    duration = duration + 70;
                    startMoving();
                };
            });

        } else {
            duration = duration + 100;
            final float degree = (float) (Math.random() * 360);
            degreeBack = 360 - degree;
            rotateAnimation2 = new RotateAnimation(0, degree,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation2.setInterpolator(new LinearInterpolator());
            rotateAnimation2.setDuration(duration);
            rotateAnimation2.setRepeatCount(0);
            rotateAnimation2.setFillAfter(true);
            imgBottle.startAnimation(rotateAnimation2);

            rotateAnimation2.setAnimationListener(new AnimationListener() {
                public void onAnimationStart(Animation anim) {
                };

                public void onAnimationRepeat(Animation anim) {
                };

                public void onAnimationEnd(Animation anim) {
                    afterSpinEnd();
                };
            });

        }
    } catch (Exception e) {
        flagSpinAvailable = true;
        e.printStackTrace();
    }
}

This is my code to rotate a image around itself and slowly decrease the speed


text:
Q: Is it ok to call model learning in machine learning an "estimator"? Spark doc contains this:

An Estimator abstracts the concept of a learning algorithm or any algorithm that fits or trains on data. Technically, an Estimator implements a method fit(), which accepts a DataFrame and produces a Model, which is a Transformer. For example, a learning algorithm such as LogisticRegression is an Estimator, and calling fit() trains a LogisticRegressionModel, which is a Model and hence a Transformer.

But Wikipedia says:

An "estimator" or "point estimate" is a statistic (that is, a function of the data) that is used to infer the value of an unknown parameter in a statistical model. The parameter being estimated is sometimes called the estimand. It can be either finite-dimensional (in parametric and semi-parametric models), or infinite-dimensional (semi-parametric and non-parametric models). If the parameter is denoted $\theta$ then the estimator is traditionally written by adding a circumflex over the symbol: $\widehat {\theta }$. Being a function of the data, the estimator is itself a random variable; a particular realization of this random variable is called the "estimate". Sometimes the words "estimator" and "estimate" are used interchangeably.

I would have called the machine learning model itself the "estimator". Are the 2 definitions above close enough, or off, or are there important distinctions to be aware of?

A: Spark's documentation refers to internal names of Spark's procedures and objects, not to theoretical concepts. In statistics estimator is basically a procedure that estimates something given the data and returns an estimate.
It is hard to answer your question without knowing what you mean by model. Statistical model describes the phenomenon of interest in terms of probability theory (notice that there are also other models, e.g. mechanistic models). It is not yet an estimator of anything, but just an abstract description of the problem. You need an estimator to estimate the parameters of your model (also in case of so-called non-parametric models). In machine learning people often call algorithms used to estimate something as models, but in general: model is a theoretical description of the problem and estimator is a procedure that generates the estimates of its parameters. Estimator is a general procedure, not its implementation, so function foo() in software XYZ is not an estimator, but rather it's an implementation of some estimator.


text:
Q: Ant Design TreeSelect map data from API to title value keys I am trying to populate a Tree Select in ANT Design from API, the API Response type is so
projectData = ProjectData[];

export type ProjectData = {
    key?: number;
    projectId: number;
    projectName: string;
    description: string;
    level: number;
    parent: string;
    parentId: number;
    children: ProjectData[];
};

for TreeSelect I can't find an option to set title to projectName and value to projectId
Tree select takes treeData values in this format
const treeData = [
  {
    title: 'Node1',
    value: '0-0',
    children: [
      {
        title: 'Child Node1',
        value: '0-0-1',
      },
      {
        title: 'Child Node2',
        value: '0-0-2',
      },
    ],
  },
  {
    title: 'Node2',
    value: '0-1',
  },
];

For example if I am using a a Cascader in ant design I can set the mapping with the fieldNames prop like so
fieldNames={{ label: 'projectName', value: 'projectId', children: 'children' }}
is it possible at all to do something like this with TreeSelect?
I have a ProjectData[] as mentioned above and I need to generate a tree select using that data. What is the best way?
Now If I use Cascader I can only select the Last(deepest) entry and not a node which is a parent. Thus I have to use Treeselect and Can't figure out how to map it properly.
------- Edit -----------
Added a sample of data with implementation of cascader and treeselect on codesandbox here

A: Upon reading the docs, it seems like you can do this through the prop treeDataSimpleMode.  This would change the expected format of the treeData from nested objects with children to a flat array where each object has its own id and a parent id pId.  It also appears that we can specify the property names for id and pId which is exactly what you want.  We can change treeNodeLabelProp from "label" to "projectName" and treeNodeFilterProp from "value" to "projectId".
So it seems like this might be all you need:
const MyTree = ({projectData}: {projectData: ProjectData[]}) => {
  return (
    <TreeSelect
      treeData={projectData}
      treeDataSimpleMode={{
        id: 'projectId',
        pId: 'parentId',
        //rootPId can be set too
      }}
      treeNodeLabelProp="projectName"
      treeNodeFilterProp="projectId"
    />
  )

I can't really test this out without sample data so let me know if you get any errors.
Note that the typings in the antd package are not strict enough to detect changes in the formatting.  The DataNode interface makes all of the expected properties optional and has a string index signature to allow for any custom properties.
export interface DataNode {
    value?: RawValueType;
    title?: React.ReactNode;
    label?: React.ReactNode;
    key?: Key;
    disabled?: boolean;
    disableCheckbox?: boolean;
    checkable?: boolean;
    children?: DataNode[];
    /** Customize data info */
    [prop: string]: any;
}

A: 2022 Answer
In Ant design version 4.17.0 you can use fieldNames Doc


text:
Q: Flutter: Function with function as Argument; set default function I want to create a helper to handle my dialogs. For this I created a static method to call:
I have a class DialogInstance to provide my values, that should hold style and other dialog information.

class DialogInstance {
  final BuildContext context;
  final String title;
  final String message;
  final void Function() onCancel;
  final void Function() onConfirm;
  final String confirmText;
  final String cancelText;
  final Color confirmColor;
  final Color cancelColor;

  DialogInstance.confirm(
      {@required this.context,
      @required this.title,
      @required this.message,
      @required this.onConfirm,
      Function() onCancel, // should be default set
      String confirmText,
      String cancelText,
      Color confirmColor,
      this.cancelColor})
      : this.onCancel = onCancel ?? _popContext(context), // setting default (doesn't work)
        this.confirmText = confirmText ?? 'Ok',
        this.cancelText = cancelText ?? 'Abbruch',
        this.confirmColor = confirmColor ?? Colors.red;

  static _popContext(BuildContext context) {
    Navigator.pop(context);
  }
}

I call this via:
DialogHelper.showDialog(dialogInstance: myDialog)

If I do it like this, the method _popContext gets called at initialisation and not onPressed in the dialog.
How can I set this function as default and the dialog doesn't get closed at initialisation?

A: Necessary to create a new function and call pop context () => _popContext(context). But it's impossible to create final function in constructor, use factory constructor.
class DialogInstance {
  final BuildContext context;
  final String title;
  final String message;
  final void Function() onCancel;
  final void Function() onConfirm;
  final String confirmText;
  final String cancelText;
  final Color confirmColor;
  final Color cancelColor;

  DialogInstance._(
      {this.context,
      this.title,
      this.message,
      this.onCancel,
      this.onConfirm,
      this.confirmText,
      this.cancelText,
      this.confirmColor,
      this.cancelColor});

  factory DialogInstance.confirm(
      {@required BuildContext context,
      @required String title,
      @required String message,
      @required void Function() onConfirm,
      Function() onCancel, // should be default set
      String confirmText,
      String cancelText,
      Color confirmColor,
      Color cancelColor}) {
    return DialogInstance._(
      context: context,
      title: title,
      message: message,
      onConfirm: onConfirm,
      onCancel: onCancel ?? () => _popContext(context),
      confirmText: confirmText ?? 'Ok',
      cancelText: cancelText ?? 'Abbruch',
      confirmColor: confirmColor ?? Colors.red,
    );
  }

  static _popContext(BuildContext context) {
    Navigator.pop(context);
  }
}


text:
Q: How I can type half-space char in the desktop skype application? Can anyone explain to me that how I can type half-space char in the desktop Skype application? In Persian Language we can use the half-space char but skype prevents us to do this. When we type half-space char (shift space), skype seems to remove this char.

A: What such an interesting issue! I also have that problem. It seems to me it's a bug that Skype couldn't support the Persian Language correctly. I reckon it should be submitted as an issue for Skype.


text:
Q: How to kill previous cronjob process when new starts? Can't believe I haven't found any answers of this question on the site.
Anyway, I have a cronjob task that I want to run every third minute. If it's not completed when next one starts after 3 minutes, I want the current running one to be killed. NOT the new one to wait. I new one must be started, but the old one must be killed. How do I do this?
Here is my current code:
*/3 * * * * wget -O /dev/null http://mywebsite.com/wp-admin/admin-ajax.php?action=my_function
Anyone know the answer?

A: Thick and quick way:
Look at the process ID (PID).
Modify the process to put its PID into a temporary file. If your process is called fred, call the file /var/tmp/fredpid or something like that.
This way, every time the process starts up, it checks for the presence of the temporary file already being there. You must code that functionality of course, not forgetting to make sure the process deletes the temporary file at the end of its execution.
Roughly speaking, the steps are as follows:
(1) If /var/tmp/fredpid exists, snarf the PID from the file
(2) kill the older process running under that PID.
(3) Place the current PID in the temporary file.
(4) resume work.
(5) work ends, remove /var/tmp/fredpid


text:
Q: How a add a new widget inside a widget which is dynamically created using jquery for gridstack in an Angular6 Project I have a button on which I have added a click event , in that method I am generating a new grid-stack widget
AddWidget(fieldType)

{
   var templateString;
   switch(fieldType)
   {
      case 'Text' :

                        <button class="fa fa-ellipsis-v buttonClicked" style="float:right;border:none;background-color: transparent;margin-right:2px;"></button>

                                Field Name

                             <input class="ms-TextField-field updateValue" style="width:75%" type="text" placeholder="Enter Field Name">

          break;
   }
}

After that,
    var $htmlString = $(templateString);
    $htmlString.children('div.grid-stack-item-content').attr('id', newid);
    var grids = $('.grid-stack').data('gridstack');
    grids.addWidget($htmlString, 1, 1, 3, 1, true, 3);

This works fine, But I am blocked how to again add a new widget inside this newwly created widget.
Suppose I am having a button in the above created widget, and I need to add a further sub grid-stack-item widget inside it.
How to solve this problem??


text:
Q: Intel PEBS sample context I am using Linux perf tool to monitor system-wide  (exclude_kernel == 0) PEBS samples. I was wondering whether PEBS sample can occur at interrupt context (i.e., during an interrupt is being served by the interrupt handler). If it is possible, is there any way to determine the context (e.g, process context, interrupt context) of the PEBS sample (i.e., register bits)?

A: PEBS sampling never occurs when an interrupt is being serviced.

PEBS uses the above buffering mechanism to store its records. You can clearly see all the PEBS relevant fields like PEBS buffer base and PEBS interrupt threshold etc. PEBS interrupts occur when the PEBS buffer index matches the PEBS interrupt threshold specified.
The PEBS interrupt handler will reset the PEBS Buffer Index back to the start of the PEBS buffer base. If PEBS sampling were to continue, then PEBS would also try to access the DS buffer to increment the PEBS Buffer Index. So both the PEBS Interrupt and PEBS itself will try to write to the same DS save area. This obviously points to a race condition between the PEBS interrupt handler and PEBS module.
To avoid this race condition, it is required to disable PEBS sampling (by disabling flags in the IA32_PEBS_ENABLE msr register). Also all the event counters must be disabled as well by the interrupt handler. This is the proof in the kernel.
However, if the PEBS interrupts cause too much throttling on the CPU, you can have a PERF_RECORD_THROTTLE event, but this is of course, not a PEBS_SAMPLE event but rather a PERF_RECORD event.


text:
Q: Find the maximum magnitude and print it I have a set of values as shown below.
-4.904045E+04   3.972944E+04
-1.205839E+05   3.662380E+04
-1.950760E+04   1.020331E+01
-1.128968E-01   1.129738E+05
-8.031810E+01   1.466682E+05
-4.914462E+04   2.353826E+03
-4.020837E+04   3.524823E+01
-3.058178E+03   1.234481E+04

I would like to find the maximum magnitude of the two and print the result with the original sign (nagative or positive).
Ex: I need the result like this:
-4.904045E+04
-1.205839E+05
-1.950760E+04
1.129738E+05
1.466682E+05
-4.914462E+04
-4.020837E+04
1.234481E+04

Please let me know the code for performing this.
Thank you in advance.

A: If $1  is always negative and $2 always positive:
awk '{print(-$1>$2?$1:$2)}' < your-file

If not:
awk 'function abs(x) {return (x<0?-x:x)}
     {print(abs($1)>abs($2)?$1:$2)}' < your-file

A: And here's a Perl one:
perl -alne 'abs($F[0])>abs($F[1]) ? print $F[0] : print $F[1]' < file

Flags:

*

*-e : give a script in the command line

*-n : run the script given by e on each line of the input file

*-a : splits each line at white space into the array @F

*-l : automatically adds a new line (\n) to each print.


text:
Q: Angular auxiliary route from child not loading component I have a route defined like this:
My app.component.html has 2 outlets:
<router-outlet></router-outlet>
<router-outlet name="modal"></router-outlet>

My route:
const routes: Routes = [
  { path: 'contents/:id', component: ContentComponent, children: [
    { path: 'edit', component: ContentFormComponent, outlet: 'modal' }
  ]},
];

The route (example) /contents/324231 loads fine with the ContentComponent.
What I need to do is that the route /contents/324231/edit loads the ContentFormComponent inside the 'modal' outlet.
I tried to follow the examples, building a link:
<a [routerLink]="[ {outlets: { modal: 'edit' } } ]" >edit</a>

It gives the href: /contents/1/(modal:edit)
When I click in the link, the url changes to this but the component is not loaded (neither the constructor or ngOnInit method are called).
Any thoughts?


text:
Q: Why is the argument passed in to my recursive function not updating its value? I'm just playing around with simple recursion and functions. Nothing too serious, but not doing what I expect:
    var recursive = function adder (x) {
  x = ++x
  if (x < 10) {
    console.log('x is now: ' + x)
    adder(x)
  }
  return x
}

console.log(recursive(5))

This completes the loop and runs properly, but am wondering why the 'final' output is '6.' Why don't I get the 'final' value of x after all the recursion is done?

A: x=++x;
x+=1;
x++;
++x;

You need either the pre increment or the increase by operator, or the postincrement without an reassignment. The post increment retuns first, then increments...
alert((1)++)//1

Some ongoing explanations:
var recursive = function adder (x) {
  ++x;
  if (x < 10) {
   console.log('x is now: ' + x)
   return adder(x); //lets return our added result
  }
 return x;//if x=10 lets return 10
}

console.log(recursive(5))//will log 10

It mainly didnt work as expected as primitives are passed by value. So there are actually 5 different x variables in 5 different contexts of adder...
Unlike primitives, objects are passed by reference:
function adder(obj){
 obj.x++;
 if(obj.x<10){
   adder(obj);
 }
}

var test={x:1};
adder(test);
console.log(test.x);


text:
Q: Convergence of sum of random numbers I'm not too sure if this is a sensible, well-defined question to ask, but there's no harm in asking, so here goes.
Say I draw a number from the uniform distribution on the unit interval. I draw another number and add it to the first. I draw more numbers and keep adding them. If I continue this for infinitely many steps, how likely is it that this 'random sum' will converge?
That's the basic idea I want to ask. Let me try making it a bit more formal: Let $X_i\sim\mathcal{U}(0,1)$ for all $i$, and let $X_n=\sum_{i=1}^n X_i$. Then we can define $X_\infty=\lim_{n\to\infty}X_n$. Now, I want to know $P(X_\infty < \infty)$.
If you can share other interesting properties of $X_\infty$, that would be cool too.

A: For $X_n$ to converge, you need that for any $\epsilon >0$, there is $n_0$ such that if $n > n_0$, $|X_n - X_{n_0}| < \epsilon$. However, this would imply that for every $\epsilon >0$, there is an index, $n_0$, after which, at the very least, every drawn value is smaller than $\epsilon$. However, for arbitrarily small $\epsilon$, and infinitely many draws from the unit interval, the probability of all draws being smaller than $\epsilon$ tends to $0$.
Putting it another way, "almost all" sums formed from numbers in the unit interval do not converge.


text:
Q: Refresh the datasource on password rotation in SpringBoot Application Can someone please guide me, how I can refresh the datasource whenever the password is rotated for the database.
Basically I don't want any manual step to refresh the datasource(like calling any endpoint). Rather than I can poll a file to see if DB credentials are rotated using FileWatcher service.
I have already read few solutions over stackoverflow regarding the same ask. But I couldn't able to implement it successfully.
Since I am new to stackoverflow can't comment on others question to get solution clarified.
Below is simple class for creating the connection pool.
@Configuration
@EnableTransactionManagement
public class JpaConfig {
@Value("${db.username}")
private String username;

@Value("${db.password}")
private String password;

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("com.example");
        factory.setDataSource(dataSource());

        Properties properties = new Properties();
        properties.put("hibernate.format_sql", true);
        properties.put("hibernate.show_sql", true);
        properties.put("hibernate.hbm2ddl.auto", "none");
        properties.put("hibernate.generate_statistics",  false);
        factory.setJpaProperties(properties);
        return factory;
}
@Bean
public PlatformTransactionManager transactionManager() {
  JpaTransactionManager txManager = new JpaTransactionManager();
  txManager.setEntityManagerFactory(entityManagerFactory);
  return txManager;
}
private DataSource dataSource() {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl("db_connection_url");
    hikariConfig.setUsername(username);
    hikariConfig.setPassword(password);
    hikariConfig.setPoolName("test_pool");
    HikariDataSource hikariDataSource = new HikariDataSource(hikariConfig);
    return hikariDataSource;
}

}

A: You can use "Spring Cloud Bus". And whenever you change the datasource password configuration, your service can listen for this event so that it can create a new bean based on the new configuration.
Please look at this document
https://spring.io/projects/spring-cloud-bus

A: This repo has solution for this question : https://github.com/visa2learn/spring-cloud-vault-db-cred-rotation
I find it quite useful.
Just to make solution better read about SecretLeaseContainer :
Event-based container to request secrets from Vault and renew the associated Lease. Secrets can be rotated, depending on the requested RequestedSecret.getMode()


text:
Q: Shouldn't ball has to move in the circle even after cutting the rope by which it was attached? Since the tension force is a central acting force, the torque on an orbiting ball about that center is zero. But if the rope is cut down during motion the torque would still remain zero. This would mean that angular momentum of the orbiting ball should be conserved, but I find everywhere that ball will move in a straight line tangentially. What is wrong in my reasoning?

A: The planets will continue moving with the momentum they have at the moment the Sun disappears, apart from mutual attraction. These orbitals conserve planetary angular momentum is conserved. This is clear from the formula $L = \vec r \times \vec p$. $r \sin \theta$ and $mv$ remain constant after such an event.
The presence of gravity means that the orbit has to be a conic section to conserve angular momentum, the ellipticity depending on a combination of L and energy. In the absence of gravity straight inertial movement does the job.

A: The flaw in your reasoning is thinking that straight line motion at constant velocity does not constitute constant angular momentum about some point, but it actually does.
Angular momentum is given by$^*$
$$\mathbf L=\mathbf r\times\mathbf p$$
Without loss of generality, let's assume after the rope is cut our object is moving along the line $y=1$ in the x-y plane, and we are looking at the angular momentum about the origin. Then our angular momentum must always be perpendicular to the x-y plane, so it will be sufficient to just look at the magnitude of the angular momentum
$$L=rp\sin\theta$$
where $\theta$ is the angle between the position vector and the momentum vector (which is the angle between the position vector and the x-axis based on the set up above).
Now, since there are no forces acting on our object, $p$ is constant. Also, $r\sin\theta$ is just the constant $y=1$ value given by the line the object is moving along. Therefore, it must be that $L$ is constant.
This shows that absence of a net torque (conserved angular momentum) is not enough to uniquely determine the motion. While in circular motion, there is still a net force acting on our object. Without the rope, there is no net force. The motions are different.

$^*$Note that this applies to any type of motion, not just circular motion.


text:
Q: Disk path changes from boot to boot I have a disk
sudo lshw -C disk
 *-disk
   description: ATA Disk
   product: Corsair CSSD-F12
   physical id: 0.0.0
   bus info: scsi@7:0.0.0
   logical name: /dev/sde
   version: 2.0
   serial: 10516505330003430015
   size: 111GiB (120GB)
   capabilities: gpt-1.00 partitioned partitioned:gpt
   configuration: ansiversion=5 guid=21ec30ba-0aab-4ce9-be03-8f6f4de1afa1 sectorsize=512

I've mounted it yesterday:
cat /etc/fstab
/dev/sdg1 /home/ssa/mnt/corsair ext4 defaults 0 0

Yesterday it had path /dev/sdg1 now it's /dev/sde and mount is not working.
Why name is changed after reboot?

A: Such device names are not persistent, udev makes no guarantees that they will be the same. The Arch Wiki says:

Because udev loads all modules asynchronously, they are initialized in a different order. This can result in devices randomly switching names. A udev rule can be added to use static device names.

You should use labels or UUIDs instead.
First, get the UUID:
sudo blkid -o export /path/to/device | grep UUID

Then use:
UUID=... /path/to/mount/point type ...

For example:
$ sudo blkid -o export /dev/sda3 | grep UUID
UUID=d3504dc2-8f01-48f1-be05-d265110e2e73

And the corresponding entry would be:
UUID=d3504dc2-8f01-48f1-be05-d265110e2e73 /   ext4    errors=remount-ro 0       1


text:
Q: PHP Warning: count(): Parameter must be an array or an object that implements Countable in PHP Warning: count(): Parameter must be an array or an object that implements Countable in /opt/lampp/htdocs/deingreidcht/typo3conf/ext/toctoc_comments/pi1/class.toctoc_comments_pi1.php
how to solve this
Here is my code, I have applied condition,
if (count($rowsrf)== 0) {

A: You can typo3 standard method
For example in your controller
$this->yourextRepository->findAll()->count();

May this will help you!


text:
Q: django как сделать страницу просмотра логов Логи пишу через библиотека logging лежат в папке logs
Вопрос. Как мне в админку добавить страницу. Без модели. Произвольную страницу. Чтобы я там например вывел логи и какую нить простую формочку для поиска / фильтра сделать
может есть какая то заготовка?

A: Создание кастомной страницы в админ панели мало чем отличается от создания обычной странице на django. Вопрос достаточно обширный и я напишу тезисно, что надо сделать, относительно вашего какого-то приложения (views.py, urls.py)

*

*Во views.py пишете обычное представление
from django.shortcuts import rende

def show_admin_panel_custom(request):
    context = {'data': 'test'}
    return render(request, 'any_path/admin_panel_custom.html', context)

*Создаете шаблон admin_panel_custom.html и наследуете его от admin/base_site.html. Пример
{% extends 'admin/base_site.html' %}
....

*Определим URLs в urls.py
from django.conf.urls import url
from django.contrib.auth.decorators import user_passes_test
from any_path.views show_admin_panel_custom

urlpatterns = [
    url(r'^admin-added-page/$', user_passes_test(lambda u: u.is_superuser)(show_admin_panel_custom), name='show_admin_panel_custom'),
 ]

В общем, то, и все. Не забудьте прокинуть URLы приложения до URLов проекта и по ссылке http://localhost:8000/admin-added-page вам будет доступна страничка, причем если вы обратите внимание на ссылку, то я сразу ограничил доступ к ней только для суперпользователя. any_path - это путь до приложения и необходимо прописать ваше значение
Далее, есть несколько путей добавления ссылки в админке на эту страницу, но это отдельный вопрос и с этим вам уже будет под силу разобраться


text:
Q: c++ multithreading function calls with parameters by reference I am using a library which uses multithreading to call member functions when an event happens. Each "handler" in the library has a thread which can call function MyClass::Process(const Signal& signal). MyClass has a reference to a Catalog class called cat.
Inside of Process I have the following code:
Stats stats;//simple container struct to hold values

std:string id(signal.signalId());
//set values of stats here based on the values in signal

cat->onSignalUpdate(id, stats);

From the libary's documentation:

It's impossible in bounds of single instance of Handler to have two
  user callbacks to be invoked simultaneously. However, different
  instances of Handler for different channels are not linked with each
  other, therefore invocations from different Handler instances may
  occur in parallel.

Catalog has a member std::map<std::string, Stats> signal_map
Inside of Catalog::onSignalUpdate(const std::string& id, const Stats& stats)
std::map<std::string, Stats>::iterator it(signal_map.find(id));
if(it != signal_map.end())
{
    it->second = stats;
}

This works much of the time, where the proper Ids are mapped to the appropriate Stats struct. Occasionally I am getting improper matching where an ID of Handler A, is being assigned to a struct belonging to that of Handler B. It appears to me that the function is being called in parallel. I was under the impression that in threading, calls to functions, while done in parallel, are duplicated. Is this not the case, or is there an issue with passing values by reference in threads?

A: You can't update a std::map from multiple threads without some form of protection against multiple threads modifying the map at the same time. You need a mutex or something along those lines. In partciular, if id is "new", then a the underlying data structures (typically a "RB-tree") in the map will be altered. This MUST not be done from multiple threads. You also can't access the tree to "read" while it is being modified, as the entries in the tree may be "half-updated" (e.g. the next element is pointing to an element that hasn't been properly filled in or some such).


text:
Q: Keyboard command to copy and paste last line in terminal? Is there a command to copy the last line in terminal and paste it into my current command without reaching for my mouse?

I'd like to be able to scroll up and take a line and paste it to terminal.


text:
Q: How to be able to highlight only singe mat-list element at a time I have dynamic mat-list:
          <mat-list *ngFor="let item of (items$ | async)">
            <mat-list-item>
              <mat-checkbox
                [value]="item.id"
                (change)="doStuff($event)"
              >
              </mat-checkbox
              ><a (click)="getDetails(item.id)">{{
                item.title
              }}</a></mat-list-item
            >
          </mat-list>

on getDetails I am displaying some additional info in the div about the item and at the same time I want to highlight that particular selected item. Then if I click  other item I want only that one to be highlighted now and the other one to get unhighlighted.
I think I need to have a css class that just gets assigned on item being clicked but having difficulties to approach that in my particular use case.
How would you achieve that with a minimum pain? Any ideas?
UPDATE:
Currently playing with @ViewChildren('#matList') myItems: ElementRef; but no luck yet


text:
Q: Extra lines in ajax response wordpress I'm using jQuery for ajax requests in wordpress and Success response is like
1.
2.
3.<option value="65">test</option>

means newline character being added when the script executes. so my respionse is not getting display into html. I am using ajax into fancybox.
Please help.

A: assuming that the response you're getting is in the var response:
// splitting up response line by line
var arr = response.split('\n');

// getting the last line, and then getting everything after the dot
var html = arr[arr.length-1].split('.')[1];

The pure HTML is now in the variable html.
Cheers


text:
Q: How to verify results of Pyephem I want to see "in my sky" how many satellites I can see.
I'm using this code:
sat_alt, sat_az, sat_name = [], [], []

observer = ephem.Observer()
observer.long = Longitude
observer.lat = Latitude
observer.date = TimeNow

HowMany = 0

print "TIME: ", TimeNow
print
GPS_list = 'http://www.celestrak.com/NORAD/elements/gps-ops.txt'
GPS2_list = 'http://www.tle.info/data/gps-ops.txt'
GLONASS_list = 'http://www.celestrak.com/NORAD/elements/glo-ops.txt'
GLONASS2_list = 'http://www.tle.info/data/glo-ops.txt'
#'http://www.amsat.org/amsat/ftp/keps/current/nasabare.txt').readlines()

tles = urllib2.urlopen(GPS_list).readlines()
tles = [item.strip() for item in tles]
tles = [(tles[i],tles[i+1],tles[i+2]) for i in xrange(0,len(tles)-2,3)]

for tle in tles:

    try:
        sat = ephem.readtle(tle[0], tle[1], tle[2])
        rt, ra, tt, ta, st, sa = observer.next_pass(sat)

        if rt is not None and st is not None:
            sat.compute(observer)

            if TimeNow >= ephem.localtime(st) and TimeNow <= ephem.localtime(rt):
                text = tle[0]
                sat_alt.append(np.rad2deg(sat.alt))
                sat_az.append(np.rad2deg(sat.az))

                text2 = text.rsplit(')', 1)[0]
                NamePRN = text2.rsplit('(', 1)[1]
                sat_name.append(NamePRN)

                #I wanna Try just with the PRN 1
                if 1 == 1: # NamePRN = 'PRN 01':
                    print NamePRN
                    print "Elev:" , np.rad2deg(sat.alt), "Azimuth: ",np.rad2deg(sat.az) #sat.alt / ephem.degree
                    print "original rise time: ",rt
                    print 'rise time: ', ephem.localtime(rt)
                    print 'set time: ',  ephem.localtime(st)
                    print
                    print 'Time until rise: ', ephem.localtime(rt) - TimeNow
                    print 'Time until set: ',ephem.localtime(st) - TimeNow
                    timeuntilrise = ephem.localtime(rt)-TimeNow
                    HowMany += 1
                    minutesaway = timeuntilrise.seconds/60.0

                    if sys.platform == 'darwin':
                        say = 'say "%s WILL BE MAKING A PASS IN %d MINUTES."' % (NamePRN,minutesaway)
                        os.system(say)
                    else:
                        print "Minutes Away: ",minutesaway

            #print ' Rise Azimuth: ', ra
            #print ' Transit Time: ', tt
            #print ' Transit Altitude: ', ta
            #print ' Set Time: ', st
            #print ' Set Azimuth: ', sa
            #print 'rise time: ', ephem.localtime(rt)
            #print 'set time: ',  ephem.localtime(st)
            #print
    except ValueError as e:
        print e
print
print "How Many: ", HowMany

The results are:
TIME:  2017-03-23 09:32:30.445831

PRN 14
Elev: 23.5719168541 Azimuth:  186.783257119
original rise time:  2017/3/23 18:15:23
rise time:  2017-03-23 13:15:23.000003
set time:  2017-03-23 05:56:40.000003

Time until rise:  3:42:52.554172
Time until set:  -1 day, 20:24:09.554172
Minutes Away:  222.866666667
PRN 22
Elev: 27.8617383982 Azimuth:  135.529777134
original rise time:  2017/3/23 18:59:39
rise time:  2017-03-23 13:59:38.000003
set time:  2017-03-23 05:52:54.000003

Time until rise:  4:27:07.554172
Time until set:  -1 day, 20:20:23.554172
Minutes Away:  267.116666667
PRN 19
Elev: 63.2536032619 Azimuth:  23.0164551349
original rise time:  2017/3/23 19:01:01
rise time:  2017-03-23 14:01:00.000003
set time:  2017-03-23 07:01:07.000003

Time until rise:  4:28:29.554172
Time until set:  -1 day, 21:28:36.554172
Minutes Away:  268.483333333
PRN 23
Elev: 2.50815303871 Azimuth:  88.104092255
original rise time:  2017/3/23 21:33:06
rise time:  2017-03-23 16:33:06.000003
set time:  2017-03-23 08:35:45.000003

Time until rise:  7:00:35.554172
Time until set:  -1 day, 23:03:14.554172
Minutes Away:  420.583333333
PRN 17
Elev: 43.5586196015 Azimuth:  52.03302655
original rise time:  2017/3/23 18:27:16
rise time:  2017-03-23 13:27:15.000003
set time:  2017-03-23 06:12:30.000003

Time until rise:  3:54:44.554172
Time until set:  -1 day, 20:39:59.554172
Minutes Away:  234.733333333
PRN 31
Elev: 7.61244305169 Azimuth:  168.667710308
original rise time:  2017/3/23 19:47:23
rise time:  2017-03-23 14:47:23.000003
set time:  2017-03-23 08:03:23.000003

Time until rise:  5:14:52.554172
Time until set:  -1 day, 22:30:52.554172
Minutes Away:  314.866666667
PRN 12
Elev: 48.18881167 Azimuth:  258.782917613
original rise time:  2017/3/23 18:42:38
rise time:  2017-03-23 13:42:38.000003
set time:  2017-03-23 07:35:56.000003

Time until rise:  4:10:07.554172
Time until set:  -1 day, 22:03:25.554172
Minutes Away:  250.116666667
PRN 25
Elev: 18.8269690697 Azimuth:  222.58247788
original rise time:  2017/3/23 19:39:10
rise time:  2017-03-23 14:39:09.000003
set time:  2017-03-23 08:34:40.000003

Time until rise:  5:06:38.554172
Time until set:  -1 day, 23:02:09.554172
Minutes Away:  306.633333333
PRN 01
Elev: 9.20983988345 Azimuth:  117.518172142
original rise time:  2017/3/23 17:53:54
rise time:  2017-03-23 12:53:54.000003
set time:  2017-03-23 04:56:06.000003

Time until rise:  3:21:23.554172
Time until set:  -1 day, 19:23:35.554172
Minutes Away:  201.383333333
PRN 24
Elev: 15.4381621753 Azimuth:  284.908746358
original rise time:  2017/3/23 16:23:16
rise time:  2017-03-23 11:23:16.000003
set time:  2017-03-23 05:14:38.000003

Time until rise:  1:50:45.554172
Time until set:  -1 day, 19:42:07.554172
Minutes Away:  110.75
PRN 06
Elev: 49.0638613556 Azimuth:  345.92883678
original rise time:  2017/3/23 20:57:05
rise time:  2017-03-23 15:57:04.000003
set time:  2017-03-23 08:25:55.000003

Time until rise:  6:24:33.554172
Time until set:  -1 day, 22:53:24.554172
Minutes Away:  384.55
PRN 03
Elev: 41.016662249 Azimuth:  109.881781593
original rise time:  2017/3/23 19:45:53
rise time:  2017-03-23 14:45:53.000003
set time:  2017-03-23 06:43:35.000003

Time until rise:  5:13:22.554172
Time until set:  -1 day, 21:11:04.554172
Minutes Away:  313.366666667
PRN 32
Elev: 13.6017761707 Azimuth:  207.711749038
original rise time:  2017/3/23 17:23:22
rise time:  2017-03-23 12:23:22.000003
set time:  2017-03-23 05:14:55.000003

Time until rise:  2:50:51.554172
Time until set:  -1 day, 19:42:24.554172
Minutes Away:  170.85

How Many:  13

I'm checking the page "http://www.n2yo.com/" in the menu "Satellites in Orbit"->"GPS satellites" But How can I see if I'm right or not? another web page?
Thanks.

A: Calsky and n2yo works to see the azimuth and elevation from some location. in Calsky show for default, the satellites above 25º

A: For on-line tools, I really find in-the-sky.org useful and helpful. It's quite new, modern, and well-maintained by an active space expert and web developer. See this and this.
Another python check can be done with Skyfield. It is maintained by the same person who maintains PyEphem, but again is much newer and modernized. Skyfield is quite different than PyEphem on the inside, and they have different sets of capabilities.  See all of these in stackoverflow, and then all of these in Space Exploration SE, and then all of these in Astronomy SE!


text:
Q: ElasticSearch/Kibana: how to aggregate similar type of pages Brand new kibana user, I am trying to track the usages on my site.
I have some pages in the follow type of url:
https://example.com/services/{serviceId}/users

so the serviceId changes for each service, however I want to see how many people are going to the /users page of their service.
Is there a way to aggregate the count of that?

A: Assuming that url is a multi-field type, you have the below mapping:
PUT my_url_index
{
  "mappings" : {
    "properties" : {
      "url" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          }
        }
      }
    }
  }
}

Sample Docs:
POST my_url_index/_doc/1
{
  "url": "https://example.com/services/101/users"
}

POST my_url_index/_doc/2
{
  "url": "https://example.com/services/asdasd/users"
}

POST my_url_index/_doc/3
{
  "url": "https://example.com/services/555/users"
}

POST my_url_index/_doc/4
{
  "url": "https://example.com/users/4444/create"
}

Note that I'm assuming you only one variation of URL where you have both services and user tokens in it.
This below query should help you get the total count as well as the count like how many times each user has been going:
POST my_url_index/_search
{
  "size": 0,
  "query": {
    "query_string": {
      "query": "(services) AND (users)",
      "fields": ["url"]
    }
  },
  "aggs": {
    "my_users": {
      "terms": {                          <----- Note the logic mentioned here
        "script": {
          "source": "doc['url.keyword'].toString().substring(30, doc['url.keyword'].toString().indexOf('/users'));"
        },
        "size": 10
      }
    }
  }
}

Response:
{
  "took" : 336,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 3,                             <---- total count
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {                           <----- count of each user
    "my_users" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "101",
          "doc_count" : 1
        },
        {
          "key" : "555",
          "doc_count" : 1
        },
        {
          "key" : "asdasd",
          "doc_count" : 1
        }
      ]
    }
  }
}

Let me know if this helps and if you are looking for anything else.


text:
Q: "Are you sure you want to leave this page?" functions for cancel and OK i'm trying to do something similar to some websites where you leave and it'll display a popup saying "Are you sure you want to leave this page" and with two options saying "Cancel" and "OK".
How would I do that and make it so when you click "Cancel" it'll just cancel the box and when they click "OK" it'll do a 'leaveChat();' function and leave the website?
I've tried using the onbeforeunload which was working but i'm not sure on the function part.
Thanks for the help!

A: There is no way to do that.
You can try sending the AJAX request in onunload, but I don't think that will work reliably.

A: To pop a message when the user is leaving the page to confirm leaving, you just do:

To call a function:

A: here is my html
<!DOCTYPE HMTL>
<meta charset="UTF-8">

<title>Home</title>

        Welcome To My Home

        I am a student at Columbia College of Missouri.

And so this is how I did something similar in javaScript
var myGlobalNameHolder ="";

function myFunction(){
var myString = prompt("Enter a name", "Name Goes Here");
    myGlobalNameHolder = myString;
    if (myString != null) {
        document.getElementById("replaceME").innerHTML =
        "Hello " + myString + ". Welcome to my site";

        document.getElementById("belong").innerHTML =
        "A place you belong";
    }
}

// create a function to pass our event too
function myFunction2(event) {
// variable to make our event short and sweet
var x=window.onbeforeunload;
// logic to make the confirm and alert boxes
if (confirm("Are you sure you want to leave my page?") == true) {
    x = alert("Thank you " + myGlobalNameHolder + " for visiting!");
}
}


text:
Q: Why xor operation on constants (character) is working differently when used variables in its place Have a look at the following code :
Case 1 :
char a = 'x' ^ 'y';

It is working fine.
But when I use variable instead of constants as here :
Case 2:
char x = 'x';
char y = 'y';
char a = x ^ y; // Error!

In java language : case 1 is working and value of a comes out to be 1 but case 2 is not working.
In C and C++ : both cases are working, and the value of a comes out to be 1
In C# : both the cases are not working.
In javascript : both cases are working, which is not a HLL, and value of a comes out to be 0.

I understand that java is converting variables to integer to do binary operation, but why it is working in case 1 and not in case 2, Why same is not working in C# And why the values are different in the case of javascript.
Updated
When I made the variables final than it is working in java, but still not in C#
final char x = 'x';
final char y = 'y';
char a = x ^ y;

But still I cannot understand why constants are working but when using variable they are not. And why same is not happening with other high level programming language.
I think it is a basic operation and should be working in all programming languages with same behaviour.

Note To test all above cases in javascript I am replacing 'char' with 'var' in all cases and they are working.

A: Answering for Java only.
The expression 'x' ^ 'y' is a constant expression; x ^ y is not, unless both variables are declared final. Furthermore, the result is an int; ^ is an integral bitwise operator, meaning that both operands have to be promoted to an integral type before being evaluated. char promotes to int.
So you have this int expression, and you try to narrow it to a char. In the general case, this could lead to a loss of precision (ints are 4 bytes, chars are 2), so the compiler doesn't let you do that without you explicitly stating it's what you want to do (via a cast to char). However, you can implicitly narrow constant expressions, if their value would fit into the new type. From JLS 5.2:

*

*A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

(Emphasis added)
Intuitively, this makes total sense: the error is there to tell you that you may lose precision, and so it wants you to confirm that you know that; in a sense, it's a loud warning. But if the compiler can know absolutely that this won't happen, as it can for a constant expression, then it makes things a bit easier for you and "hides" that warning.

A: I will consider C languages that is C, C++ and C#.
In C# there is no implicit conversion from an integral type to type char. According to section "11.1.5 Integral types" of the ECMA 334 Standard "C# Specification"

• There are no implicit conversions from other types to the char type.
  In particular, even though the sbyte, byte, and ushort types have
  ranges of values that are fully representable using the char type,
  implicit conversions from sbyte, byte, or ushort to char do not exist.

So you need explicitly to cast the result of the operator to type char. For example
using System;

namespace ExclusiveOr
{
    class Program
    {
        static void Main(string[] args)
        {
            char a = ( char )('x' ^ 'y' );
            char c = 'x', d = 'y';
            char b = ( char )( c ^ d );

            Console.WriteLine("a = {0}, b = {1}", (int)a, (int)b);
        }
    }
}

The output is
a = 1, b = 1

According to the C Standard (section 6.7.9 Initialization)

4 All the expressions in an initializer for an object that has static
  or thread storage duration shall be constant expressions or string
  literals

So for example this code will be compiled
#include <stdio.h>

char a = 'x' ^ 'y';

int main(void)
{
    printf( "a = %d\n", a );

    return 0;
}

The output is
a = 1

However this code will not be compiled
#include <stdio.h>

char c = 'x';
char d = 'y';

char b = c ^ d;

int main(void)
{
    printf( "b = %d\n", b );

    return 0;
}

will not be compiled. The GCC compiler will issue error
prog.c:8:1: error: initializer element is not constant  char b = c ^ d;
However if you will make varaible b local then the code will be compiled successfully
#include <stdio.h>

char c = 'x';
char d = 'y';

int main(void)
{
    char b = c ^ d;
    printf( "b = %d\n", b );

    return 0;
}

The output is
b = 1

In C++ there is no such a restriction for objects with the static storage duration so all examples of programs similar to C programs showed above will be compiled.

A: Under normal circumstances, the operands of the following binary operators are "widened" before the operation is performed.
(From the JLS 5.6.1)

*

*The multiplicative operators *, /, and % (§15.17)

*The addition and subtraction operators for numeric types + and - (§15.18.2)

*The numerical comparison operators <, <=, >, and >= (§15.20.1)

*The numerical equality operators == and != (§15.21.1)

*The integer bitwise operators &, ^, and | (§15.22.1)

*In certain cases, the conditional operator ? : (§15.25)
In the case of char operands, widening will convert the operands to int.
For the arithmetic and bitwise operations, the type of the operation's result is the same as the "wider" of the two operands.
When x and y have type char, the expression x ^ y gives you an int value.  That can't be assigned back to a char without a type cast, and hence you get a compilation error.

For the case where you are using char literals, the same widening process happens.  But there is a "special exception" in the language which allows the value of a constant expression to be implicitly narrowed, provided that the constant expression's value will fit into the type.  In this case, 'x' ^ 'y' will "fit" into a char, so the assignment is allowed.
The JLS reference for this exception for constant expressions is JLS 5.2.


text:
Q: What's the proper way to work with assets in Yii? I notice that Yii creates strange set of directories (names like 8523d23 or 10s89b92) in assets directory, and this even happens at runtime. For example, one of my tables got more than 10 records, pagination kicked-in and I got a new files in assets subdirectory named pager.css.
When I move my site from testing to production, should I copy all those, or just create an empty "assets" directory, and it will be filled at runtime?
If I want to add, for example, some new jQuery plugin, how should I proceed?
For example, I wish to add jquery.charcounter.js, do I copy it to assets or to yii/framework/web/js/source? If I do the latter, how do I get this .js file included in HTML page output?

A: This would resolve the query as this provides detailed explanation for the assets folder:
http://www.yiiframework.com/wiki/148/understanding-assets/

A: assets should be a writable directory. Yii takes care of assets.
By calling Yii::app()->assetManager->publish() some stylesheets, images, scripts, or even entire directories can be put into a web-visible folder.
pager.css and other non-familiar files are produced by widgets (CLinkPager for example) and other components (such as CClientScript publishes jQuery whenever you need that).
During deployment, this folder should be empty, but it doesn't really matter.
Adding plugins should never be done through framework folders. You can place them either in components dir and publish it runtime if necessary, or into any other convenient visible directory (like as images or css).
Update
To embed jquery.charcounter.js, put it in components directory, then call
Yii::app()->clientScript->registerScriptFile(
    Yii::app()->assetManager->publish(
        Yii::getPathOfAlias('application.components').'/jquery.charcounter.js'
    ),
    CClientScript::POS_END
);

Regarding weird folder names, I firmly believe they are unique hashes (or part of), so they can be differentiated if application uses several extensions.


text:
Q: How to stop css dropdown menu from overlapping footer? I'm trying to make a responsive navigation menu with dropdowns, but the mobile navigation dropdowns overlap the footer. How can I make it so that the dropdowns push the footer down instead of overlapping it?

@font-face {
    font-family: 'FairydustB';
    }

    body {
    margin: 0;
    padding: 0;
    background: gainsboro;
    font-size: 1em;
    }

    header {
    width: 100%;
    height: 64px;
    margin: 0;
    padding: 0 0 4px 0;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 100;
    background: white;
    box-shadow: 0 1px 16px gray;
    }

    #logo {
    width: 10%;
    display: inline;
    margin: 0 0 0 10%;
    padding: 0 0 8px 0;
    float: left;
    text-align: right;
    font-family: 'FairydustB';
    font-size: 3em;
    text-decoration: none;
    border: none;
    }

    #logo:hover {
    background: white;
    }

    .red {
    color: red;
    }

    .green {
    color: limegreen;
    }

    nav {
    width: 60%;
    float: right;
    margin: 24px 20% 0 0;
    padding: 0;
    font-family: sans-serif;
    }

    ul {
    display: flex;
    justify-content: space-between;
    margin: auto;
    padding: 0 96px;
    list-style: none;
    }

    li {
    display: inline-block;
    margin: 0px;
    padding: 0px;
    }

    a {
    margin: 0;
    padding: 23px;
    color: gray;
    text-decoration: none;
    font-size: 1em;
    }

    a:hover {
    background: honeydew;
    color: limegreen;
    }

    #menu-icon {
    display: none;
    }

    .dropmenu {
    display: none;
    position: relative;
    margin: 0;
    padding: 0;
    background-color: white;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.1);
    }

    .dropmenu a {
    padding: 16px;
    display: block;
    text-align: left;
    }

    .dropdown:hover .dropmenu {
    display: block;
    background: azure;
    }

    footer {
    display: block;
    width: 100%;
    height: 64px;
    position: fixed;
    bottom: 0;
    left: 0;
    margin: 0;
    padding: 0;
    position: fixed;
    background: white;
    }

    @media only screen and (max-width : 880px) {
    #logo {
        width: 20%;
        margin: 0 0 0 16px;
    }

    nav {
        width: 60%;
        float: left;
        margin: 24px 0 0 0;
        padding: 0;
        font-family: sans-serif;
    }

    ul {
        display: flex;
        justify-content: space-between;
        margin: auto;
        padding: 0 32px;
        list-style: none;
    }
    }

    @media only screen and (max-width : 800px) {

    header {
        position: fixed;
    }

    #logo {
        width: 70%;
        display: block;
        margin: 0;
        padding: 8px 0 12px 16px;
        float: left;
        text-align: left;
        font-size: 2.5em;
    }

    div {
        margin: 0 0 0 0;
        padding: 12px 0 0 0;
    }

    #menu-icon {
        display: block;
        width: 25%;
        height: 57px;
        position: fixed;
        top: 0;
        right: 0;
        list-style: none;
        background: limegreen;
    }

    .menu-bar {
        display: block;
        width: 32px;
        height: 4px;
        margin: 8px auto;
        padding: 0;
        text-align: center;
        background: white;
    }

    .menu-bar a {
        display: none;
    }

    nav ul {
        display: inline-block;
        position: fixed;
        right: 0;
        top: 68px;
        width: 80%;
        float: right;
        margin: 0 auto 16px auto;
        padding: 0;
        background: white;
    }

    nav li {
        display: block;
        margin: 0;
        padding: 0;
        text-align: left;
        background: white;
        border: 1px solid skyblue;
    }

    nav a {
        display: block;
        color: black;
        text-decoration: none;
    }

    nav:hover ul {
         display: block;
         background: white;
    }
    }

        RedGreen

.

.

.

HOME

QUESTIONS

                        LINK
                        LINK
                        LINK

PHILOSOPHY

                        LINK
                        LINK
                        LINK

HISTORY

                        LINK
                        LINK
                        LINK

ABOUT

LINK

LINK

LINK

LINK

LINK

A: Your footer has position: fixed which takes it out of the normal page flow so it doesn't "reserve" space on the page. You need to change the footer to position: relative so it isn't removed from the page flow.

A: Move the footer links out of nav and into a div

LINK

LINK

LINK

LINK

LINK


text:
Q: Rational homotopy groups of $S^2\vee S^2$ From what I understand $\pi_n(S^2\vee S^2)\otimes\mathbb{Q}\neq 0$ for $n\geq 2$. My question is:

Is there a "hands-on" proof of this fact using differential forms?

I am sure I will receive answers like: that is Hilton's theorem or use Sullivan's minimal model or check the section in Bott and Tu about the rational homotopy theory.
However, all these answers are useless for me because I am an analyst and not topologist and in order to use this fact in my research I need a straightforward construction that I could use to get integral estimates of forms.
Rational homotopy theory of Sullivan is build on differential forms and you can represent elements in rational homotopy using the Hopf-Novokov integral as explained in:
Hardt, Robert; Rivière, Tristan Connecting rational homotopy type singularities. Acta Math. 200 (2008), no. 1, 15–83.
The points is that I do not really understand what they do and I do not even know if their machinery can be used to answer my question. Thus I am asking if there is a simple way to prove the result I am quoting using integration of differential forms.
To be more precise:

One can use differential forms to prove that $\pi_{4n-1}(S^{2n})\neq 0$ and that can be explained on a couple of pages with all details. Is there a similar proof of the fact I mentioned?

A: Ryan's answer generalizes. I prefer $\iota_1, \iota_2$ for the inclusions of wedge summands, and then $\omega_1, \omega_2$ for forms which generate cohomology supported on each of the wedge summands.  Then I claim that a numerical homotopy invariant which evaluates non-trivially on $[[\cdots[\iota_1,\iota_2],\iota_2],\cdots],\iota_2]$ is
$f \mapsto \int_{S^n}  d^{-1} \left( \cdots d^{-1} \left( d^{-1} \left(d^{-1} f^*(\omega_1) \wedge f^*(\omega_2)) \wedge f^*(\omega_2) \right) \wedge f^*(\omega_2) \right) \cdots \right) \wedge f^*(\omega_2),$
where each $d^{-1}$ denotes a choice of some form to cobound what is in each case a closed and thus exact form of degree less than $n$ on $S^n$.  (As Sullivan and others point out, such choices can be made universally through  a constructive proof of the Poincare Lemma.)  Since there is such a Whitehead product in every degree greater than or equal to two, this claim answers the Question.
The proof that this integral is homotopy invariant is elementary, along the lines which Ryan gives in the example of his answer.  There is also probably a more direct "hands-on" proof that this integral evaluates to one on the Whitehead product given, but I am going to cite my work with Ben Walter, namely
https://arxiv.org/abs/0809.5084
(not the paper Ryan linked to, though I appreciate his seeing the relevance of our ideas).  This integral is a case of a Hopf invariant, which is the main object of study of the paper.  This integral is the Hopf invariant associated to the element of the bar construction $|\omega_1|\omega_2| \omega_2| \cdots |\omega_2|$.  To see it evaluates as claimed I prefer to use the bracket-cobracket compatibility theorem, namely Theorem 1.12 of the paper, from which this is quick inductive combinatorics.   While the present MO answer is thus not self-contained, note that Theorem 1.12 occurs just on page 7, and I would call its proof "hands-on".
The cited paper was written to solve exactly these types of questions.  We give an algorithm called weight reduction which can be used to associate integral(s - non-unique) to any cycle in the (Lie coalgebraic) bar construction on the cochains (forms), which are homotopy periods.  This association defines an isomorphism between the homology of this bar construction and the linear dual of homotopy.  Though Sullivan in his seminal paper pointed to how one can produce complete rational homotopy periods (I wish we could call this "rational cohomotopy") through minimal models, what Ben and I find is that the Quillen functor approach is, perhaps surprisingly, more readily tied to geometry.  The general principle which follows from our work is that one can detect all rational homotopy through numerical invariants which are "higher linking with correction," governed by the Lie coalgebraic bar construction.  Thus, geometry, combinatorics, algebra and functorial formalism all work together as well as one could hope for in giving a sharp resolution to the homotopy periods question in the simply connected setting.  (The non-simply connected case is ongoing research that I am having PhD students work on.)  And as Ryan says, I have recorded lectures on this subject.  The best place to see a summary of and links to the lectures is here
https://pages.uoregon.edu/dps/GeometricAlgebraicTopology/
The first three lectures cover these Hopf invariants.

A: Piotr, I think the question you really want to ask is:

Given a map $f:S^n \to S^2 \vee S^2$, how do I prove that it is homotopically nontrivial?

This is the so-called homotopy period problem, and it has several solutions.  I'll outline one way.
Every simply connected compact manifold (or cellwise smooth complex) $X$ has a Sullivan minimal model $\mathcal M_X$, which is a free, minimal differential graded algebra:

*

*a differential graded algebra is a chain complex with a graded commutative multiplication satisfying the graded Leibniz rule (for example, the differential forms on a space)

*it is free as a graded-commutative algebra (so for example, the powers of a generator are zero iff the generator is in odd degree)

*it is minimal if indecomposable elements (linear combinations of generators) are never coboundaries.

The cohomology ring of $\mathcal M_X$ is the de Rham cohomology ring of $X$.  Moreover there is an algebra homomorphism $m_X:\mathcal M_X \to \Omega^*X$ which induces an isomorphism on cohomology.
In the case of spheres and wedges of spheres, because the cohomology is concentrated in one dimension, this completely pins down $\mathcal M_X$—there are no choices involved in constructing it.  So for example, for $S^n$, you have to start with one $n$-dimensional generator $x$ and $m_{S^n}(x)=\omega$ can be any form that integrates to 1 over $S^n$.  Now if $n$ is odd, $x^2=0$ and we're done, $\mathcal M_{S^n}=\mathbb{R}\langle x \rangle$ and $m_{S^n}$ induces an isomorphism on cohomology.  If $n$ is even, $x^2$ is nonzero, and so in order to induce an isomorphism on cohomology we have to kill it.  That means there's also a $(2n-1)$-dimensional generator $y$ with $dy=x^2$.  Now of course $m_{S^n}(x^2)=0$ so we can set $m_{S^n}(y)=0$ as well.
It turns out that the indecomposables in degree $k$ are naturally isomorphic to $\operatorname{Hom}(\pi_k(X),\mathbb{R})$.  So if you're willing to assume this, we've proved that $\pi_{4n-1}(S^{2n})$ is nontrivial.  Now the question is, how do you detect it, for a map $f:S^3 \to S^2$?  Of course you already know the answer to this, but I want to give a slightly different answer.
This $f$ is homotopically trivial if and only if it extends to $D^4$.  Now Sullivan tells us that asking if $f$ extends to $D^4$ is the same as asking if the map $f^*m_{S^2}:\mathcal M_{S^2} \to \Omega^*(S^3)$ lifts to $\Omega^*(D^4)$.  One such lift would of course be $F^*m_{S^2}$, for a genuine filling $F:D^4 \to S^2$, but there could be many lifts that don't come from such a filling.  For example, a lift which comes from a filling will always send the 3-dimensional generator $y$ to $0$, but a general lift need not do that.
How do you construct a lift $\phi$?  Well, first you extend the form $f^*m_{S^2}(x)$ to a closed form $\phi(x)$ on $D^4$.  There is no obstruction to doing this, by the Poincaré lemma.  However, now $\phi(x)^2$ might not be zero, and we need a $\phi(y)$ such that $\phi(y)|_{S^3}=0$ and $d\phi(y)=\phi(x)^2$.  You can build such a $\phi(y)$ if and only if $\int_{D^4} \phi(x)^2=0$.  This $\int_{D^4} \phi(x)^2$ is the Hopf invariant.  (This formula is related to the Whitehead formula via Stokes' theorem.)
Now $\mathcal M_{S^2 \vee S^2}$ is going to be much more complicated.  You start by making sure that you have the right cohomology in degree 2, so you introduce two indecomposable generators $x_1$ and $x_2$.  But now $\mathbb{R}\langle x_1,x_2 \rangle$ has cohomology in degree $4$ generated by $x_1^2, x_2^2, x_1x_2$, and you have to kill all of it by adding generators in degree $3$.  Then that generates more cohomology in degree $5$ and you kill it by adding generators in degree $4$.  And you just keep going, so it looks like this:
$$\begin{align*}x_1, x_2 &\mid dx_1=dx_2=0 \\
y_{11},y_{12},y_{22} &\mid dy_{ij}=x_ix_j \\
z_1, z_2 &\mid dz_1=x_1y_{12}-x_2y_{11},dz_2=x_2y_{12}-x_1y_{22} \\ \vdots &\mid \vdots\end{align*}$$
(I might have gotten the signs wrong in the last row.)
But if someone gives you a map $f:S^n \to S^2 \vee S^2$, the resulting map $f^*m_{S^2 \vee S^2} \to \Omega^*S^n$ is still very simple: it sends $x_1$ and $x_2$ to the pullbacks of the volume forms on the two spheres, and everything else to zero.  Now if you want to know whether your map is (rationally) trivial, you check if it can be extended "formally" to $D^{n+1}$, that is, whether there is a map $\phi:\mathcal M_{S^2 \vee S^2} \to \Omega^*D^{n+1}$ whose restriction to $\Omega^*S^n$ is $f^*m_{S^2 \vee S^2}$.  So in the case of $S^4$, it goes like this:

*

*You extend $f^*m_{S^2 \vee S^2}x_i$ to $\phi(x_i) \in \Omega^*D^5$.  There's no obstruction.

*You find primitives for $\phi(x_1)^2$, $\phi(x_1)\phi(x_2)$, and $\phi(x_2)^2$.  There's no obstruction to doing this, and those are going to be your $\phi(y_{ij})$'s.

*Now you have 5-forms $\phi(x_1y_{12}-x_2y_{11})$ and $\phi(x_2y_{12}-x_1y_{22})$ which are zero on the boundary $S^4$.  The obstructions to finding primitives for these that are zero on the boundary are their integrals over $D^5$.  Sullivan's theory says that these will be the same no matter how you chose the $\phi(y_{ij})$.

*Now there are infinitely many additional generators of $\mathcal M_{S^2 \vee S^2}$, but luckily all their differentials are in degrees $\geq 6$, and therefore automatically go to zero under a map to $\Omega^*D^5$.  So if there's no obstruction corresponding to 4-dimensional generators, we can send the generators in higher degrees to zero and be done.

The 5-dimensional obstructions are the equivalent of the Hopf invariant in this situation.  Using Stokes' theorem repeatedly, you can also come up with an obstruction that lives entirely in $S^4$, just using primitives without extensions.  But that's a bit harder to describe.
If you want to understand the proofs of these statements, I recommend Griffiths and Morgan's book.  Section 3 of my paper "Plato's cave and differential forms" also contains a summary.
Addendum: The only things I really used about smooth forms in the above arguments are (1) the fact that they form a graded commutative DGA and (2) the Poincaré lemma.  So if you want to think about other types of cochains, you can do that as long as they satisfy those two properties.  In my work I have sometimes used flat forms instead of smooth ones.

A: Here is an example of how to detect elements of $\pi_5 (S^2 \vee S^2)$.
Let $\omega_i : S^2 \to S^2 \vee S^2$ be the inclusion of the $i$-th wedge summand.  Then how do we detect $[[[\omega_1,\omega_2],\omega_2],\omega_2] \in \pi_5 (S^2 \vee S^2)$? where here the bracket is the Whitehead bracket notation.
Given a map $f : S^5 \to S^2 \vee S^2$, take the pre-image of a point in either wedge summand (away from the wedge point).  Generically this is a pair of disjoint framed $3$-manifolds in $S^5$. These framed manifolds are null-cobordant (for a generic map they would be torsion, but for our Whitehead bracket they are null).  That said, even though they are null, they may not be disjointly null.   Call the first manifold $M_1$ and the 2nd $M_2$.
So we have framed $4$-manifolds $W_1$ and $W_2$ with $\partial W_i = M_i$.  If we use the notation $\delta M_i$ to denote a manifold whose boundary is $M_i$, i.e. the symbol means `a choice of cobounding manifold' then we could write $\delta M_i = W_i$.  The generalized linking number we want to use to detect the non-triviality of the homotopy-class $[[[\omega_1, \omega_2], \omega_2], \omega_2]$ is:
$$\delta(\delta(\delta M_1 \cap M_2) \cap M_2) \cap M_2$$
i.e. we are computing this as a signed intersection number.  Since $M_i$ is $3$ dimensional $\delta M_i$ is $4$-dimensional, so $\delta M_1 \cap M_2$ is $2$-dimensional, etc, one follows through the dimension argument and one sees the above intersection is a framed $0$-dimensional manifold, which up to cobordism is an integer.
I think if you were to put this into the language of differential forms, given a map $f : S^5 \to S^2 \vee S^2$, let $w_1, w_2$ be the area forms of the two $S^2$ wedge summands, then one computes
$$\int_{S^5} \delta \left( \delta \left( \left( \delta f^* w_1 \right) \wedge f^* w_2 \right) \wedge f^* w_2\right) \wedge f^* w_2$$
Where here $\delta$ denotes the dual to the `cobounding' operation, i.e. one is applying the Poincar'e Lemma to find an exterior anti-derivative.
So this is one integral that detects a very specific homotopy-class $S^5 \to S^2 \vee S^2$.
edit:
Regarding how to verify these statements, as Dev mentions, there are complete proofs in his paper.  I think verifying the above statement about the higher linking numbers, expressed in terms of intersections of cobounding manifolds; the geometry behind these statements basically boil down to understanding the standard surgery decompositions of the sphere, i.e. $S^{n-1} \simeq S^{i-1} \times D^j \cup D^i \times S^{j-1}$ where $i+j=n$.
I think the differential form computations proceed similarly, using these standard surgery decompositions -- as the Whitehead products are basically defined in terms of these canonical surgery decompositions of spheres.  The advantage to the intersection-theory approach is you can easily avoid technical issues in regard to the wedge point.  Off the top of my head the forms approach seems a bit more technical to me, in that you need to use explicit collapse maps $D^n \to S^n$, in order to pull-back the volume forms.  Other than that, the computation should be fairly mechanical.


text:
Q: Error 3031 - not a valid password I am trying to access an MDB file via VB6 and receiving:
Error 3031 - not a valid password

What is the likely cause?  I believe I am sending the correct password of the file yet it produces this error.

A: CAUSE:
When you manually set the database password to a password with fourteen characters (the limit), you cannot use that same password to programmatically open the database
SOLUTION:
1:
Do not select a password that is longer than 13 characters if you need to open the database programmatically.
2:
When you open the database programmatically, you need only include the first 13 characters of the database password.
To make the example in the "Steps to Reproduce Problem" section work, change the following line of code
Set db = ws.OpenDatabase _
("C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb", _
False, False, "MS Access;PWD=FourteenCharac")

to read as follows:
Set db = ws.OpenDatabase _
("C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb", _
False, False, "MS Access;PWD=FourteenChara")

NOTE: This will programmatically open the Northwind.mdb database even though the password is not correct.


text:
Q: If two maps induce the same homomorphism on the fundamental group, then they are homotopic This is exercise 15.11(d) in C. Kosniowsky book A first course in algebraic topology:

Prove that two continuous mappings  $\varphi,\ \psi:X\to Y$, with $\varphi(x_0)=\psi(x_0)$ for some point $x_0\in X$, induce the same homomorphism from $\pi(X,x_0)$ to $\pi(Y,\varphi(x_0))$ if $\varphi$ and $\psi$ are homotopic relative to $x_0$.

Which is easy to solve. We were asked to prove the converse but, is it true to begin with? If so, is it an standar exercise or thought one?

A: Hint: Consider $\phi\colon S^2\to S^2$ the identity map.


text:
Q: flutter convert image File into data:image/jpeg;base64,/9j/4AA     final bytes = Io.File(file.path).readAsBytesSync();
    String img64 = base64Encode(bytes);
    String img642 = base64.normalize(img64);
    print("img64 => $img642");

i get result iVBORw0KGgoAAAANSUhEUgAAAbAAAAN1CAYAAAAe9K4EAAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAACAASURBVHic7L3nk2THma/3ZOYx5au97/EGg5kBBgABEPT+cnd5797dq5Bu6Js+6a9ShBShkEIr3b1LriNBwhAegxmMNz2+x7Tv8ua4zNSHU90zMIQnyN49D2LQ3VXVp6uzqvOXb76/901hrbVkZGRkZGTsMOSf+glkZGRkZGR8ETIBy8jIyMjYkWQClpGRkZGxI8kELCMjIyNjR5IJWEZGRkbGjiQTsIyMjIyMHUkmYBkZGRkZO5JMwDIyMjIydiSZgGVkZGRk7EgyAcvIyMjI2JFkApaRkZGRsSPJBCwjIyMjY0eSCVhGRkZGxo4kE7CMjIyMjB1JJmAZGRkZGTuSTMAyMjIyMnYkmYBlZGRkZOxIMgHLyMjIyNiRZAKWkZGRkbEjyQQsIyMjI2NHkglYRkZGRsaOJBOwjIyMjIwdSSZgGRkZGRk7kkzAMjIyMjJ2JJmAZWRkZGTsSDIBy8jIyMjYkWQClpGRkZGxI8kELCMjIyNjR5IJWEZGRkbGjiQTsIyMjIyMHUkmYBkZGRkZO5JMwDIyMjIydiSZgGVkZGRk7EgyAcvIyMjI2JFkApaRkZGRsSPJBCwjIyMjY0eSCVhGRkZGxo4kE7CMjIyMjB1JJmAZGRkZGTuSTMAy/mhYa//UTyEjI+PfMM6f+glk/NvBWkuSJERRRJIkGGNwHAfP83BdFymz9VJGRsZXRyZgGV8JSaLp9XrU63VWV1dpNJtok1AqlRkdGWFqcpJyuYzjOAgh/tRPNyMj498AmYBlfCnSqEuzubnJnTt3uHz5ChcuXGBldRWEoVqtsnfvXp55+mmOHDnC6Mgovu9nIpaRkfGlyQQs4wtjjKHX7bKyusKZM6e5fOkS9+7dpV6vE8URSgmioEWntUmjtsrS0l0OHzrMvv0HGR0
how to get result with format ?
data:image/jpeg;base64,/9j/4AA .........
i want send this format to send email image.. with html
    final bytes = Uint8List.fromList(file.readAsBytesSync());
    var decodedImage = await decodeImageFromList(file.readAsBytesSync());
    print("height-widht ${decodedImage.height}, ${decodedImage.width}");
    var dataUrl = Uri.dataFromBytes(
      bytes,
      // mimeType: 'application/octet-stream',
    ).toString();
    print("dataUrl $dataUrl");

i got height from print
height-widht 885, 432
but when i put result in <img src="" it's only show height my be 20..

my complete code
final directory = await getApplicationDocumentsDirectory();
String filename =
'${directory.path}/${orderCtrl.orderDetail.first.id}_${generateRandomString(5)}.png';
final imagePath = await File(filename).create();
await imagePath.writeAsBytes(image);
print(filename);
File file = File('${filename}');
    final bytes = Uint8List.fromList(file.readAsBytesSync());
    var decodedImage = await decodeImageFromList(file.readAsBytesSync());
    print("height-widht ${decodedImage.height}, ${decodedImage.width}");
    var dataUrl = Uri.dataFromBytes(
      bytes,
      // mimeType: 'application/octet-stream',
    ).toString();
    print("dataUrl $dataUrl");

      String img64 = base64UrlEncode(bytes);
      print("img64 => $img64");
      String img642 = base64.normalize(img64);
      print("img642 => $img642");
      String img6421 = "data:image/jpeg;base64,${base64.normalize(img64)}";

      print(img6421);
    Get.dialog(Column(
      children: [
        Expanded(
          child: Container(
            child: SingleChildScrollView(
              child: Container(
                  padding: EdgeInsets.all(10),
                  color: Colors.yellow,
                  child: Image.memory(base64Decode(img642))),
            ),
          ),
        ),
        // Image.file(file),
      ],
    ));

in dialog is show but base64 i just get litte height of picture

A: String img642 = "data:image/jpeg;base64,${base64.normalize(img64)}";

print(img642);

//result
data:image/jpeg;base64,VBORw0KG...


text:
Q: I want to use [\alert] in [ColorVerbatim] in latex I can use \alert<number>{...} outside of ColorVerbatim.
When I write \alert<number>{...} inside of ColorVerbatim, the text <number>... is colored in red.
How can I use \alert<number>{...} properly inside of ColorVerbatim?


text:
Q: How to Pivot one columns multiple times? A table is
  ID  YEAR Name   Value

  1    2014  A     10
  2    2014   B    20
  1    2013   A     30

Want a table like below:
 ID  2014   2013   A  B
 1    10    20    40  0

 2    20     0    0    20

Bascially want to Pivot Value column for both Year and Name. How can I do this?

A: I would do this with conditional aggregation:
select id,
       sum(case when year = 2014 then value else 0 end) as [2014],
       sum(case when year = 2013 then value else 0 end) as [2013],
       sum(case when name = 'A' then value else 0 end) as [A],
       sum(case when name = 'B' then value else 0 end) as [B]
from table t
group by id;

A: Here is the way using pivot
SELECT id,
       Isnull([2014], 0) [2014],
       Isnull([2013], 0) [2013],
       Isnull([A], 0)    [A],
       Isnull([B], 0)    [B]
FROM   (SELECT *,
               Sum(value)OVER(partition BY Name) tot
        FROM   Yourtable) a
       PIVOT (Max(Value)
             FOR year IN ([2014],
                          [2013]))pv
       PIVOT (Max(tot)
             FOR name IN ([A],[B]))pv1

SQLFIDDLE DEMO


text:
Q: If $H$ and $K$ are normal subgroups of $G$ and $H \cong K$, prove that $G/H \cong G/K$. It is natural.
But I want to prove exactly.
My idea is to use isomorphism theorem.
Let $f: G \to G/H$ be the quotient map,
 then $f$ is a homomorphism and obviously surjective.
Hence, I just need to show $\ker(f) = K$.
However, I couldn't find the way.
Definitely, $\ker(f) = H $ and $H  \cong K$
But I can say $\ker (f) = K$.
How to prove it?

A: This is not true.  Consider $G=\mathbb{Z}_2\oplus\mathbb{Z}_4$, $H=\langle (1,0)\rangle$, and $K=\langle (0,2)\rangle$.


text:
Q: Need help to configure Resource Adapter in Jboss EAP 6.4 I am doing jboss migration from Jboss4.x to Jboss 6.4 and current version Jboss 4.x configured connection factories to communicate mainframe and working so I try to doing same thing to migrate Jboss 6 configuration using resource adapter. But I getting exception(). I do not know what I am missing.
Current JBoss 4.x configuration
jracappstest-ds.xml
<connection-factories>
                <no-tx-connection-factory>

                <jndi-name>eis/JracRa/AppslinkTest</jndi-name>
                <rar-name>unisys-jrac-connector-3.0.0.rar</rar-name>

                <connection-definition>
                    javax.resource.cci.ConnectionFactory
                </connection-definition>

                <config-property name="ServerName" type="java.lang.String">
                    TEST
                </config-property>
                <config-property name="PortNumber" type="java.lang.String">
                    6666
                </config-property>
                <config-property name="WindowName" type="java.lang.String">
                    TEST_NAME
                </config-property>

                <security-domain>jca-credentials</security-domain>

                <idle-timeout-minutes>20</idle-timeout-minutes>

                <min-pool-size>2</min-pool-size>
                <max-pool-size>10</max-pool-size>

            </no-tx-connection-factory>
        </connection-factories>

Exception
Caused by: javax.naming.NameNotFoundException: eis/JracRa/AppsTest -- service jboss.naming.context.java.jboss.eis.JracRa.AppsTest
        at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:104)
        at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:197)
        at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:174)
        at org.jboss.as.naming.InitialContext$DefaultInitialContext.lookup(InitialContext.java:245)
        at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:183)
        at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:179)
        at javax.naming.InitialContext.lookup(InitialContext.java:411) [rt.jar:1.7.0_45]
        at javax.naming.InitialContext.lookup(InitialContext.java:411) [rt.jar:1.7.0_45]
        at com.myapp.utils.unisys.connection.MainframeRA.lookupConnectionFactory(MainframeRA.java:292) [mainframe-ra-2.2.0.jar:]
        at com.myapp.utils.unisys.connection.MainframeRA.initializeConnectionFactory(MainframeRA.java:249) [mainframe-ra-2.2.0.jar:]
        ... 41 more

Code
private ConnectionFactory lookupConnectionFactory()
        throws NamingException {

        final Context initContext = new InitialContext();
        final String jndiName = "java:jboss/"
            + UnisysDataSource.getInstance().lookupJndiName(targetRegionValue);
        return (onnectionFactory) initContext.lookup(jndiName);

    }

configured in standalone.xml
<subsystem xmlns="urn:jboss:domain:resource-adapters:1.1">

            <resource-adapters>

                <resource-adapter id="unisys-jrac-connector-3.0.0.rar">

                    <archive>
                        unisys-jrac-connector-3.0.0.rar
                    </archive>

                    <transaction-support>NoTransaction</transaction-support>

                    <connection-definitions>
                        <connection-definition class-name="javax.resource.cci.ConnectionFactory" jndi-name="java:jboss/eis/JracRa/AppsTest" use-java-context="true" pool-name="eis/JracRa/AppsTest">

                            <config-property name="UserName">
                                TEST
                            </config-property>
                            <config-property name="WindowName">
                                TEST_NAME
                            </config-property>
                            <config-property name="PortNumber">
                                6666
                            </config-property>
                            <config-property name="ServerName">
                                server_name
                            </config-property>
                            <config-property name="Password">
                                TEST_PASS
                            </config-property>
                        </connection-definition>

                </resource-adapter>

            </resource-adapters>

 </subsystem>


text:
Q: check if variable undefined Need to check if an array item at a specific index contains a value.  The array index may or may not be defined, the array may or may not be defined. The value at the index could be number, string, or empty string - if index is defined at all.
is there anything wrong with
edit - removed quotes
if(undefined===array[0]){
    console.log('undefined');
}

A: Actually yes, you've mistaken "undefined" type with undefined value.
You can write either:
if (undefined === array[0]) {
    console.log('undefined');
}

or
if ('undefined' === typeof array[0]) {
    console.log('undefined');
}

And if array itself may be undefined, you should of course add the check for if before, e.g.:
if (undefined === array || undefined === array[0]{
    console.log('undefined');
}

A: @Tomek already has an excellent answer but I would still like to chime in here. One of your main problems is that you're mixing data types in your array, you shouldn't be doing that. If your array should contain strings and strings ONLY you can easily check it like this
if(typeof array[0] === "string" && array[0] !== "")

which would be a javascript equivalent of for example C#'s !string.IsNullOrEmpty.
Having multiple data types in the array complicates the checking and is indicative of an error in structuring your code. What happens for example if you enter null into the array? Then Tomek's test will fail. Of course, you could also do another check for null but I'd say it would be better to restructure your data model.


text:
Q: Will a Culture Bomb take a city in an adjacent tile? I understand how the basic Culture Bomb works. What I'm asking is if you own the tile adjacent to a neighboring city (other player or City State) and perform a Culture Bomb in it, will you take over that city?
In the picture below, the x's are your territory, the o's are your neighbor's, and the C is your neighbor's city.
x x o o o o
 x x C o o
x x(x)o o o
 x x o o o

If you bomb the (x) tile to change the territory like so
x x o o o o
 x x C o o
x x(x)x o o
 x x x o o

will you control the city C?

A: According to this (fairly comprehensive) guide, a Culture Bomb will not convert a city.  The author states that those long-range land grabs can still be useful even if they're outside of your cities' 3 tile radius utilization zone, to simply deny those resources to your enemy.


text:
Q: Constrain a columns value to a value of a different column inside the same table? I'm creating a tree view for a website using databases. I will create 2 tables, let's call them "Folder" and "File". A folder can contain multiple folders and files, and files will act as leaf nodes - which means they're a "dead end" in the tree if you're unfamiliar with the term.
The folder table will contain columns:
Folder_id, Folder_name, Folder_parent

File will contain:
File_id, File_name, File_parent

Obviously File_parent will reference a folder_id, thus creating a foreign key, but how do I make the Folder_parent reference the Folder_id?
Example:
FOLDER_NAME   | FOLDER_ID   | FOLDER_PARENT
root               1               null
Cars               2                 1
Planes             3                 1
BMW                4                 2

A: create table folder (
  folder_id int primary key,
  folder_name varchar not null,
  folder_parent int references folder(folder_id)
)

A: I would make a separate table to deal with relationships, since a file can easily exist in two folders (think aliases). In this schema, you could simplify things with just a node table and a relationships (or edges, if you're familiar with graph theory) table:
CREATE TABLE nodes (
    node_id int primary key,
    node_name varchar not null,
    node_type enum('folder','file')
)

CREATE TABLE edges (
    child_node_id int primary key,
    parent_node_id int,
    unique( child_node_id, parent_node_id)
)

I'm a little rusty on my sql, so my syntax may need some work, but that's how I would approach it. It's much more flexible this way.


text:
Q: how can i choose array size in stract type (golang) i need do something like this :
in go language,please help ,thanks
var size_IO= map[string]int{"AI":32,"DI":64,"AO":32}

type IO_point struct{
  Name string
  }
type AI struct {
    CART [64]IO_point
    Type string
    IO_points [size_IO[Type]]IO_point
}

A: Short answer: You cannot do this.
The length of the array is part of type declaration and its value must me resolved at compile time. So it should be constant.
const arr_size= 5

type IO_point struct {
    Name string
}
type AI struct {
    CART      [64]IO_point
    Type      string
    IO_points [arr_size]IO_point
}

In your situation you need a slice which is a dynamic data structure and more flexible than array. Here it is an example:
var size_IO = map[string]int{"AI": 32, "DI": 64, "AO": 32}

type IO_point struct {
    Name string
}
type AI struct {
    CART      [64]IO_point
    Type      string
    IO_points []IO_point
}

func NewAi(cart [64]IO_point, t string) AI {
    return AI{
        CART: cart,
        Type: t,
        IO_points: make([]IO_point, 0, size_IO[t]),
    }
}


text:
Q: how do I extract all prices and give the min ? JSON request I'm trying to get the min price for the requested item.
I don't get how. Can anyone help?
import requests
import json

item = input('put your item here please :  ')
gg = item.replace(' ', '_')
response_url =  requests.get(f'https://api.warframe.market/v1/items/'+ gg +'/orders?include=item')

data = json.loads(response_url.text)
price = data['payload']['orders'][0]['platinum']

print(price)

here is an example url: https://api.warframe.market/v1/items/mirage_prime_systems/orders?include=item
Here's a small sample of the data from data["payload"]["orders"]:
{'visible': True,
  'order_type': 'buy',
  'quantity': 1,
  'platinum': 11,
  'user': {'reputation': 4,
   'region': 'en',
   'avatar': 'user/avatar/60e52c93a4784b00c68db129.png?558d0a9d0e4627de50c4218bda527217',
   'last_seen': '2021-10-01T16:31:55.334+00:00',
   'ingame_name': 'WDNMDXZLL',
   'status': 'ingame',
   'id': '60e52c93a4784b00c68db129'},
  'platform': 'pc',
  'region': 'en',
  'creation_date': '2021-10-01T16:13:57.000+00:00',
  'last_update': '2021-10-01T16:13:57.000+00:00',
  'id': '615733c5db3f3b01febb45a4'},
 {'order_type': 'sell',
  'visible': True,
  'platinum': 19,
  'quantity': 1,
  'user': {'reputation': 0,
   'region': 'en',
   'last_seen': '2021-10-01T19:36:31.682+00:00',
   'ingame_name': 'Weshu',
   'avatar': 'user/avatar/5f775345d5551401da6e613f.png?38078a7a72b95c6a3f2b34319aea3e05',
   'status': 'ingame',
   'id': '5f775345d5551401da6e613f'},
  'platform': 'pc',
  'region': 'en',
  'creation_date': '2021-10-01T17:49:13.000+00:00',
  'last_update': '2021-10-01T17:49:13.000+00:00',
  'id': '61574a195af7c701d3bcbf74'},

we get lot of offers and lot of prices im trying to get min price of them all and display it !! thanks for help in advance

A: You don't specify what you mean by "min price of them all" so I'll assume you want both the minimum buy price and the minimum sell price:
orders = data["payload"]["orders"]
min_buy_price = min(o["platinum"] for o in orders if o["order_type"] == "buy")
min_sell_price = min(o["platinum"] for o in orders if o["order_type"] == "sell")


text:
Q: Remove bright streak from image using python I have a set of images I'm using to perform a 3D reconstruction using mayavi in python, unfortunately there is a bright streak through most images over the features of interest that is screwing my reconstruction up, as shown in the figure below. The features of interest in this case are the 'holes' in the structure.

I've attempted to use scikit-image erode and dilate functions to remove the feature, unfortunately the distorts the rest of the image a little too much, whilst failing to remove the feature completely, as shown below.

Does anyone know how I can simply remove this bright streak, without distorting the rest of the image?