text:
Q: SQL Server update JSON with url in a property without introducing escaping sequences I am trying to update an array in a JSON contained into a column inside my DB, it's not clear to me what i did wrong but seems like that when a JSON property (a string) contain backslash, those value will be escaped.
I don't want that escaping is introduced into DB data, is there a way to prevent this or the only option is to proceed with a REPLACE() at the end of JSON modification?
Here the query :
 SELECT TOP 1  JSON_MODIFY(
           CASE WHEN ISNULL([_DOCUMENTS],'') = '' THEN '{}' ELSE [_DOCUMENTS] END ,
           '$.Documents',
           JSON_QUERY(
              (
              SELECT *
              FROM OPENJSON([_DOCUMENTS], '$.Documents') WITH (
                 Title nvarchar(1000) '$.Title',
                 Category nvarchar(1000) '$.Category',
                 NumberOfPages INT '$.NumberOfPages',
                 SizeInBytes INT '$.SizeInBytes',
                 MimeType nvarchar(1000) '$.MimeType',
                 [Date] nvarchar(1000) '$.Date',
                 ResourceId INT '$.ResourceId',
                 ResourceType INT '$.ResourceType',
                 ParentEntityType INT '$.ParentEntityType',
                 [Url] nvarchar(1000) '$.Url',
                 [Site] nvarchar(1000) '$.Site',
                 [Description] nvarchar(1000) '$.Description',
                 PreviewImageUrl nvarchar(1000) '$.PreviewImageUrl',
                 LanguageCode nvarchar(1000) '$.LanguageCode',
                 Sort INT '$.Sort'
              )
              WHERE LanguageCode != N'ru'
              FOR JSON PATH
              )
           )
        )
    FROM [dbo].[myTalbe]

Here the JSON before transformation :
{
    "ResourceId": 0,
    "ResourceType": 999,
    "ParentEntityId": 3,
    "ParentEntityType": 60,
    "Links": [],
    "ProvisionalMainImage": {
        "MimeType": "image/png",
        "ImageKind": 0,
        "Size": 0,
        "Annotation": null,
        "ImageGroup": "default",
        "ResourceId": 0,
        "ResourceType": 60,
        "ParentEntityId": 0,
        "ParentEntityType": 0,
        "Url": "",
        "Site": "",
        "Description": "",
        "PreviewImageUrl": "",
        "LanguageCode": "template",
        "Sort": 0
    },
    "Images": [],
    "YouTubeVideos": [],
    "Documents": [{
            "Title": "",
            "Category": "",
            "Author": "",
            "NumberOfPages": 0,
            "SizeInBytes": 161356,
            "MimeType": "application/pdf",
            "Date": "2000-01-01T00:00:00",
            "ResourceId": 0,
            "ResourceType": 70,
            "ParentEntityId": 0,
            "ParentEntityType": 0,
            "Url": "https://mySite/..",
            "Site": "",
            "Description": "",
            "PreviewImageUrl": "https://mySite/..",
            "LanguageCode": "pt",
            "Sort": 0
        }, {
            "Title": "",
            "Category": "",
            "Author": "",
            "NumberOfPages": 0,
            "SizeInBytes": 192958,
            "MimeType": "application/pdf",
            "Date": "2000-01-01T00:00:00",
            "ResourceId": 0,
            "ResourceType": 70,
            "ParentEntityId": 0,
            "ParentEntityType": 0,
            "Url": "https://mySite/..",
            "Site": "",
            "Description": "",
            "PreviewImageUrl": "https://mySite/..",
            "LanguageCode": "ru",
            "Sort": 0
        }, {
            "Title": "",
            "Category": "",
            "Author": "",
            "NumberOfPages": 0,
            "SizeInBytes": 162314,
            "MimeType": "application/pdf",
            "Date": "2000-01-01T00:00:00",
            "ResourceId": 0,
            "ResourceType": 70,
            "ParentEntityId": 0,
            "ParentEntityType": 0,
            "Url": "https://mySite/..",
            "Site": "",
            "Description": "",
            "PreviewImageUrl": "https://mySite/..",
            "LanguageCode": "template",
            "Sort": 0
        }
    ],
    "Htmls": []
}

Here the result after the query do its transofrmation :
{
    "ResourceId": 0,
    "ResourceType": 999,
    "ParentEntityId": 3,
    "ParentEntityType": 60,
    "Links": [],
    "ProvisionalMainImage": {
        "MimeType": "image/png",
        "ImageKind": 0,
        "Size": 0,
        "Annotation": null,
        "ImageGroup": "default",
        "ResourceId": 0,
        "ResourceType": 60,
        "ParentEntityId": 0,
        "ParentEntityType": 0,
        "Url": "",
        "Site": "",
        "Description": "",
        "PreviewImageUrl": "",
        "LanguageCode": "template",
        "Sort": 0
    },
    "Images": [],
    "YouTubeVideos": [],
    "Documents": [{
            "Title": "",
            "Category": "",
            "NumberOfPages": 0,
            "SizeInBytes": 161356,
            "MimeType": "application\/pdf",
            "Date": "2000-01-01T00:00:00",
            "ResourceId": 0,
            "ResourceType": 70,
            "ParentEntityType": 0,
            "Url": "https:\/\/mySite\/..",
            "Site": "",
            "Description": "",
            "PreviewImageUrl": "https:\/\/mySite\/..",
            "LanguageCode": "pt",
            "Sort": 0
        }, {
            "Title": "",
            "Category": "",
            "NumberOfPages": 0,
            "SizeInBytes": 162314,
            "MimeType": "application\/pdf",
            "Date": "2000-01-01T00:00:00",
            "ResourceId": 0,
            "ResourceType": 70,
            "ParentEntityType": 0,
            "Url": "https:\/\/mySite\/..",
            "Site": "",
            "Description": "",
            "PreviewImageUrl": "https:\/\/mySite\/..",
            "LanguageCode": "template",
            "Sort": 0
        }
    ],
    "Htmls": []
}

As you can see the wrong '\ /' sequence is introduced at some point by the function used (one of them probably do the escaping thing). I can easily revert '\ /' back to '/' with just a REPLACE operation. But that approach seems risky to me, if there are other escaping i didn't see in my testing.
I prefer to understand how to use the function above, to manupulate JSON without introducing escaping artifacts.

A: If I understand the question correctly, you are trying to delete items from the $.Documents JSON array, based on a specific condition. The documentation explains, that ... If the source data contains special characters, the FOR JSON clause escapes them in the JSON output with '\' ..., so a possible approach is to parse this JSON array with OPENJSON() and default schema, and rebuild it again using string aggregation:
SELECT JSON_MODIFY(
   [_DOCUMENTS],
   '$.Documents',
   JSON_QUERY((
      SELECT CONCAT('[', STRING_AGG([value], ','), ']')
      FROM OPENJSON([_DOCUMENTS], '$.Documents')
      WHERE JSON_VALUE([value], '$.LanguageCode') != 'ru'
   ))
)
FROM [dbo].[myTalbe]


text:
Q: page token youtube api v3 I want to do pagination with youtube api v3 (/videos?).
My request uri - https://www.googleapis.com/youtube/v3/videos?key={APP_KEY}&part=snippet&maxResults=50&chart=mostPopular&videoCategoryId=10

But in response I didn't see nextPageToken field.
If I send maxResult field which set in 49 (not 50 like first request). In response I can find nextPageToken field and count of items in search - 200. BUT, when I send new request for second part of search - in response I have only 15 items (must be 49) and haven't nextPageToken field, only previousPageToken.
Thank.

A: Not an answer, but too much to put into a comment:
Using
https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.videos.list?part=snippet&chart=mostPopular&maxResults=20
to collect the nextPageToken, then doing a second and finally third time, the same is happening to me.
I then removed the maxResults param, thinking this might not be doing what I thought, and patiently worked through until I hit the same place as before (was using maxResults = 20)..and no more nextPageToken, even though the "totalResults": 200
Can only think:

*

*throttled to only give you 40 results (in which case it should indicate so)

*bug

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to implement a custom actionbar and set a resizable title to it in Android? I created a custom actionbar so that I can add buttons to the actionbar. But now I need a way to display the title of the app on this custom actionbar. I have a temporary fix by adding a TextView to my custom actionbar but I don't want to be re-sizing it for different devices (such as tablets and phone). See is what it looks it so far:

This title is too small. I want it to match the size of the buttons. Here is my code for the custom actionbar xml:
actionbar_custom.xml
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:layout_gravity="fill_horizontal" >

    <ImageButton
        android:id="@+id/btnBack"
        android:background="?attr/actionBarItemBackground"
        android:layout_width="?attr/actionBarSize"
        android:layout_height="match_parent"
        android:scaleType="centerInside"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/ic_keyboard_backspace_white_24dp" />

    <TextView
        android:id="@+id/customTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:scaleType="centerInside"
        android:layout_toRightOf="@+id/btnBack"
        android:text="App Title" />

    <ImageButton
        android:id="@+id/btnHelp"
        android:background="?attr/actionBarItemBackground"
        android:layout_width="?attr/actionBarSize"
        android:layout_height="match_parent"
        android:scaleType="centerInside"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/ic_help_white_24dp" />

</RelativeLayout>

Any suggestions? Let me know if more detail is required.

A: I added this line to the TextViewtag: android:textAppearance="?android:attr/textAppearanceMedium"


text:
Q: How to implement or emulate an "abstract" OCUnit test class? I have a number of Objective-C classes organized in an inheritance hierarchy. They all share a common parent which implements all the behaviors shared among the children. Each child class defines a few methods that make it work, and the parent class raises an exception for the methods designed to be implemented/overridden by its children. This effectively makes the parent a pseudo-abstract class (since it's useless on its own) even though Objective-C doesn't explicitly support abstract classes.
The crux of this problem is that I'm unit testing this class hierarchy using OCUnit, and the tests are structured similarly: one test class that exercises the common behavior, with a subclass corresponding to each of the child classes under test. However, running the test cases on the (effectively abstract) parent class is problematic, since the unit tests will fail in spectacular fashion without the key methods. (The alternative of repeating the common tests across 5 test classes is not really an acceptable option.)
The non-ideal solution I've been using is to check (in each test method) whether the instance is the parent test class, and bail out if it is. This leads to repeated code in every test method, a problem that becomes increasingly annoying if one's unit tests are highly granular. In addition, all such tests are still executed and reported as successes, skewing the number of meaningful tests that were actually run.
What I'd prefer is a way to signal to OCUnit "Don't run any tests in this class, only run them in its child classes." To my knowledge, there isn't (yet) a way to do that, something similar to a +(BOOL)isAbstractTest method I can implement/override. Any ideas on a better way to solve this problem with minimal repetition? Does OCUnit have any ability to flag a test class in this way, or is it time to file a Radar?

Edit: Here's a link to the test code in question. Notice the frequent repetition of if (...) return; to start a method, including use of the NonConcreteClass() macro for brevity.

A: Here's a simple strategy that worked for me.  Just override invokeTest in your AbstractTestCase as follows:
- (void) invokeTest {
    BOOL abstractTest = [self isMemberOfClass:[AbstractTestCase class]];
    if(!abstractTest) [super invokeTest];
}

A: You could also override + (id)defaultTestSuite method in your abstract TestCase class.
+ (id)defaultTestSuite {
    if ([self isEqual:[AbstractTestCase class]]) {
        return nil;
    }
    return [super defaultTestSuite];
}

A: It sounds like you want a parameterized test.
Parameterized tests are great whenever you want to have a large number of tests with the same logic but different variables. In this case, the parameter to your test would be the concrete tested class, or possibly a block that will create a new instance of it.
There's an article about implementing parameterized testing in OCUnit here. Here's an example of applying it to testing a class hierarchy:
@implementation MyTestCase {
    RPValue*(^_createInstance)(void);
    MyClass *_instance;
}

+ (id)defaultTestSuite
{
    SenTestSuite *testSuite = [[SenTestSuite alloc] initWithName:NSStringFromClass(self)];

    [self suite:testSuite addTestWithBlock:^id{
        return [[MyClass1 alloc] initWithAnArgument:someArgument];
    }];

    [self suite:testSuite addTestWithBlock:^id{
        return [[MyClass2 alloc] initWithAnotherArgument:someOtherArgument];
    }];

    return testSuite;
}

+ (void)suite:(SenTestSuite *)testSuite addTestWithBlock:(id(^)(void))block
{
    for (NSInvocation *testInvocation in [self testInvocations]) {
        [testSuite addTest:[[self alloc] initWithInvocation:testInvocation block:block]];
    }
}

- (id)initWithInvocation:(NSInvocation *)anInvocation block:(id(^)(void))block
{
    self = [super initWithInvocation:anInvocation];
    if (!self)
        return nil;

    _createInstance = block;

    return self;
}

- (void)setUp
{
    _value = _createInstance();
}

- (void)tearDown
{
    _value = nil;
}

A: The simplest way:
- (void)invokeTest {
    [self isMemberOfClass:[AbstractClass class]] ?: [super invokeTest];
}

Copy, paste and replace AbstractClass.

A: I don't see a way to improve on the way you're currently doing things without digging into OCUnit itself, specifically the SenTestCase implementation of -performTest:. You'd be set if it called invoked a method to determine "Should I run this test?" The default implementation would return YES, while your version would be like your if-statement.
I'd file a Radar. The worst that could happen is your code stays the way it is now.


text:
Q: Firestore query is not running with startAfter I have following firestore query and startAfter is not working there. Instead of "starting after" it restarts at the beginning. Any help will be highly appreciated.
            const messages = [],
                f = Firebase.firestore()
                    .collection("chat")
                    .doc(chatId)
                    .withConverter(ChatMessageConverter)
                    .collection("messages")
                    .orderBy('creation_time', 'desc')
                    .limit(limit);
            if (!_.isNull(lastActiveDoc))
                f.startAfter(lastActiveDoc);
            const snapshot = await f.get();

A: When you call startAfter(lastActiveDoc) (or any other of the query building method) it returns a new query. You have to make sure to call get on that new query.
The simplest way to do that is with f = f.startAfter(lastActiveDoc); (so with an additional f =  in there, so that you're using the new query.
So:
f = Firebase.firestore()
    .collection("chat")
    .doc(chatId)
    .withConverter(ChatMessageConverter)
    .collection("messages")
    .orderBy('creation_time', 'desc')
    .limit(limit);

if (!_.isNull(lastActiveDoc))
    f = f.startAfter(lastActiveDoc); // the change is in this line

const snapshot = await f.get();


text:
Q: Adding DKIM DNS record - can something go wrong? I have a working external managed mail system for our company domain.
Additionally I am currently trying to setup a second mailserver (which I have control over) for the same domain with DKIM with postfix.
The externally managed main mail server should continue to send emails normally via its own DKIM signatures, the newly created mailserver should start signing with its key.
I will be able to use either of these mailservers for sending mails.
Now my concern is:
If I add DKIM signatures to my domain's DNS records, will I still be able to safely send mails via the primary managed mailserver that also does
 DKIM or will it then complain somehow.
I just want to make sure, that mails from the managed mailserver (with its own DKIM) will not be treated as SPAM once DKIM is enabled for the secondary mailserver.
Also to note, the managed mailserver already has two DKIM DNS records:
(Note: there is whysover no domain part in the DNS name entry)
key2._domainkey.reply
key2._domainkey.returnpath

The name part looks strange as I thought the domain name itself must be present...
The following is what I want to add now:
host1._domainkey.DOMAIN.TLD

Can they interfere somehow?
Update
Added note that the already configured DNS record does not include the domain name in its name field for DKIM

A: The short answer is that they shouldn't interfere, but that unless your setup is more complicated than you explained, something is weird.
In more details, DKIM has a built-in feature called selectors which is designed to handle multiple hosts/daemons actually signing emails for the same domain. See section 3.1 of RFC 6376.
Basically, that is the part before the _domainkey in the DNS record, which allows you to setup as many signing services as you need. Once a signature is received, it will contain the selector that did the signing and only its DNS record will be checked.
Here, you have two DNS entries:

*

*One defines selector key2 for the domain reply.DOMAIN.TLD (assuming the line you pasted is from the zone DOMAIN.TLD)

*The other defines selector key2 for the domain returnpath.DOMAIN.TLD
Note that despite sharing the same selector name, there is no relation between them in DKIM as a selector is defined for a domain and that the domains here are not the same.
However, it typically is used to allow the same key on two domains.
Now you propose to add a new DKIM entry, for the selector host1 of domain DOMAIN.TLD (without any subdomain). Note that unless you set-it up as strict (s flag in the DNS record), this key will be able to sign subdomains, including reply.DOMAIN.TLD and returnpath.DOMAIN.TLD.
Hence this will work. However, I'm not sure this behavior (a first key that is allowed on 2 subdomains and a new key that will be allowed on the parent domain and all the subdomains) is what you intended.


text:
Q: history.pushState not working in Chrome on iOS when executing without an interaction It seems like history.pushState is not working in Chrome on iOS when executed manually without any touch/click interaction.
I need help with understanding why iOS Chrome does this, and if possible, how to fix it.
https://codepen.io/grymer/pen/OOmebv
Here is a codepen with a minimum working example.
To test it, you need to fork the pen and go into debug view in Chrome on an iOS device.
Then you will see "a button that says "To B". Press it and then use browser back. You will see that this behavior differs from any other browser.
var React, { Component } = React;
var { BrowserRouter, Redirect, Route, Switch } = ReactRouterDOM;

class App extends Component {
  render() {
    return (
      <BrowserRouter basename={location.href}>
        <Switch>
          <Route path="/b" component={B} />
          <Route component={A} />
        </Switch>
      </BrowserRouter>
    );
  }
}

class A extends Component {
  constructor() {
    super();

    this.state = {};

    this.handleClick = this.handleClick.bind(this);
  }

  render() {
    if(this.state.redirect) {
      return <Redirect push to="/b" />
    }

    return (

        On page A
        <button onClick={this.handleClick}>To B</button>

    );
  }

  handleClick() {
    this.setState({ redirect: true });
  }
}

class B extends Component {
  constructor() {
    super();

    this.state = {
      showModal: false
    };

    this.handleClick = this.handleClick.bind(this);
  }

  componentDidMount() {
    this.button.click(); // comment this line to manually open the modal by tapping the button
  }

  render() {
    return (

        On page B
        { this.state.showModal ? <Modal history={this.props.history} onClose={() => this.setState({ showModal: false }) } /> : null }
        <button ref={(el) => this.button = el } onClick={this.handleClick}>Open modal</button>

    );
  }

  handleClick() {
    this.setState({
      showModal: true
    });
  }
}

class Modal extends Component {
  constructor() {
    super();

    this.handleClick = this.handleClick.bind(this);
    this.onPopState = this.onPopState.bind(this);
  }

  componentDidMount() {
    this.props.history.push(this.props.history.location.pathname, { type: 'modal' });
    window.addEventListener('popstate', this.onPopState);
  }

  componentWillUnmount() {
    window.removeEventListener('popstate', this.onPopState);
  }

  render() {
    return (

        Modal is opened
        <button onClick={this.handleClick}>Close modal</button>

    );
  }

  handleClick() {
    this.props.onClose();
    this.props.history.goBack();
  }

  onPopState() {
    this.props.onClose();
  }
}

ReactDOM.render(<App />, document.getElementById('react-container'));

A: Chromium team has acknowledged and they are working on a fix.
https://bugs.chromium.org/p/chromium/issues/detail?id=783382#c3


text:
Q: Monte Carlo integration - convergence I have a 5D integral being calculated with a Monte Carlo uniform random sampling. The issue is that the region of integration is very small and for 100000 points I get only around 20-30 points every time. The function has to be calculated several times for a certain parameter, which doesn't change the integration region, but changes only the magnitude of the result (which is good, I suppose).
After several runs I gathered some hundreds of points which are a valid match for the integration region. I was thinking about use those points to improve the integration result, but how can I do that, in a correct way?


text:
Q: How to create an object from 2 arrays? So I hava array Links and array Params with same langth N
So what I need is to create an object where for each link from Links I will be able to see
  param from Params
And than for example to be abble to call  something like
for each( item in object)
if (item.param == "some value") {
// some code
} else...

How to do such thing (Code exaMple, please)

A: From Array: You could first build a list with elements composed of a item and a param (supposing the length is indeed the same for both lists)
var items:Array = new Array();

for(var i:uint = 0; i < links.length; i++) {
   links:Array .push({link:links[i], param:params[i]});
}

You can then filter them easily:
items.forEach(checkValue);

for(var i:uint = 0; i < items.length; i++) {
  if (items[i].param == "some value") {
    // some code
  } else{
    ...
  }
}


text:
Q: Google Colab - Where is the output saved? I am training a machine learning model on google's colab. I am using keras with tensorflow backend (python 3.6).
I am saving my model using the model.save() function provided by keras. When I call model.save('model_name)` where is the file saved? I cannot find it in my drive anywhere.

A: First, mount your drive:
!mkdir -p drive
!google-drive-ocamlfuse drive

Now, append your path:
import sys
sys.path.append('drive/Project')

You should be able to see your files on your local and web-based drive using:
model.save('drive/Project/myModel.h5')

A: Even though it is a bit late, I was also struggling with the same question.Then i found out mounting the drive in colab and then providing the drive path,the files will get stored in the google drive
from google.colab import drive
drive.mount('/content/gdrive')
#using model.save_weights() to save the weights of the model in HDF5 format
model.save_weights("/content/gdrive/My Drive/weights.h5")

The file is saved in the drive with name "weights.h5"


text:
Q: Only show if exists in other table I'm new to PHP and MySQL and right now I'm showing a table with categories from products. But I'm trying to only show them if they exist in another table. Unfortunately, I'm not sure how to get there.
Currently, I'm showing ALL categories like this:
<?php include '/../connect.php'; ?>

<?php

$results=$conn->query("SELECT * FROM groepen");
while($rows=$results->fetch_array())
{
    ?>

<a href="<?php echo 'groep?id='.$rows['GroepID']; ?>"><?php echo $rows['GroepOmschrijving']; ?>

    <?php
    $result=$conn->query("SELECT * FROM subgroepen WHERE GroepID=".$rows['GroepID']);
    ?>

        <?php
        while($row=$result->fetch_array())
        {
            ?>
<a href="<?php echo 'subgroep?id=' . $row['SubGroepID']; ?>"><?php echo $row['SubGroepOmschrijving']; ?>
<?php
        }
        ?>

    <?php
}
?>

So, I'm trying to only show the categories if the value of table groepen.GroepID matches the value of occasions.Groepnummer.


text:
Q: WPF Loading multiple tabs simultaneously in background with freezing UI Basic UI
I have UI shown in above image.
Each Tab have Some controls like grid which has some data filled in from datatable.
What i want?
behaviour just like web browsers when we open new tab, it gets loaded in background.
Entire browser doesn't freeze. you are able to see and interact with facebook if twitter is loading in another tab.
How it is behaving currently ?
When i click on one of the item in left hand side treeview , tab gets opened but it freezes entire UI of the app, i am not able to click on another treeview item until the tab has completed its data into grid.
Current Implementation
on treeview click event, another thread is created which is calling addTab()
function.
treeviewlist_SelectedItemChanged()
{
   Dim thread As New Thread(Sub() Me.AddTab( itemno))
   thread.Start()
 }

below function creates backgroundWorker thread object bw,
bg_dowork() gets datatable from DB to bind to the grid in tabitem.
bg_RunWorkerCompleted() binds that dt to grid in tabitem.
Addtab()

{
  Thread.Sleep(TimeSpan.FromSeconds(2))
       Dispatcher.BeginInvoke(New Action(Function()

    Dim bg As New BackgroundWorker

      AddHandler bg.DoWork, Sub(sender, e)
       //get dt
      End Sub

     AddHandler bg.RunWorkerCompleted, Sub(sender, e)
     // bind dt to grid
    End Sub
   Return 1
    End Function),    DispatcherPriority.Send)

 }

To be honest i am new to WPF and vb.net and somehow feel i have messed up somewhere badly.

A: This is c# code. But it explains the concept nicely. It uses async/await keywords. The for-loop below can be replaced with your data-access code.
ViewModel vm = new ViewModel();
...
private async void Button_Click(object sender, RoutedEventArgs e)
{
    await _loadEmployees();
}

private Task _loadEmployees()
{
    Task t = Task.Factory.StartNew(() =>
    {
        var employees = new ObservableCollection<Employee>();

        for (long i = 0; i < 999999; ++i)
            employees.Add(new Employee() { Name = "Name" + i, Address = DateTime.Now.ToString() });

        vm.Employees = employees;
    });

    return t;
}

DataGrid is bound to Employees property of ViewModel .
Set Width and Height of DataGrid so that DataGrid can use UIVirtualization.
You can ask more doubts, I will update here.


text:
Q: Support for the experimental syntax 'jsx' isn't currently enabled I'm trying to run very simple code, but I'm getting an error, I didn't use the create react app!
It looks like my babel.config.js file is being ignored!
This is the structure of my small project:

My html file
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ReactJS</title>

My index.js file:
import React from 'react';
import { render } from 'react-dom';

render(
Hello World!!
, document.getElementById('app'));

My package json:
{
  "name": "front",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "dev": "webpack-dev-server --mode development",
    "build": "webpack-dev-server --mode production"
  },
  "dependencies": {
    "@babel/cli": "^7.10.5",
    "@babel/core": "^7.10.5",
    "@babel/plugin-proposal-class-properties": "^7.10.4",
    "@babel/preset-env": "^7.10.4",
    "@babel/preset-react": "^7.10.4",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  },
  "devDependencies": {
    "@babel/plugin-transform-runtime": "^7.9.0",
    "babel-loader": "^8.1.0",
    "webpack-dev-server": "^3.10.3"
  }
}

My webpack.config.js
const path = require('path');

module.exports = {
    entry: path.resolve(__dirname, 'src', 'index.js'),
    output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'bundle.js'
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'public'),
    },
    module: {
        rules: [{
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
            }
        }]
    },
};

And this is my babel.config.js
module.exports = {
    "presets": ["@babel/preset-env", "@babel/preset-react"]

};

Error when
yarn webpack-dev-server --mode development

ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /root/treina/front/src/index.js: Support for the experimental syntax 'jsx' isn't currently enabled (4:8):

  2 | import { render } from 'react-dom';
  3 |
> 4 | render(
Hello World!!
, document.getElementById('app'));
    |        ^

Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
    at Parser._raise (/root/treina/front/node_modules/@babel/parser/lib/index.js:757:17)
    at Parser.raiseWithData (/root/treina/front/node_modules/@babel/parser/lib/index.js:750:17)
    at Parser.expectOnePlugin (/root/treina/front/node_modules/@babel/parser/lib/index.js:8849:18)
    at Parser.parseExprAtom (/root/treina/front/node_modules/@babel/parser/lib/index.js:10170:22)
    at Parser.parseExprSubscripts (/root/treina/front/node_modules/@babel/parser/lib/index.js:9688:23)
    at Parser.parseMaybeUnary (/root/treina/front/node_modules/@babel/parser/lib/index.js:9668:21)
    at Parser.parseExprOps (/root/treina/front/node_modules/@babel/parser/lib/index.js:9538:23)
    at Parser.parseMaybeConditional (/root/treina/front/node_modules/@babel/parser/lib/index.js:9511:23)
    at Parser.parseMaybeAssign (/root/treina/front/node_modules/@babel/parser/lib/index.js:9466:21)
    at Parser.parseExprListItem (/root/treina/front/node_modules/@babel/parser/lib/index.js:10846:18)
ℹ 「wdm」: Failed to compile.

I'm using yarn and the WSL terminal

A: Yet another possible cause. I got this error when try to run a project in a command prompt at a path that included symlinks. Changing directory directly into the real path solved the issue.

A: The solution that worked for me was when I discovered node_modules/react-scripts/config/webpack.config.js contained:
                // @remove-on-eject-begin
                babelrc: false,
                configFile: false,

By setting babelrc: true, I was finally able to get .babelrc changes to work. I'm guessing the configFile: parameter is what you will need to change. (Note, the babelrc appears to need to go into src/ for react-scripts to find it, reasonably likely to also be true for babel.config.js.)

A: Mmm i think the problem is in your babel, try this:

*

*npm i --save-dev @babel/plugin-proposal-class-properties

*add loose:true in your babelrc

A: I remade my project from scratch and realized that I was wrong to not include the "D" at the end of the command:
yarn add webpack-dev-server -D

Now it's working!

A: Adding another answer to the mix... the project I was looking at when I hit this was built off create-react-app using react scripts v4 and React 17. The warning was showing for me in relation to the source code for a third-party module, something like:
Failed to compile.

./node_modules/@third-party/ui-components/src/components/Header.js
SyntaxError: C:\Development\app\node_modules\@third-party\ui-components\src\components\Header.js: Support for the experimental syntax 'jsx' isn't currently enabled (142:5)

The problem turned out to be that someone had mistakenly added the import for the third-party component as follows:
import { Header } from '@third-party/ui-components/src';

Instead of:
import { Header } from '@third-party/ui-components';

So, webpack was trying to use the original source code for the package instead of the compiled export. And, checking into react-scripts, the module loader for JS external to the app is set up as follows:
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
  test: /\.(js|mjs)$/,
  exclude: /@babel(?:\/|\\{1,2})runtime/,
  loader: require.resolve('babel-loader'),
  options: {
    babelrc: false,
    configFile: false,
    compact: false,
    presets: [
      [
        require.resolve('babel-preset-react-app/dependencies'),
        { helpers: true },
      ],
    ],
    cacheDirectory: true,
    // ----- 8< -----
  },
}

Fixing up the import path by removing the /src fixed the issue.

A: In my case, Creating "babel.config.js" file with the following content worked.
module.exports = {
    presets:[
        "@babel/preset-env",
        "@babel/preset-react"
    ]
}

A: This https://stackoverflow.com/a/52693007/10952640 solved for me.
You need @babel/preset-react set also on webpack config:
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        options: { presets: ['@babel/env','@babel/preset-react'] },
      },

A: Just create a .babelrc file in the root of your project and add:
{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

A: 2021
I fixed it adding
"jsx": "react-jsx"

to my "compilerOptions" on my tsconfig.json file

A: In my package.json, I added:
 "babel": {
  "presets": [
    "@babel/react",
    "@babel/env"
  ],
  "plugins": [
    "@babel/proposal-class-properties",
    "@babel/plugin-transform-runtime"
  ]
}

A: For Rails/React, run the line below:
$ bin/rails webpacker:install:react

A: inside the webpacker.yml file if using react with rails add jsx extension.
  extensions:
    - .jsx
    - .mjs
    - .js
    - .sass
    - .scss
    - .css
    - .module.sass
    - .module.scss
    - .module.css
    - .png
    - .svg
    - .gif
    - .jpeg
    - .jpg

A: For me the test doesn't work in VSCode only. I'm using yarn workspace and CRA as one of the workspaces.
This means the solution is to ignore the failing VSCode tests and start the tests in command line instead:
yarn workspace frontend test

A: I came across the same error, my problem was that during rebase I lost a brace somewhere so my package.json wasn't working properly - if your babel is showing errors like this - try checking if your package.json has brackets properly set up

A: For the people who are getting this error while building Remix app, change the extension of file from .js to .jsx/.tsx or check with tsconfig file.

A: If you're using Babel 7 and yarn workspaces or a monorepo and getting this error you need to tell Babel to transpile files outside your package directory.
In your webpack 5 config put babelrcRoots: ['../*'] in your js test object options. Here's mine for example:
  {
    use: ['babel-loader'],
    exclude: /node_modules/,
    test: /\.(js|jsx)$/,
    options: {
      presets: ['@babel/preset-env'],
      babelrcRoots: ['../*']
    }
  },

See other options in this github issue

A: module.exports = {
   plugins: ["nativewind/babel"],
   presets: ['babel-preset-expo'],
  };

Make changes according the the link below to your babel.config.js
From https://www.nativewind.dev/quick-starts/create-react-native-app
and then just add the presets as shown above, it will work.


text:
Q: How to copy an existing worksheet and multi-paste it in the same workbook using xlrd, xlwt, and xlutils I have an excel template file dot xlt extension. I want to make a program using python (xlrd, xlwt, and xlutils) where it will copy the existing template to the new workbook (distinct name). Then the wokrbook will have a sheet as the template.
My question, how to copy and paste the first sheet to the same workbook.
So, the output are many same sheets in a workbook as the template.
Please tell me how to do that ?


text:
Q: How to do a binary filter on a BindingSource I am using the MySql .Net Connector binding the DataSet to a ComboBox.
I am trying to filter the dataset using a binary expression, and the results are always a null dataset.
this.customerBindingSource.Filter = "scale & 64";
this.customerBindingSource.Sort = "custid";
this.customerTableAdapter.Fill(this.requisitionDataSet11.customer);

if I change the filter to a basic = I get some of the results.
this.customerBindingSource.Filter = "scale = 64";

I am trying to achieve the equivalent of the sql this statement
SELECT * FROM customer where scale & 64 order by custid;


text:
Q: Displaying list view Items when button is clicked I am creating a Tables app i.e. When a number is entered in editText and button is pressed, The list view will show the table of that certain number.
I tried this code but it keeps crashing.
public class MainActivity extends AppCompatActivity {

    ListView myListView;

    public final void generate(int timesTableNumber){
        ArrayList<String> timeTableContent= new ArrayList<String>();

        for(int j=1;j<=10;j++)
            timeTableContent.add(Integer.toString(j*timesTableNumber));

        ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,timeTableContent);

        myListView.setAdapter(arrayAdapter);
    }

    public void table(View view)
    {
        EditText editText=(EditText)findViewById(R.id.editText);
        generate(Integer.parseInt(editText.toString()));
    }

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

        myListView=findViewById(R.id.myListView);

        generate(1);

    }
}

A: You should add getText() .
 generate(Integer.parseInt(editText.getText().toString()));

Then use String.valueOf  instead of Integer.toString.
        for(int j=1;j<=10;j++)
        timeTableContent.add(String.valueOf(j*timesTableNumber));


text:
Q: Using Clojure multimethods defined across multiple namespaces Although the below example seems a bit strange, it's because I'm trying to reduce a fairly large problem I've got at present to a minimal example. I'm struggling to work out how to call into multimethods when they're sitting behind a couple of abstraction layers and the defmulti and corresponding defmethods are defined in multiple namespaces. I really feel like I'm missing something obvious here...
Suppose I've got the following scenario:

*

*I purchase stuff from a variety of suppliers, via their own proprietary interfaces

*I want to implement a common interface to talk to each of those suppliers

*I want to be able to purchase different items from different suppliers

Using Clojure, the recommended ways of implementing a common interface would be via protocols or multimethods. In this case, as I'm switching based on the value of the supplier, I think the best way to handle the situation I'm describing below is via multimethods (but I could be wrong).
My multimethod definitions would look something like this, which defines a common interface I want to use to talk to every supplier's APIs:
(ns myapp.suppliers.interface)
(defmulti purchase-item :supplier)
(defmulti get-item-price :supplier)

For each supplier, I probably want something like:
(ns myapp.suppliers.supplier1
  (:require [myapp.suppliers.interface :as supplier-api]))
(defmethod purchase-item :supplier1 [item quantity] ...)
(defmethod get-item-price :supplier1 [item] ...)

and
(ns myapp.suppliers.supplier2
  (:require [myapp.suppliers.interface :as supplier-api]))
(defmethod purchase-item :supplier2 [item quantity] ...)
(defmethod get-item-price :supplier2 [item] ...)

So far, no problem
Now to my code which calls these abstracted methods, which I assume looks something like:
(ns myapp.suppliers.api
  (:require [myapp.suppliers.supplier1 :as supplier1]
            [myapp.suppliers.supplier2 :as supplier2])
(defn buy-something
  [supplier item quantity]
  (purchase-item [supplier item quantity])
(defn price-something
  [supplier item]
  (get-item-price [supplier item])

This is starting to look a bit ... ugly. Every time I implement a new supplier's API, I'll need to change myapp.suppliers.api to :require that new supplier's methods and recompile.
Now I'm working at the next level up, and I want to buy a widget from supplier2.
(ns myapp.core
  (:require [myapp.suppliers.api :as supplier])
(def buy-widget-from-supplier2
  (buy-something :supplier2 widget 1)

This can't work, because :supplier2 hasn't been defined anywhere in this namespace.
Is there a more elegant way to write this code? In particular, in myapp.core, how can I buy-something from :supplier2?

A: Initial notes
It's hard to tell if you mixed up some things in the process of simplifying the example, or if they weren't quite right out of the gate. For an example of what I'm referring to, consider purchase-item, though the issues are similar for get-item-price:

*

*The defmulti call is a single-argument function

*The defmethod calls each take two arguments

*The call in buy-something passes a vector to purchase-item, but looking up the :supplier keyword in a vector will always return nil
Your concerns

*

*
Every time I implement a new supplier's API, I'll need to change myapp.suppliers.api to :require that new supplier's methods and recompile.

*

*If you require the myapp.suppliers.interface namespace myapp.suppliers.api, the problem can be avoided

*
This can't work, because :supplier2 hasn't been defined anywhere in this namespace.

*

*Simply put, this will work. :)

*
Is there a more elegant way to write this code? In particular, in myapp.core, how can I buy-something from :supplier2?

*

*Certainly, but this solution is going to make some assumption based on the ambiguities in the Initial notes.

Without straying too far from your original design, here's a fully-working example of how I interpret what you were trying to achieve:

*

*myapp.suppliers.interface
(ns myapp.suppliers.interface)

(defmulti purchase-item (fn [supplier item quantity] supplier))

*myapp.suppliers.supplier1
(ns myapp.suppliers.supplier1
  (:require [myapp.suppliers.interface :as supplier-api]))

(defmethod supplier-api/purchase-item :supplier1 [supplier item quantity]
  (format "Purchasing %dx %s from %s" quantity (str item) (str supplier)))

*myapp.suppliers.supplier2
(ns myapp.suppliers.supplier2
  (:require [myapp.suppliers.interface :as supplier-api]))

(defmethod supplier-api/purchase-item :supplier2 [supplier item quantity]
  (format "Purchasing %dx %s from %s" quantity (str item) (str supplier)))

*myapp.suppliers.api
(ns myapp.suppliers.api
  (:require [myapp.suppliers.interface :as interface]))

(defn buy-something [supplier item quantity]
  (interface/purchase-item supplier item quantity))

*myapp.core
(ns myapp.core
  (:require [myapp.suppliers.api :as supplier]))

(def widget {:id 1234 :name "Monchkin"})

(supplier/buy-something :supplier1 widget 15)
;;=> "Purchasing 15x {:id 1234, :name \"Monchkin\"} from :supplier1"

(supplier/buy-something :supplier2 widget 3)
;;=> "Purchasing 3x {:id 1234, :name \"Monchkin\"} from :supplier2"

As you can see, the supplier/buy-something calls propagate to the appropriate multimethod implementations. Hopefully this helps you get where you were trying to go.


text:
Q: How can I easily implement right-to-left text direction with Symfony2 My question is in the title. Can you help me to implement better solution for right-to-left text direction.

A: For example, you can make something like this
<?php

namespace You\YourBundle\Constants;

    class LanguageConstants
    {
        const LANGUAGE_EN = 1;
        const LANGUAGE_HR = 2;
        const LANGUAGE_SR = 3;
        const LANGUAGE_BS = 4;
        const LANGUAGE_DE = 5;
        const LANGUAGE_PT = 6;
        const LANGUAGE_AR = 7;

        static private $constants = array(
            self::LANGUAGE_EN => 'English',
            self::LANGUAGE_HR => 'Hrvatski',
            self::LANGUAGE_SR => 'Srpski / Српски',
            self::LANGUAGE_BS => 'Bosanski / Босански',
            self::LANGUAGE_DE => 'Deutsch',
            self::LANGUAGE_PT => 'Português',
            self::LANGUAGE_AR => 'العربية',
        );

        static private $constantsURL = array(
            self::LANGUAGE_EN => 'en',
            self::LANGUAGE_HR => 'hr',
            self::LANGUAGE_SR => 'sr',
            self::LANGUAGE_BS => 'bs',
            self::LANGUAGE_DE => 'de',
            self::LANGUAGE_PT => 'pt',
            self::LANGUAGE_AR => 'ar',
        );

        static private $constantsRTL = array(
            self::LANGUAGE_EN => false,
            self::LANGUAGE_HR => false,
            self::LANGUAGE_SR => false,
            self::LANGUAGE_BS => false,
            self::LANGUAGE_DE => false,
            self::LANGUAGE_PT => false,
            self::LANGUAGE_AR => true,
        );

        static public function getLanguageConstants()
        {
            natsort(self::$constants);
            return self::$constants;
        }

        static public function getLanguageName($const)
        {
            return self::$constants[$const];
        }

        static public function getLanguageURL($const)
        {
            return self::$constantsURL[$const];
        }

        static public function getLanguageRTL($const)
        {
            return self::$constantsRTL[$const];
        }
    }

So, this is one way to go. This way you can have all your language data in one place, you can easily get en in yoururl/en/yourroute by calling getLanguageURL, and in same maner you can call getLanguageRTL in your controller with a proper _local and pass in to twig so that you could do if R2L true then dir=rtl.
You can even make a twig extension to call getLanguageRTL from twig but since controller is the place to do all "dirty works", why bother.
Best regards


text:
Q: Magento2 add breadcrumb dynamically on custom pages Magento2 How can I add breadcrumb dynamically on custom pages?
Home > FAQ > Carpet FAQ
Home > FAQ > Shutters FAQ

Where Carpet & Shutters are dynamic

A: You can achieve by using the below code in the block file.
  public function _prepareLayout()
        {
            $breadcrumbsBlock = $this->getLayout()->getBlock('breadcrumbs');
            $baseUrl = $this->_storeManager->getStore()->getBaseUrl();

            if ($breadcrumbsBlock) {

                $breadcrumbsBlock->addCrumb(
                    'home',
                    [
                    'label' => __('FAQ'), //lable on breadCrumbes
                    'title' => __('Carpet FAQ'),
                    'link' => $baseUrl
                    ]
                );
                $breadcrumbsBlock->addCrumb(
                    'coderkube',
                    [
                    'label' => __('Carpet FAQ'),
                    'title' => __('Carpet FAQ'),
                    'link' => '' //set link path
                    ]
                );
            }
            $this->pageConfig->getTitle()->set(__('FAQ')); // set page name
            return parent::_prepareLayout();
        }

A: In your custom controller you can add breadcrumbs using below code.

resultPageFactory is Magento\Framework\View\Result\PageFactory

public function execute(){
    $resultPage = $this->resultPageFactory->create();
    $breadcrumbsBlock = $resultPage->getLayout()->getBlock('breadcrumbs');
    if ($breadcrumbsBlock) {
        $breadcrumbsBlock->addCrumb(
            'home',
            [
                'label'    => __('Home'),
                'link'     => $this->_url->getUrl('')
            ]
        );
        $breadcrumbsBlock->addCrumb(
            'faq',
            [
                'label'    => __('Faq'),
                'link'     => $this->_url->getUrl('faq')
            ]
        );
        /* you can add here your confition for dynamic element*/
        $breadcrumbsBlock->addCrumb(
            'carpet_faq',
            [
                'label'    => __('Carpet FAQ'),
                'link'     => $this->_url->getUrl('carpetfaq')
            ]
        );
    }
    return $resultPage;
}


text:
Q: [[PromiseState]]: "rejected" in loop I am using react in javascript and I try to encrypt array elements using a loop, then I want to push each result  in an element of the new array, I use this code:
   var eccrypto = require("eccrypto");

   var privateKey= Buffer.from([238, 239, 199, 101, 188, 134, 13, 13,195, 172, 125, 168, 225, 189, 72, 148, 225, 200, 127, 218, 204, 11, 150, 146, 180, 243, 195, 109, 200, 119, 50, 20],'hex');

  let array = [2,3,5];
  let array2=[];

    for (let b of array) {

          const a= eccrypto.sign(privateKey,b);
          array2.push(a);

        }
        console.log(array2);

the problem is it rejected in the second and fourth elements.
The result is like this:

and the error message:

I tried to use async/await as a lot of the previous problems solved by using it, but I get the same problem.
I'll appreciate your help, thank you.

A: You need to do following way
import eccrypto  from 'eccrypto'
import crypto from 'crypto'

export default function App() {
  let array = [2,3,5];

let array2=[];

  var privateKey = eccrypto.generatePrivate();
  for (let b of array) {
    var msg = crypto.createHash("sha256").update(b).digest();
    eccrypto.sign(privateKey, msg).then(function(a) {
      array2.push(a);

    });

  }
  console.log(array2);


text:
Q: Starting google appengine devserver on all network interfaces I am currently starting appengine devserver using following maven command
mvn appengine:devserver
It starts the devserver on localhost. But I need devserver to listen on my wireless interface too, so that google endpoints service running on devserver can be accessed from my android device.
Following page describes that command line argument --address=0.0.0.0 would make devserver listen on all network interfaces. But I have no idea how I can give this argument through maven.
https://cloud.google.com/appengine/docs/java/tools/devserver?hl=en
Does anyone know how to do this?

A: The configuration is described here Specifying a local port for local testing


text:
Q: Is there a way to embed a Sh/Bash session in C or C++? As it can be done with Python.
I am interested not only in running single shell commands, but also in saving the current environment state.
For example, the following code:
system("a=2");
system("echo $a");

prints nothing, but I want to find a way by which the program would print "2".
The main goal is to keep the shell environment (that can be initialized, for example, using .bashrc) throughout the entire С/С++ program, as if you work in your terminal.

A: Bash does not have an API in the same sense that Python does, but it's a shell.  It has a text-based UI that is relatively easy for other programs to use.  You cannot use system() because it requires you to specify all shell input up front and blocks until the shell exits, but you can use the same mechanism that system() does: run the shell in a separate process.
Details depend on the machine on which your program runs, but on machines where you typically find Bash or another Bourne-family shell -- Linux, Mac, and other POSIX systems -- you have at least two main alternatives:

*

*If you want the shell output to go (only) to the host program's standard output and standard error streams, then you can use popen() to open a stream connected to a shell:
FILE *shell = popen("/bin/bash -i", "w");

You could then write an arbitrary sequence of shell commands to the stream, and the shell will receive them on its standard input, execute them, and write the results to its standard output.  The shell launched this way will share the caller's standard output and standard error.

*If the host program must both feed input to the shell and receive its output then you need to work at a lower level:

*

*Use pipe() to create two pipes (three if you want to capture the shell's standard error separately).

*fork() a child process in which to run the shell, and in it

*

*dup2() the appropriate pipe ends onto the child's standard in, out, and (optionally) error.

*close() the pipe ends that the child will not be using

*execl() the shell in the child process.

*Back in the parent,

*

*close() the pipe ends the parent will not be using

*send commands to the shell over the pipe set up for doing so

*read responses and / or error responses via the pipe(s)

*when done with the shell close() the pipes and wait() for the child process to terminate.  You can get its exit status at this point if you're interested in that.

Option (2) requires handling a lot more details -- more even than the above overview might suggest.  You will find many answers here on SO that address them if you have need of that.

A: You cannot accomplish this by calling system() because it will be done in new process that will quickly exit.
However, you can call setenv - it will edit environment variables for currently running process (your C program), and it will be inherited by all processes you might create e.g. using system().

A: Like this:
system("a = 2; echo $a");


text:
Q: JPA - Entities are not stored in database I am facing a problem, when I tried to insert a data into Database through JPA (@persistanceContex)
Observations

*

*Not getting any errors;

*Record is not storing into database (save)

*When I tried with listAll() ; it retrieving the data from database

Domain
@Entity
public class Test {

    @Id
    private int id;

    @Column(name="full_name")
    private String fullName;

    @Column(name="mobile_number")
    private int mobileNumber;

    .....

}

DAO Class
@Repository("testDAO")
@Transactional
public class TestDAO {

    private EntityManager entityManager;

     @PersistenceContext(unitName="CRUD_Test_Annotation")
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public void save(Test test){
        entityManager.persist(test);
    }
}

Service
@Service("testService")
@Transactional
public class TestService {

    private static final Logger logger = LoggerFactory.getLogger(TestService.class);

    @Autowired(required=true)
    private TestDAO testDAO;

    public void save(Test test){
        logger.info("TestService::save()");
        testDAO.save(test);
    }

    public void list(){
        testDAO.getAll();
    }

}

Controller
@RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Locale locale, Model model) {

        Test test = new Test();
        test.setId(xx);
        test.setFullName("xxxxx");
        test.setMobileNumber(yyyyyy);

        testService.save(test);
        return "home";
    }

application-context.xml
<tx:annotation-driven transaction-manager="transactionManager" />

    <!-- Declare a JPA entityManagerFactory-->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">

        <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"></property>
        <property name="persistenceUnitName" value="CRUD_Test_Annotation" />

        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
            </bean>
        </property>
    </bean>

    <!-- Declare a transaction manager-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

A: First of all, you don't need two transaction boundaries, I suggest you remove @Transactional from your DAO and keep the one in your service.
Start by verifying that spring-transaction has initiated a transaction: Use the debugger and stop the application after the transaction boundary, for instance in your  TestService.save-method. If transactions are running, you will see org.springframework.transaction.interceptor.TransactionInterceptor#invoke in the call stack.  If you don't see the TransactionInterceptor, then that's your problem. Post your persistence.xml file if transactions are running.


text:
Q: How to use a for loop to display an image depending on a position in an index? This is inside a react-native project:
I have a progress bar that has 10 positions, and each position as a possibility of three states - incomplete, active, complete. There is an image that corresponds to each of those states. I was thinking I could use a for loop that would look for the index number of the page, which I'll store in an object, and depending on the relationship between the position in the loop and and the index number, that would determine which image gets displayed. Something like this:
if the position in the loop > index number, display the incomplete image

if the position in the loop = index number, display the active image

if the position in the loop < index number, display the complete image

Beyond this, I'm not even sure on where to start.

A: In your class/component:
  state = {
    indexNum: 4, // arbitrary value
  }

  displayStatus(item) {
    if(item.id > this.state.indexNum){ // Incomplete
      return <View style={styles.progressPoint}><Text>I</Text></View>;
    }
    else if(item.id == this.state.indexNum){ // Active
      return <View style={styles.progressPoint}><Text>A</Text></View>;
    }
    else if(item.id < this.state.indexNum){ // Complete : you can use only 'else' here
      return <View style={styles.progressPoint}><Text>C</Text></View>;
    }

  }

In render() of your class/component:
    // Positions/Pages - these will serve as basis for .map - you can add more than 'id'
    const positions  = [{"id": 1},{"id": 2},{"id": 3},{"id": 4},{"id": 5},
                       {"id": 6},{"id": 7},{"id": 8},{"id": 9},{"id": 10}];
    return (
       <View style={styles.container}>
          {positions.map((item) => (
             this.displayStatus(item)
          ))}
       </View>
    );

Here's an Expo Snack of the above (based on the scope of your question) to get you started.
You can store the index number of the page in state and update this state at completion of each progress position. Note: if you are not using redux, you may need to pass/handle state (index number) on each page individually (depending on your navigation or components structure).


text:
Q: DeviceIoControl (kernel32.lib) Inspired by balena.io's drivelist, I create a Rust version. The idea is simple, using Windows' Setup API to read all connected storages list (with mount points/drive letters), using winapi crate
///file main.rs
use core::{slice, ffi};
use std::{ptr::{null_mut, addr_of, null}, mem::{zeroed, size_of, MaybeUninit, align_of, transmute}, str::from_utf8};

use winapi::{um::{setupapi::{SetupDiGetClassDevsA, DIGCF_PRESENT, DIGCF_DEVICEINTERFACE, SP_DEVINFO_DATA, SetupDiEnumDeviceInfo, HDEVINFO, PSP_DEVINFO_DATA, SetupDiGetDeviceRegistryPropertyW, SPDRP_FRIENDLYNAME, SPDRP_REMOVAL_POLICY, SPDRP_ENUMERATOR_NAME, SetupDiDestroyDeviceInfoList, SP_DEVICE_INTERFACE_DATA, SetupDiEnumDeviceInterfaces, SetupDiGetDeviceInterfaceDetailW, PSP_DEVICE_INTERFACE_DETAIL_DATA_W, SP_DEVICE_INTERFACE_DETAIL_DATA_W}, winioctl::{GUID_DEVINTERFACE_DISK, VOLUME_DISK_EXTENTS, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, PVOLUME_DISK_EXTENTS}, handleapi::{INVALID_HANDLE_VALUE, CloseHandle}, cfgmgr32::{CM_REMOVAL_POLICY_EXPECT_SURPRISE_REMOVAL, CM_REMOVAL_POLICY_EXPECT_ORDERLY_REMOVAL}, errhandlingapi::GetLastError, fileapi::{CreateFileW, OPEN_EXISTING}, winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_ATTRIBUTE_NORMAL}, ioapiset::DeviceIoControl}, shared::{minwindef::MAX_PATH, winerror::{ERROR_NO_MORE_ITEMS, ERROR_INSUFFICIENT_BUFFER}}, ctypes::c_void};

fn get_detail_data(h_dev_info:HDEVINFO,device_info_data:PSP_DEVINFO_DATA)
{
    let mut h_device=INVALID_HANDLE_VALUE;
    let mut index=0_u32;

    unsafe{
        loop {
            if h_device!= INVALID_HANDLE_VALUE {
                CloseHandle(h_device);
                h_device=INVALID_HANDLE_VALUE;
            }

            let mut device_interface_data:SP_DEVICE_INTERFACE_DATA=zeroed();
            device_interface_data.cbSize=size_of::<SP_DEVICE_INTERFACE_DATA>() as _;

            if SetupDiEnumDeviceInterfaces(h_dev_info, device_info_data, &GUID_DEVINTERFACE_DISK, index, &mut device_interface_data) == 0 {
                let error_code=GetLastError();

                if error_code!=ERROR_NO_MORE_ITEMS {
                    panic!("SetupDiEnumDeviceInterfaces: Error {}",error_code);
                }

                break;
            } else {
                let mut size={
                    let mut required_size=MaybeUninit::<u32>::uninit();

                    if SetupDiGetDeviceInterfaceDetailW(h_dev_info, &mut device_interface_data, null_mut(), 0, required_size.as_mut_ptr(), null_mut())==0 {
                        if GetLastError()==ERROR_INSUFFICIENT_BUFFER {
                            required_size.assume_init()
                        } else {
                            panic!("Error SetupDiGetDeviceInterfaceDetailW");
                        }
                    } else {
                        0
                    }
                };
                let mut buf:Vec<u8>=Vec::with_capacity(TryInto::<usize>::try_into(size).unwrap() + align_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>()-1);
                let align_offset=buf.as_mut_ptr().align_offset(align_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>());
                let device_iface_detail =&mut *(buf.as_mut_ptr().offset(align_offset.try_into().unwrap()) as *mut MaybeUninit<SP_DEVICE_INTERFACE_DETAIL_DATA_W>);
                device_iface_detail.write(SP_DEVICE_INTERFACE_DETAIL_DATA_W {
                    cbSize: size_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>().try_into().unwrap(),
                    DevicePath: [0],
                });

                if SetupDiGetDeviceInterfaceDetailW(h_dev_info, &mut device_interface_data, device_iface_detail.as_mut_ptr(), size, &mut size, null_mut())==0 {
                    println!("Error {}, Couldn't SetupDiGetDeviceInterfaceDetailW",GetLastError());
                    break;
                }

                let device_detail_data=device_iface_detail.assume_init_ref();
                h_device=CreateFileW(device_detail_data.DevicePath.as_ptr(), 0, FILE_SHARE_READ,  null_mut(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, null_mut());

                if h_device==INVALID_HANDLE_VALUE {
                    println!("Couldn't open handle to device: Error {}",GetLastError());
                    break;
                }

                get_device_number(h_device);
            }

            index+=1;
        }

        if h_device!= INVALID_HANDLE_VALUE {
            CloseHandle(h_device);
            h_device=INVALID_HANDLE_VALUE;
        }
    }
}

fn get_device_number(h_device:*mut c_void)
{
    unsafe {
        let mut size=0_u32;

        let mut disk_extents=MaybeUninit::<VOLUME_DISK_EXTENTS>::uninit();
        disk_extents.write(zeroed());
        let result=DeviceIoControl(h_device, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, null_mut(), 0, disk_extents.as_mut_ptr() as _, size_of::<VOLUME_DISK_EXTENTS>() as _, &mut size, null_mut());
/* It returns 0!! */
        println!("Bytes returned: {}",size);

        if result!=0 {
            println!("Success");
        } else {
/* This will be executed */
            println!("get_device_number fail. Error {}",GetLastError());
        }
    }
}

fn get_enumerator_name(h_dev_info:HDEVINFO,device_info_data:PSP_DEVINFO_DATA) -> String
{
    unsafe {
        let mut buffer:[u8;MAX_PATH]=zeroed();

        if SetupDiGetDeviceRegistryPropertyW(h_dev_info, device_info_data, SPDRP_ENUMERATOR_NAME, null_mut(), &mut buffer as _, (size_of::<u8>() * MAX_PATH) as _, null_mut()) != 0 {
            ansi_to_string(&buffer)
        } else {
            "".to_string()
        }
    }
}

fn get_friendly_name(h_dev_info:HDEVINFO,device_info_data:PSP_DEVINFO_DATA) -> String
{
    unsafe {
        let mut buffer:[u8;MAX_PATH]=zeroed();

        if SetupDiGetDeviceRegistryPropertyW(h_dev_info, device_info_data, SPDRP_FRIENDLYNAME, null_mut(), &mut buffer as _, (size_of::<u8>() * MAX_PATH) as _, null_mut()) != 0 {
            ansi_to_string(&buffer)
        } else {
            "".to_string()
        }
    }
}

fn is_removable(h_dev_info:HDEVINFO,device_info_data:PSP_DEVINFO_DATA)->bool
{
    unsafe {
        let mut result=0_u8;
        SetupDiGetDeviceRegistryPropertyW(h_dev_info, device_info_data, SPDRP_REMOVAL_POLICY, null_mut(), &mut result as _, size_of::<u32>() as _, null_mut());

        match result as u32
        {
            CM_REMOVAL_POLICY_EXPECT_SURPRISE_REMOVAL|CM_REMOVAL_POLICY_EXPECT_ORDERLY_REMOVAL =>true,
            _=>false
        }
    }
}

fn is_usb_drive(enumerator_name:&str) -> bool
{
    ["USBSTOR", "UASPSTOR", "VUSBSTOR","RTUSER", "CMIUCR", "EUCR","ETRONSTOR", "ASUSSTPT"].contains(&enumerator_name)
}

fn ansi_to_string(unsafe_utf8:&[u8])->String
{
    match from_utf8(&unsafe_utf8.iter().filter(|c| **c != 0).map(|c| *c).collect::<Vec<u8>>() as _)
    {
        Err(err)=>{
            println!("Error {}",err);
            "".to_string()
        },
        Ok(res)=>res.trim().to_string()
    }
}

fn main() {
    unsafe {
        let h_device_info=SetupDiGetClassDevsA(&GUID_DEVINTERFACE_DISK, null_mut(), null_mut(), DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);

        if h_device_info!=INVALID_HANDLE_VALUE {
            let mut i=0;
            let mut device_info_data:SP_DEVINFO_DATA=zeroed();
            device_info_data.cbSize=size_of::<SP_DEVINFO_DATA>() as _;

            while SetupDiEnumDeviceInfo(h_device_info, i, &mut device_info_data)!=0
            {
                let enumerator_name=get_enumerator_name(h_device_info, &mut device_info_data);
                let friendly_name=get_friendly_name(h_device_info, &mut device_info_data);

                if friendly_name.is_empty() {
                    continue;
                }

                println!("Name: {}",friendly_name);
                println!("Is USB drive: {}",is_usb_drive(&enumerator_name));
                println!("Is removable: {}",is_removable(h_device_info, &mut device_info_data));

                get_detail_data(h_device_info, &mut device_info_data);
                i+=1;
            }
        }

        SetupDiDestroyDeviceInfoList(h_device_info);
    }
}

Terminal output:
Name: SKHynix_HFM512GDHTNI-87A0B
Is USB drive: false
Is removable: false
DevicePath: \\?\scsi#disk&ven_nvme&prod_skhynix_hfm512gd#5&8980ef4&0&000000#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
Bytes returned: 0
get_device_number fail. Error 1

Everything went fine until DeviceIoControl always returns 0 and GetLastError() returns 1 (inside get_device_number() function). Can someone guide me figuring out what went wrong?
Thanks in advance


text:
Q: Turning Resharper on/off Can I switch resharper on/off in a simple manner.
The issue is sometimes I dealing with big files  and makes my VS slow, sometimes it pops out a message telling me resharper is out of memory. Can I activate/deactivate it without having to reload the solution?

A: In ReSharper 5.0, the keyboard shortcut to temporarily enable/disable code analysis for the current file is Ctrl+Shift+Alt+8. It was Ctrl+8 in previous versions.

A: In versions 7.0-2017 it's in
Tools > Options > ReSharper > Suspend

A: Press Ctrl+8.
Alternatively, click Tools, Add-in Manager, and uncheck ReSharper.

A: Try using Ctrl+8 on the big files:
http://codebetter.com/blogs/jeffrey.palermo/archive/2007/11/28/temporarily-disable-code-analysis-for-single-code-file-with-resharper-3-0-2-and-vs-2008.aspx


text:
Q: Canonically quantizing the charged scalar field with massive gauge boson I have a specific confusion in canonically quantizing the theory of a complex scalar field $\Phi$ and a real vector field $V^\mu$, with a Lagrangian density:
\begin{align*}
    \mathcal{L} = -(D_\mu \Phi)^{\dagger}D^\mu\Phi - \frac{1}{4} F_{\mu \nu}F^{\mu \nu} - \frac{1}{2}m^2 V_\mu V^\mu - \mathcal{H}(\Phi^\dagger\Phi) \ ,
\end{align*}
where $D_\mu \equiv \partial_\mu - i g V_\mu$ and $F_{\mu\nu} = \partial_{[\mu}V_{\nu]} \ .$
Here is my attempt with the point of confusion noted:
First step is to expand this Lagrangian and identify the conjugate fields. Expanding the Lagrangian gives us:
\begin{align*}
    \mathcal{L} = -(\partial_\mu \Phi)^{\dagger}\partial^\mu\Phi - \frac{1}{4} F_{\mu \nu}F^{\mu \nu} - \frac{1}{2}m^2 V_\mu V^\mu - ig V_\mu (\Phi^\dagger \partial^\mu \Phi - \Phi (\partial^\mu \Phi)^\dagger) - g^2 V^2 |\Phi|^2 - \mathcal{H}(\Phi^\dagger\Phi)
\end{align*}
There is no mass term for the scalar field here, but we can pull it out of the arbitrary function if needs be, but the scalar field could very well be massless. Also, we can choose:
$$J^\mu = - ig (\Phi^\dagger \partial^\mu \Phi - \Phi \partial^\mu \Phi^\dagger)$$
In any case, we get the following conjugate fields:
\begin{align*}
    \Pi = \dot{\Phi}^\dagger - i g V^0 \Phi^\dagger\\
    \Pi^\dagger = \dot{\Phi} + i g V^0 \Phi\\
    P^i = F^{i0} = \dot{V}^i + \partial_i V^0
\end{align*}
Now, $P^0 = 0$, so $V^0$ is just an auxiliary field, we can use the equation of motion ($-\partial_i F^{i0} = J^0 - 2 g^2 V^0 |\Phi|^2 - m^2 V^0$) to eliminate it in terms of the canonical field variable. This will help us in switching from Lagrangian to Hamiltonian formalism. But, I get:
$$V^0 = \frac{\nabla \cdot P + J^0}{(2g^2|\Phi|^2 + m^2)}$$
I was wondering if I can do that, i.e. just divide by a function of a field?
I am following Weinberg's approach for quantization.


text:
Q: Best practice to shutdown SharePoint 2016/2019 farm to do a "cold" snapshot. How to handle Distributed cache? Hello SharePoint Experts.
We want to perform a "cold" snapshot of our virtual SharePoint Servers and need to shutdown the servers before we will patch the farm.
As far as I understand there is no need for a specific order to shut down the servers, but it will minimize the error events if we do it in the following order:

*

*WebFrontEnd Servers

*App Servers (If there are more than one App servers the one with the Central Administration last)

*SQL Server

Is it also necessary to stop the search services before shutting down and to run the script provided by microsoft to gracefully shutdown the distributed cache hosts?
https://docs.microsoft.com/en-us/SharePoint/administration/manage-the-distributed-cache-service#perform-a-graceful-shutdown-of-the-distributed-cache-service-by-using-a-powershell-script
Are there any suggestions to do before we start the patching?
Thank you very much in advance and kind regards,
DocZito

A: You're correct, there is no specific order in which you need to shutdown your farm (or bring it up).
Because you're shutting down all servers, you can skip the script. AppFab will resolve the unallocated cache fractions when you bring up your DC(s).
Provided you're running 2016 or 2019, I would skip the snapshot step. Patching failures are incredibly rare. In fact, we patch SharePoint 2016 during business hours and have done so for 2 years now without issues on a monthly basis.


text:
Q: Why does this event handling code for ender break when I try to clean it up some? This is the code that works properly:
bonzo.aug({
  bind: function (event, handler) {

    if (this[0].attachEvent)
            this[0].attachEvent('on'+event, handler);
          else
            this[0].addEventListener(event, handler);
        },
  unbind: function (event, handler) {
            if (this[0].detachEvent)
              this[0].detachEvent('on'+event, handler);
            else
              this[0].removeEventListener(event, handler);
          },
  once: function (event, handler) {
          function doOnce(e) {
            bonzo(this).unbind(event, doOnce);
            handler.call(this, e);
          }
          this.bind(event, doOnce);
        }
});

But then when I try to consolidate and soup parts of it up a little, unbind and once break:
(function($){
  $.ieEventApi = !!window.attachEvent; // !-[1,];

  $.addEventListener = $.ieEventApi ? "attachEvent" : "addEventListener",
  $.removeEventListener = $.ieEventApi ? "detachEvent" : "removeEventListener",
  $.onForIe = $.ieEventApi ? 'on' : '',
  $.adaptEventHandlerForIe = function(f){
    return function(e){
      e.target = e[(e.target ? e.target : (e.srcElement || document))];
      return f(e);
    };
  };

  $.aug({
    bind: function (event, handler) {
            for(var i = 0; i < this.length; i++) // I'd use Bonzo.each if I could find any documentation for its use.. :-\
                this[i][$.addEventListener]($.onForIe+event, $.adaptEventHandlerForIe(handler), false); // The "false" is superfluous on IE, but apparently not problematically so.
            return this;
          },
    unbind: function (event, handler) {
              for(var i = 0; i < this.length; i++)
                this[i][$.removeEventListener]($.onForIe+event, $.adaptEventHandlerForIe(handler), false);
              return this;
            },
    once: function (event, oncehandler) {
            // This just calls the other two, which already handle iteration.
            this.bind(event, doOnce);
            return this;

            function doOnce(e) {
              $(e.target /*Or should I be using e.target here?*/ ).unbind(event, doOnce);
              oncehandler.call(this, e);
            }
          }
  });
})(bonzo);

A: Shouldn't the following line
e.target = e[(e.target ? e.target : (e.srcElement || document))];

be something like
e.target = e[e.target ? 'target' : (e.srcElement ? 'srcElement' : 'document')];

? I mean, when you're referring to a prop in an object and using square brackets you should write the inner value in string format. So e.etc should become e['etc'].


text:
Q: How to create a server alias for joomla I have a multilanguage website in joomla. The FaLang component creates the following URLs:
www.myDutchDomain.nl/nl/
www.myDutchDomain.nl/en/
www.myDutchDomain.nl/de/
I have 2 other URLs which should redirect to English and German URL:
www.myEnglishDomain.eu >> www.myDutchDomain.nl/en/
www.myGermanDomain.de >> www.myDutchDomain.nl/de/
After redirect I want to see myEnglishDomain and myGermandomain in URL. If I'm not mistaken it's called server alias.
How can I create a server alias for this purpose?

A: You should be able to use mod rewrite to solve this by adding lines to your .htaccess file, allowing anything on your country domains 'www.myEnglishDomain.eu/{wildcard}' to be rewritten to the country path '/en/{wildcard}'.
First you must make sure that the bindings for each domain are pointing to this website.
Then add the following lines to your .htaccess file:
RewriteEngine on

RewriteCond %{HTTP_HOST} ^www.myEnglishDomain.eu$[NC]
RewriteRule ^(.*)$ /en/$1 [L]

RewriteCond %{HTTP_HOST} ^www.myGermanDomain.de$ [NC]
RewriteRule ^(.*)$ /de/$1 [L]

If you need the domain within the browser to update to myDutchDomain.nl, then doing the following instead:
RewriteEngine on

RewriteCond %{HTTP_HOST} ^www.myEnglishDomain.eu$ [NC]
RewriteRule ^(.*)$ http://www.myDutchDomain.nl/en/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www.myGermanDomain.de$ [NC]
RewriteRule ^(.*)$ http://www.myDutchDomain.nl/de/$1 [R=301,L]

For further help, here is a mod rewrite cheat sheet: http://www.cheatography.com/davechild/cheat-sheets/mod-rewrite/
Disclaimer: I have not been able to test the above rules, please let me know if this contains syntax or other errors so to maintain an accurate reference for other people.


text:
Q: Issue with Sharepoint workflow with a custom content type I'm running into an issue with a custom approval workflow that was written in visual studio.  It creates an approval task using a custom content type.  I developed the workflow on a sharepoint enterprise environment, but the client is trying to run it on a foundation server.  The issue I'm running into is when the content type is assigned to the task list.  Whenever the workflow is run, I am unable to edit the list item, or update the task item.  As soon as I remove the content type from the task list, I can view and edit all of the records just fine.  I do get the following event in the logs:

System.NullReferenceException: Object reference not set to an instance
  of an object.    at
  Microsoft.SharePoint.Publishing.CachedListItem.GetWorkflowInfo(SPListItem
  item)     at Microsoft.SharePoint.Publishing.CachedListItem

To make it more interesting, I was able to run the workflow when the content type was not assigned and get the approval task created, then add in the content type after, then successfully edit and update both records.
And a bit of code....  this is my create task with content type method:
private void createTaskWithContentType1_MethodInvoking(object sender, EventArgs e)
    {
        //set the primary approval task as not completed
        this.primaryApprovalTaskCompleted = false;

        //get the primary approver
        var field = workflowProperties.Item.Fields.GetField("primaryApprover") as SPFieldUser;
        var fieldValue = field.GetFieldValue(workflowProperties.Item[field.Id].ToString()) as SPFieldUserValue;

        createTaskWithContentType1.TaskProperties.AssignedTo = fieldValue.User.LoginName;

        createTaskWithContentType1.TaskProperties.DueDate = DateTime.Now.AddHours(4);

        createTaskWithContentType1.TaskProperties.Title = "Primary Approval for Batch Job ID: " + workflowProperties.Item["batchJobId"].ToString();

        createTaskWithContentType1.TaskProperties.SendEmailNotification = true;

    }

and the xml for my content type:
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Field ID="{46F9442F-19E3-4818-8FE7-719E5961C8A1}" Name="ApprovalStatus" DisplayName="Approval Status" Type="Choice" Required="TRUE" Sealed="TRUE" Overwrite="True" >
    <CHOICES>
      <CHOICE>Approve</CHOICE>
      <CHOICE>Reject</CHOICE>
    </CHOICES>
  </Field>

  <Field ID="{B485C5E5-A85C-4C09-AE96-F7FC71FB4A3D}" Name="ApprovalNotes" DisplayName="Approval Notes" Type="Text" Overwrite="True" />

  <ContentType ID="0x01080100922FA9051D1C471DA956E627E6B3B81E"
           Name="ApprovalContentType"
           Group="Custom Content Types"
           Description="Approval Content Type"
           Version="0"
           Overwrite="True">
     <FieldRefs>
      <RemoveFieldRef ID="{a8eb573e-9e11-481a-a8c9-1104a54b2fbd}" Name="Priority" Hidden="TRUE"/>
      <RemoveFieldRef ID="{c3a92d97-2b77-4a25-9698-3ab54874bc6f}" Name="Predecessors" Hidden="TRUE"/>
      <RemoveFieldRef ID="{c15b34c3-ce7d-490a-b133-3f4de8801b76}" Name="Status" Hidden="TRUE"/>
      <RemoveFieldRef ID="{d2311440-1ed6-46ea-b46d-daa643dc3886}" Name="PercentComplete" Hidden="TRUE"/>
      <RemoveFieldRef ID="{7662cd2c-f069-4dba-9e35-082cf976e170}" Name="Body" Hidden="TRUE"/>
      <FieldRef
    ID="{46F9442F-19E3-4818-8FE7-719E5961C8A1}"
    Name="ApprovalStatus" Sealed="TRUE" Required="TRUE"/>
      <FieldRef
    ID="{B485C5E5-A85C-4C09-AE96-F7FC71FB4A3D}"
    Name="ApprovalNotes"/>
    </FieldRefs>

  </ContentType>
</Elements>

A: I have the same issue and resolved with following code.
   <ContentType ID="0x01080100C2CC93E34F784038BE7CA4CFD86BD58E"
                Name="taskCT"
                Group="Custom Content Types"
                Description="My Content Type"
                Inherits="FALSE"
                Version="0">

Just add 01 after 0x0108 ( 0x010801[remaing guid_ ]) in content type id so that every thing works fine. It's bug, Microsoft has given this solution.

A: Ok, so the solution for this one...  the issue had something to do with the fact that I used a create task with content type object.  I was able to replace it with a create task object, then set the content type of the object through code.  Still puzzles me as to why this worked on both of my test farms, but failed on my clients...


text:
Q: Counterexamples to: If $f:X \to Y$ is continuous, $Y$ is compact, then $f^{-1}$ is continuous. It is a theorem that if $f:X \to Y$ is a continuous bijection, $X$ is compact, then $g = f^{-1}$ is continuous. My professor asked us to find a counterexample to

If $f:X \to Y$ is continuous, $Y$ is compact, then $g = f^{-1}$ is continuous.

I do not like my counterexample so much because it uses the discrete metric. Are there other counterexamples?
My Counterexample: Let $X = [0, 1]$ with the Discrete metric, $Y = [0, 1]$ with the Euclidean metric, and let $f$ be the identity function.

A: Your example is fine, and quite simple and to the point.

A: Your example is fine. Another example is to take $X=[0,2\pi)$ with the usual metric, and let $Y=S^1 = \{z\in\mathbb{C}\mid |z|=1\}$, the unit circle on the complex plane, with the usual metric (so the distance is measured on the plane, not along the circle).
Let $f\colon X\to Y$ be given by $f(x) =e^{ix} = \cos(x) + i\sin(x)$.
Now, $Y$ is closed and bounded, so it is compact. The function $f$ is a continuous bijection. But $f^{-1}$ is not continuous; if it were, then $f$ would be a homeomorphism, but removing a single point from $X$ (other than $0$) will disconnect $X$, and removing a single point from $Y$ does not. Alternatively, note that you cannot find a neighborhood of $1\in Y$ whose image lies inside the neighborhood $[0,\frac{1}{2})$ of $f^{-1}(1)=0$, since the image will contain points arbitrarily close to $2\pi$.


text:
Q: Number of conjugacy classes of finite reductive groups Let $G$ be a connected reductive group over $\mathbb{Z}$.  Let $c_{G(\mathbb{F}_q)}$ be the number of conjugacy classes of $G(\mathbb{F}_q)$.
Question: Is it true that $c_{G(\mathbb{F}_q)}$ is a quasi-polynomial in $q$? I.e. is it true that there exists an integer $N$ (depending only on $G$) such that for every $i\in \{0,1,\dotsc,N-1\}$ there exists a polynomial $P_i$ such that $c_{G(\mathbb{F}_q)}=P_i(q)$ for all $q\equiv i \bmod N$?
If the answer is yes, then a type-independent explanation would be desirable. I'm mainly interested in the case $i=1$ but the general question seems worthwhile.
Frank Lübeck's tables at Character Degrees and their Multiplicities for some Groups of Lie Type of Rank < 9 illustrate that the question has a positive answer for (simply connected form of) exceptional groups. For instance, for $G_2$, $E_6$ and $E_7$, the site states that $N=6$ and gives the explicit polynomials. We also have a lot of positive evidence for classical groups coming from explicit computations in Macdonald - Numbers of conjugacy classes in some finite classical groups and Wall - On the conjugacy classes in the unitary, symplectic, and orthogonal groups among others.

A: Assume that $G$ is adjoint split over $\mathbb F_q$. Let $G^*$ be the (Langlands) dual group; it is also split over $\mathbb F_q$. For each semisimple $s \in G^*( \mathbb F_q)$ let $N_s$ be the number of unipotent representations
of the centralizer $Z_{G^*}(s)(\mathbb F_q)$. The number of conjugacy classes in $G(\mathbb F_q)$ is equal to the number of irreducible characters of $G(\mathbb F_q)$ and this equals (by my 1984 classification) the sum $\sum_s N_s$ where $s$ runs over the $G^*(\mathbb F_q)$-conjugacy classes of semisimple elements in $G^*(\mathbb F_q)$. Since the $N_s$ are very well behaved (much better behaved that number of unipotent classes) this reduces the problem to a problem of counting semisimple classes in $G^*(\mathbb F_q)$ with centralizer of fixed type. From this the desired result follows.
The main point is that the number of unipotent classes in $G(\mathbb F_q)$ behaves differently in small characteristic while the number of uniptent representations of a reductive group over $\mathbb F_q$ is independent of characteristic. This makes it easier to count irreducible representations than conjugacy classes.


text:
Q: Warning while compling Gem5 i am trying to compile gem5 on ubuntu 20.04 OS using below command:
scons build/X86/gem5.opt -j8
i got below warning:
Warning: Header file <png.h> not found.
This host has no libpng library.
Disabling support for PNG framebuffers.
Warning: Deprecated namespaces are not supported by this compiler.
Please make sure to check the mailing list for deprecation
announcements.
Warning: Couldn't find HDF5 C++ libraries. Disabling HDF5 support
i tried below solutions:
sudo apt-get install libhdf5-dev
sudo apt-get install libpng-dev
then tried to compile gem5 again with same build command, but still getting the same warnings


text:
Q: how to fix bootstrap column align Hello I have website called: http://mtisambebi.ge/
There is module where I have boostrap cols, but one col is aligned left and I do not understand whay.
this is screenshot
also module is called: ბოლო სიახლეები in main page.

A: Please add

 after every 3 column. where getting flot right


text:
Q: Moving Icons - Pixels I've been researching this for a while, but cannot find any solutions.
Here's my code

If you copy and paste this code into the HTML area of this site: http://jsfiddle.net/T3Nnu/3/
If you look at the Facebook Icon, it is set a few pixels higher than the SoundCloud (Orange) icon. Is there any way that I can make it even / parallel with the SoundCloud (Orange) icon?

A: change it with following:

Because iframe height and width is 32px and image width and height is 34px.

A: You can try this,  http://jsfiddle.net/T3Nnu/4/


text:
Q: Custom List Form on Home Page I created a custom list in SharePoint 2013.  The question I have sounds simple but I have not been able to find a way that works.  I created a subsite and custom list.  When someone goes to the home page I want the form to appear on the home page.  I know I add a link to the new item from the custom list but I want the form to be on the page.  I was thinking to use page viewer web part.  that may display the form but doesn't allow someone to fill out the form.
Can anyone help me show the New Item form on the home page that will allow someone to complete the form from the home page and save.  Also I not access to use InfoPath.  That could be the easiest option.

A: I tried this earlier by copying webpart code to home page web part zone but ended with issues.
Then implemented a custom form and added to home page.
Here, there are 2 ways to do this.

*

*Set new form as a home page and add additional web part zones to NewItem.aspx page (e.g.: right zone, left zone, footer zone, etc...) for other content.

*Create a custom form using HTML and JavaScript and add to home page using content editor web part which we chose for our site.

Let me know if you need additional inputs.
Thanks,
Venkat

A: Customizing the OOTB form will consume more time, instead of that, we can create a new custom form as a custom web part.
Step 1: Create Custom visual web part
Step 2: Add Html, CSS, and jss whatever you required for your form
step 3: Deploy it your site collection, First Navigate to list/newform.aspx page and add our custom web part and close the existing OOTB web part(form)
step 4: Then add the same web part in Homepage(Handle it CSS\jss for the look and feel like to show the dialog based on icon click, etc)


text:
Q: Sum of infinite series.
If $$S=\frac{2}{10}+\frac{6}{10^2}+\frac{12}{10^3}+\frac{20}{10^4}+\cdots,$$
  find the value of $S$.

*

*$24/90$

*$242/900$

*$245/900$

*$200/729$

What I understand:
Had the numerators not been present, it could have been solved by infinite geometric series formula. Also, I can't find any relationship between the numerators. Please help me with this question.

A: When $|x|<1$, $$\frac{1}{1-x} = 1+x+x^2+x^3+x^4+x^5+\cdots$$
Differentiate both sides twice to get
$$\frac{2}{(1-x)^3} = 2+6x+12x^2 + 20 x^3+ \cdots$$
Consequently,
$$\frac{2x}{(1-x)^3} = 2x+6x^2+12x^3 + 20 x^4+ \cdots$$
Put $x=1/10$ to find the required sum.

A: Here's how to get
a more general result
with just algebra
(no calculus).
Let
$s_m(x)
=\sum_{n=0}^{\infty} p_m(n)x^n
$,
where
$|x| < 1$
(so all the series converge)
and
$p_m(n)
=\prod_{k=1}^m (n+k-1)
=n(n+1)...(n+m-1)
$.
I will
show that,
for $m \ge 1$,
$s_m(x)
=\dfrac{m!x}{(1-x)^{m+1}}
$.
In particular,
$\sum_{n=1}^{\infty} \dfrac{n(n+1)}{10^n}
=s_2(1/10)
=\dfrac{2(1/10)}{(9/10)^3}
=\dfrac{200}{729}
$.
We have
$\begin{array}\\
p_m(n+1)-p_m(n)
&=\prod_{k=1}^m (n+k)-\prod_{k=1}^m (n+k-1)\\
&=\prod_{k=1}^m (n+k)-\prod_{k=0}^{m-1} (n+k)\\
&=(n+m)\prod_{k=1}^{m-1} (n+k)-n\prod_{k=1}^{m-1} (n+k)\\
&= (n+m-n)\prod_{k=1}^{m-1}(n+k)\\
&=mp_{m-1}(n+1)\\
\end{array}
$
Therefore,
for $m \ge 1$,
$\begin{array}\\
(1-x)s_m(x)
&=\sum_{n=0}^{\infty} p_m(n)x^n-x\sum_{n=0}^{\infty} p_m(n)x^n\\
&=\sum_{n=0}^{\infty} p_m(n)x^n-\sum_{n=0}^{\infty} p_m(n)x^{n+1}\\
&=\sum_{n=0}^{\infty} p_m(n)x^n-\sum_{n=1}^{\infty} p_m(n-1)x^{n}\\
&=p_m(0)+\sum_{n=1}^{\infty} (p_m(n)-p_m(n-1))x^n\\
&=\sum_{n=1}^{\infty} mp_{m-1}(n)x^n
\qquad\text{since }p_m(0) = 0\\
&=m\sum_{n=1}^{\infty} p_{m-1}(n)x^n\\
&=m(-p_{m-1}(0)+\sum_{n=0}^{\infty} p_{m-1}(n)x^n)\\
&=m(-p_{m-1}(0)+s_{m-1}(x))\\
&=ms_{m-1}(x)-mp_{m-1}(0)\\
&=ms_{m-1}(x)-1
\qquad\text{for } m=1\\
&=ms_{m-1}(x)
\qquad\text{for }m \ge 2\\
\end{array}
$
We have
$s_0(x)
=\dfrac1{1-x}
$.
Therefore
$(1-x)s_1(x)
=s_0(x)-1
=\dfrac{x}{1-x}
$
so
$s_1(x)
=\dfrac{x}{(1-x)^2}
$.
For
$m \ge 2$,
$s_m(x)
=\dfrac{ms_{m-1}(x)}{1-x}
$
From this,
$s_2(x)
=\dfrac{2s_{1}(x)}{1-x}
=\dfrac{2x}{(1-x)^3}
$.
By an easy induction,
$s_m(x)
=\dfrac{m!x}{(1-x)^{m+1}}
$.

A: Very elegant solution from Math Lover indeed, let me provide you a solution that's a bit more hands on:
$$S = \frac{2}{10} + \frac{6}{10^2} + \frac{12}{10^3} +\frac{20}{10^4} + \ ...$$
Multiply both sides by the factor $\frac{1}{10}$:
$$\frac{S}{10} = \frac{2}{10^2} + \frac{6}{10^3} + \frac{12}{10^4} +\frac{20}{10^5} + \ ...$$
Evaluate $S - \frac{S}{10}$:
$$S - \frac{S}{10} = \frac{2}{10} + \Big(\frac{6}{10^2} - \frac{2}{10^2}\Big) + \Big(\frac{12}{10^3} - \frac{6}{10^3}\Big) +\Big(\frac{20}{10^4} - \frac{12}{10^4}\Big) + \ ...$$
$$S - \frac{S}{10} = \frac{2}{10} + \frac{4}{10^2} + \frac{6}{10^3} +\frac{8}{10^4} + \ ...$$
And let's multiply this result by $\frac{1}{10}$:
$$\frac{S}{10} - \frac{S}{10^2} = \frac{2}{10^2} + \frac{4}{10^3} + \frac{6}{10^4} +\frac{8}{10^5} + \ ...$$
And let's subtract $\frac{S}{10} - \frac{S}{10^2}$ from $S - \frac{S}{10}$ using the same logic:
$$\Bigg(S - \frac{S}{10}\Bigg) - \Bigg(\frac{S}{10} - \frac{S}{10^2} \Bigg) = \frac{2}{10} + \Big(\frac{4}{10^2} - \frac{2}{10^2}\Big) + \Big(\frac{6}{10^3} - \frac{4}{10^3}\Big) + \Big(\frac{8}{10^4} - \frac{6}{10^4}\Big) + \ ...$$
$$\Bigg(S - \frac{S}{10}\Bigg) - \Bigg(\frac{S}{10} - \frac{S}{10^2} \Bigg) = \frac{2}{10} + \frac{2}{10^2} + \frac{2}{10^3} +\frac{2}{10^4} + \ ...$$
And now let's multiply by $\frac{1}{10}$ to get a new sum, then we subtract the new sum from the old sum.. again. This time however we can see that all of the terms cancel each other out except for the first fraction $\frac{2}{10}$:
$$\Bigg(\Bigg(S - \frac{S}{10}\Bigg) - \Bigg(\frac{S}{10} - \frac{S}{10^2} \Bigg)\Bigg) - \Bigg(\frac{\Bigg(S - \frac{S}{10}\Bigg) - \Bigg(\frac{S}{10} - \frac{S}{10^2} \Bigg)}{10}\Bigg)\Bigg) = \frac{2}{10}$$
Now simplify that mess and we get:
$$\frac{729}{10^3}S = \frac{2}{10}$$
$$729S = 200$$
$$S = \frac{200}{729}$$
So the correct answer is (4): $\frac{200}{729}$


text:
Q: How can I process outgoing mail with mutt? Is it possible to alter outgoing emails with mutt? I need it at the MIME level, just before a message is passed on to an SMTP server.
For example: My language uses diacritics, but there are still some people with old email clients that can't handle it. It would be convenient if I could add another MIME part to a message with a variant with stripped diacritic accents.
I could create some kind of SMTP filter, but then I'd lose the possibility of giving the sender some feedback and recovery in the case of an error. If for some reason the filter failed, I'd like to display a message to the user and ask how to continue.


text:
Q: How to easily copy hyperlinks in web pages Two related questions that come up for me in Firefox and perhaps elsewhere in Windows 7 when coming across a link like this: How to Select Hyperlink Text in Google Chrome?

*

*While reading html/a web page, I want to select some text that happens to be a hyperlink. If it's one word and not a hyperlink, I could double-click. Since it's a link, I'd like to have some ctrl/alt/RMB shortcut to select the link so that I can quickly copy the text.

*Same question as above, though I want to copy the text and its hyperlinkto paste into a Rich/HTML editor/doc. For example, I'm reading an article that has embedded links and I'd like to paste that embedded link into an email so that the recipient sees the text and can also follow the link, just like it was in the original article.
Both of these scenarios boil down to the ability to easily select hyperlinked text. I waste a surprising amount of time trying to figure out where I can put my cursor to start dragging across a link so that I can copy either the text or the text with its link.
I've seen questions asking this for chrome more than firefox - maybe there's a FF plugin. BTW If I just wanted the link in FF, I could right-click anywhere in the link/text and choose Copy Link Location, but I want to copy the text with and without the link, not just the link.

A: to select some text from a link, hold ALT, start selecting the text and then move slightly the cursor from the link and release it,
To copy the link (without the text in front) you could simply drag it directly into any text editor :
drag it over the icon of the editor in the Taskbar (the editor window will pop up) and drop it there. it will shows as below
http:// superuser.com/questions/173200/how-to-select-hyperlink-text-in-google-chrome
another option is to select and right click the whole link, then go to [view selection source] and you will get the full HTML code of the link.

A: You can use LinkSidebar addon for Firefox to copy multiple links at one time. After installing the addon, open the Preferences window and make sure you select "When I click on a link in the sidebar Copy Link Location". Then open a web page and activate the Links Sidebar using Firefox' menu ("View > Sidebar > Links" or Ctrl + Shift + L). Now you can see all of the links in that web page. Just hold Ctrl and select the links you want by clicking on them, and then paste in Notepad or any other text program.
I've just tested this on my PC and it works.


text:
Q: Select Distinct Years and Months for Django Archive Page I want to make an archive_index page for my django site. However, the date-based generic views really aren't any help. I want the dictionary returned by the view to have all the years and months for which at least one instance of the object type exists. So if my blog started in September 2007, but there were no posts in April 2008, I could get something like this
2009 - Jan, Feb, Mar
2008 - Jan, Feb, Mar, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
2007 - Sep, Oct, Nov, Dec

A: This will give you a list of unique posting dates:
Posts.objects.filter(draft=False).dates('post_date','month',order='DESC')

Of course you might not need the draft filter, and change 'post_date' to your field name, etc.

A: I found the answer to my own question.
It's on this page in the documentation.
There's a function called dates that will give you distinct dates. So I can do
Entry.objects.dates('pub_date','month') to get a list of datetime objects, one for each year/month.

A: You should be able to get all the info you describe from the built-in views. Can you be more specific as to what you cannot get? This should have everything you need:
django.views.generic.date_based.archive_month

Reference page (search for the above string on that page)


text:
Q: How can I render a React component inside a DOM node retrieved via class name? HTML:

JavaScript:
import ReactDOM from "react-dom";

function App() {
    return ReactDOM.render(

Hello, world!
,
        document.getElementsByClassName("root")
    );
}

export default App;

When this code gets compiled I get the following  "Error: Target container is not a DOM element."
Does anyone know why?

A: *

*You are fetching multiple elements instead of one. The second argument in ReactDOM.render should be an element, not a list of elements.

*In case you want to go using class instead of id, it might be more prudent to use document.querySelector(".root") as your second argument.

A: document.getElementsByClassName() gives an array in return instead of an element.
You can either do something like this -
document.getElementsByClassName("root")[0]

or change do getElementById("root");
and change class="root" to id="root".

A: the method getElementsByClassName returns an array-like object and not a DOM element like react-dom requires (DOCS).
In case you want to quesry a single DOM element with a class name you can use the querySelector method which returns the first element within the document that matches the specified selector
document.querySelector(".root")


text:
Q: Opening HiSuite daemon on Huawei phone I am trying to communicate my android Huawei Y330 to 'HiSuite' that runs under 'Wine'. Someone had suggested to first connect the Huawei Y330 to 'HiSuite' run under 'Windows'. Thus the 'HiSuite daemon', as he called it, would be installed on the phone.
I quote:
"First I installed wine. Then I downloaded HiSuite (Huawei's official PC suite) Link to download page and installed it.
Then I had to connect my phone to a windows PC, so the HiSuite daemon was installed on the phone.
When that is done, just open the HiSuite daemon on the phone and choose connect with wiFi. Enter the code on HiSuite on the PC, and voila. Now the phone is connected to ubuntu :)"
I have done this and could not find any 'HiSuite daemon' on my phone to open.
Any suggestions?

A: Installing this drivers solve it for me
https://github.com/siddht4/Huwaei_linux_drivers