text:
Q: ValueError: Cannot feed value of shape (40, 244, 244) for Tensor 'Placeholder_4:0', which has shape '(40, 224, 224, 3)' I am new to TensorFlow and machine learning. I'm trying to extract features of images. I extracted the features of 1 image successfully but I can't extract images[]
Here's the script:
#read image
def readfile(pathdir):
paths = glob.glob(pathdir + "*.png")
img_data_list=[]
imgs = [cv2.imread(file,cv2.IMREAD_COLOR) for file in paths]

for img in imgs:
       img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
       img_resize=cv2.resize(img,(244,244),3)

       img_data_list.append(img_resize)

img_data = np.array(img_data_list)
np.expand_dims(img_data, axis=0)
#img_data = array(img_data).reshape(1, 244,244,3)
names = [os.path.basename(path) for path in paths]
with open(pathdir + "value.txt") as file:
    nvl= file.readlines()
nvl = {line.split()[0]:float(re.sub(r'\n', "", line.split()[1])) for line
in nvl}
value =[]
for i in names:
  value.append(nvl[i])
return img_data, np.array(value), names
# extract features
def feature(train_imgs):
with tf.Session(config=tf.ConfigProto(gpu_options=
(tf.GPUOptions(per_process_gpu_memory_fraction=0.7)))) as sess:
#with tf.device('/cpu:0'):
  #with tf.Session() as sess:
      images = tf.placeholder("float", [np.shape(train_imgs)[0], 224,
224, 3])
     [bunch of code]
      return features

I get the following error:
ValueError                                Traceback (most recent call
last)
 <ipython-input-23-b21a5d063db6> in feature(train_imgs)
 47               vgg.build(images)
 48           print("Extracting feature...")
 ---> 49           features = sess.run(vgg.fc6, feed_dict=feed_dict)
 50           print('FC6 feature: ', features)
 51           print('Number of input: ', len(features))

 /usr/local/lib/python3.6/dist-
 packages/tensorflow/python/client/session.py in run(self, fetches,
feed_dict, options, run_metadata)
927     try:
928       result = self._run(None, fetches, feed_dict, options_ptr,
--> 929                          run_metadata_ptr)
930       if run_metadata:
931         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/usr/local/lib/python3.6/dist-
packages/tensorflow/python/client/session.py in _run(self, handle,
fetches, feed_dict, options, run_metadata)
1126                              'which has shape %r' %
1127                              (np_val.shape, subfeed_t.name,
-> 1128                               str(subfeed_t.get_shape())))
1129           if not self.graph.is_feedable(subfeed_t):
1130             raise ValueError('Tensor %s may not be fed.' %
subfeed_t)

ValueError: Cannot feed value of shape (40, 244, 244) for Tensor
Placeholder_4:0', which has shape '(40, 224, 224, 3)'

What's Wrong and how to fix this problem.
Thank in advance!!

A: When you apply cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) you are changing your image to gray scale, obtaining only one color channel. Your images' shape is now (?,244,244), and you are trying to feed a placeholder of shape (?,244,244,3).
If you want to use gray scale images, you should reshape your set of images to (?,244,244,1) and use a placeholder of the same shape.


text:
Q: iOS: [self.view setNeedsDisplay]; I seem to have forgotten the basics regarding this or perhaps I am just too tired.
I have a view controller and a view that is a subclass of UIView that is named MyViewClass.
In viewDidLoad of my viewController I alloc and init self.myView like this:
self.myView = [[MyViewClass alloc] initWithFrame:(CGRect){{0, 0}, 320, 480}];
self.view = self.myView;

At some time in my viewController, I would call [self.view setNeedsDisplay];. No problem here.
I expose a property in MyViewClass.h:
@property(nonatomic) i;

The property i will be used in drawRect in myView;
So, from my viewController I would set it like so:
self.myView.i = 100;

So my question is:
Why am I able to call [self.view setNeedsDisplay]; in my view controller without needing to call [self.myView setNeedsDisplay];and drawRect will be called in myView, but I can't just do self.view.i in my view controller as self.myView has been assigned to self.view already in viewDidLoad in my view controller?

A: You are able to call [self.view setNeedsDisplay], but not self.view.i because UIViewController's view property is of type UIView.

self.myView has been assigned to self.view already in viewDidLoad

Remember that the actual assignment happens at runtime, while compiler errors are generated at compile time. The compiler has no idea in what order your view controller's methods may be called, so it can't make any guesses about the actual type of a property's value beyond the property's original declaration. As far as Xcode is concerned, self.view is just a UIView.
As danh suggested above, you can override the property declaration to inform the compiler that your view is of type MyView. Although, your approach of using the self.myView property may be preferred anyway: it allows you to change up the view hierarchy in the future without changing your interface, and doesn't muck with inherited methods. UITableViewController does the same thing: both the view and tableView properties return the same view instance, but the properties are typed differently.
It's important to remember that the type of a property is not necessarily the same as the type of its value. self.view may have been assigned to an instance of MyView, but the property is still of type UIView. Regardless of the type of object assigned to it, the property's accessor is still a method with return type UIView.
So, as far as the compiler is concerned, self.view is nothing more than a plain old UIView, even if you know that it isn't.
I think it would help to elaborate more on what properties are, and differentiate between the property and the instance. When you create a property like this:
@interface MyViewController : UIViewController

@property(strong, nonatomic) MyView *myView;

@end

The compiler translates it into a variable, an accessor method (the "getter"), and a mutator method (the "setter"). The property is merely shorthand for declaring the methods like so:
@interface MyViewController : UIViewController
{
    MyView *_myView;
}

- (MyView *)myView; // accessor / getter
- (void)setMyView:(MyView *)myView; // mutator / setter

@end

@implementation MyViewController

- (MyView *)myView
{
    return _myView;
}

- (void)setMyView:(MyView *)myView
{
    _myView = myView;
}

@end

When you call self.myView, or self.view, you are actually calling the accessor method; it's equivalent to [self myView] or [self view]. What it returns is a pointer to an object in memory. Because you assigned self.view = self.myView, both properties are set to the same object; thus, both self.view and self.myView return a pointer to the same object.
To summarize:

*

*Assigning self.view = self.myView generates no compiler error, because MyView is a subclass of UIView. Note that assigning self.myView = self.view would generate a warning because UIView is not a subclass of MyView

*Calling [self.view setNeedsDisplay] causes myView to draw itself, because the same instance is assigned to both properties. If you log the descriptions (NSLog(@"view=%@, myView=%@", self.view, self.myView)) for both properties, you can observe that they have the same memory address

*You cannot call self.view.i because the view property is declared to have type UIView, and UIView has no method named i.

A:
In viewDidLoad of my viewController I alloc and init self.myView like this:

self.myView = [[MyViewClass alloc] initWithFrame:(CGRect){{0, 0}, 320, 480}];
self.view = self.myView;

Never never never do that in viewDidLoad. viewDidLoad means you already have a view. You should never ever change your view controller's view.
It is fine (and required) to set your view loadView. That is what it is for. But in viewDidLoad, absolutely not.

A: You're trying to substitute the VCs view with a UIView subclass, have it work in all the usual ways, but also give the vc's code access to properties on the subclass?  I think you can get there by overriding the view getter:
- (MyView *)view {
    return (MyView *)[super view];
}

Also, you can setup the custom view in IB as the VC's view, so there's no need to do anything in loadView.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configure DD-WRT to Limit Bandwidth on Devices I have flashed DD-WRT firmware to my TP-Link WRT841-N router, set the basic network configuration & wireless. I want to limit bandwidth on a user who is always using torrents which is causing my network connection slowdown. Or is there any way to block these bit-torrent clients?

A: I am surprised no one answered this.
Yes this is possible, there are a couple ways of achieving what you are trying to do. in my experience, when you do this with roommates who are splitting costs with you, you end up being viewed as an internet connection dictator. There are three ways to do this.

*

*Content filtering - This would block all P2P on the network, and may just start a cold war of people trying to bypass the measures you put in place. and i don't think it catches encrypted P2P traffic.

Under Access restrictions, Create a new policy.
PC's> edit list of clients> put traffic offenders in here specific or range
Days = everyday
Time = 24 hours
Catch all P2P protocols = checked
Website Blocking by Keyword = tracker announce and d1:ad2

*Quality of Service - This acts dynamically as opposed to static bandwidth settings, if no one else is using a priority service then the other users can P2P their hearts out. but as soon as someone uses a priority service the router automatically throttles the p2p to whatever is left over from legitimate traffic.

before enabling QOS you need to get an accurate speed test of your connection. either test it while no one is using the connection or disconnect the other users while you are doing it. write down the maximum download and upload speed. (usually displayed in Mbps) convert what you wrote down to kbps. it will be used in the config
Under the NAT/QOS tab > QOS
Start QOS = Enable
Packet Scheduler = HFSC
Max up = 10% less than your upload speed test
Max down = 10% less than your download speed test
Optimize for Gaming = your choice
under services priority, start adding services you don't want other traffic interfering with.
example:
Google Voice    - Premium
Skype           - Express
Http/Https      - Standard
ftp             - Bulk
any traffic not delineated goes to the lowest queue.

*MAC-address guaranteed bandwidth - This is the easiest to set up, but its not dynamic. any reservation you set here will forevermore limit the device with this MAC-Address. for instance, if you and another person are sharing a ISP connection, you could set two MAC addresses here for two PC's to get half of all the available bandwidth. neither PC would be able to go over that cap,
even if the other roommates PC was turned off. you would not be able to access the additional bandwidth.

its also under NAT/QOS > QOS > all the way at the bottom of the page.
Start QOS = Enable
Packet Scheduler = HFSC
Max up = 10% less than your upload speed test
Max down = 10% less than your download speed test
Optimize for Gaming = your choice
this is done under the MAC priority section. add the mac of the offending client end station. enter MAX up and DOWN in kbps. save and apply.
You may or may not have to reboot the router for the changes to take effect, and you're done.


text:
Q: Function type has ambiguous reference to member nextInt() My intent is to use nextInt(upperBound: Int)
let randomInt: (Int) -> Int = GKRandomSource.sharedRandom().nextInt
var myNumber = randomInt(10)

Produce error: Playground execution failed: error: ambiguous reference to member 'nextInt()'
Why?
Swift 3, xCode 8 beta 6

A: Your code compiles fine in a real iOS app, as shown by this screen shot:

That, an actual iOS app project, is the real test of whether code is valid. Playgrounds do not represent real Swift environments.


text:
Q: How to Iterate Over a List in Python I have a simple for loop to iterate over a list of various dates. For each item in the list, I exclude the timezone by taking only the first 10 characters. However, when I pass the object to my template only the first value in the list is being returned for all values.
views.py
for opportunity in opportunities:
    temp = opportunity['expectedCloseDate']
    time = temp[:10]

context { 'time': time }
return render(request, 'website', context)

template.html

    <input class="input" name="close_date" id="close_date" type="date" value="{{ time }}" disabled>

A: You can construct a list of times:
times = [opportunity['expectedCloseDate'][:10] for opportunity in opportunities]
return render(request, 'website', {'times': times})
and then iterate over this in your template:

    {% for time in times %}
        <input class="input" name="close_date" id="close_date" type="date" value="{{ time }}" disabled>
    {% endfor %}

That being said, it looks like you are building a form manually. It is usually better to use Django's Form object [Django-doc] here.
If you want to loop concurrently over two lists, you can make use of zip, like:
times = [opportunity['expectedCloseDate'][:10] for opportunity in opportunities]
opps_times = zip(opportunities, times)
return render(request, 'website', {'opps_times': opps_times})
and render this with:
{% for opportunity, time in opps_times %}

{% endfor %}

A: You are always overwriting time in each iteration. Try something like
time = []
for opportunity in opportunities:
    temp = opportunity['expectedCloseDate']
    time.append(temp[:10])

context = { 'time': time }
return render(request, 'website', context)


text:
Q: why is python statistics.mean() function acting differently when passed a numpy.ndarray or a list? why does statistics.mean act so weird? when passed a numpy.ndarray outputs the average
statistics.mean(np.array([1,4,9]))
4

when passed a list outputs the actual mean
statistics.mean([1,4,9])
4.666666666666667

I'm using python 3.7

A: No, it doesn't return the median in the first case. It returns the mean value as numpy.int64 because the input is an array of non-primitive integers.
If you pass non-primitive objects to statistics.mean the result will be converted to the input data type. In your case statistics.mean does something equivalent to:
numpy.int64(sum(np.array([1,4,9]))/len(np.array([1,4,9])))

I'm using Python 3.8.
Here is the code for mean:
def mean(data):
    """Return the sample arithmetic mean of data.

    >>> mean([1, 2, 3, 4, 4])
    2.8

    >>> from fractions import Fraction as F
    >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
    Fraction(13, 21)

    >>> from decimal import Decimal as D
    >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
    Decimal('0.5625')

    If ``data`` is empty, StatisticsError will be raised.
    """
    if iter(data) is data:
        data = list(data)
    n = len(data)
    if n < 1:
        raise StatisticsError('mean requires at least one data point')
    T, total, count = _sum(data)
    assert count == n
    return _convert(total/n, T)

Here is the code for _sum:
def _sum(data, start=0):
    """_sum(data [, start]) -> (type, sum, count)

    Return a high-precision sum of the given numeric data as a fraction,
    together with the type to be converted to and the count of items.

    If optional argument ``start`` is given, it is added to the total.
    If ``data`` is empty, ``start`` (defaulting to 0) is returned.

    Examples
    --------

    >>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75)
    (<class 'float'>, Fraction(11, 1), 5)

    Some sources of round-off error will be avoided:

    # Built-in sum returns zero.
    >>> _sum([1e50, 1, -1e50] * 1000)
    (<class 'float'>, Fraction(1000, 1), 3000)

    Fractions and Decimals are also supported:
    >>> from fractions import Fraction as F
    >>> _sum([F(2, 3), F(7, 5), F(1, 4), F(5, 6)])
    (<class 'fractions.Fraction'>, Fraction(63, 20), 4)

    >>> from decimal import Decimal as D
    >>> data = [D("0.1375"), D("0.2108"), D("0.3061"), D("0.0419")]
    >>> _sum(data)
    (<class 'decimal.Decimal'>, Fraction(6963, 10000), 4)

    Mixed types are currently treated as an error, except that int is
    allowed.
    """
    count = 0
    n, d = _exact_ratio(start)
    partials = {d: n}
    partials_get = partials.get
    T = _coerce(int, type(start))
    for typ, values in groupby(data, type):
        T = _coerce(T, typ)  # or raise TypeError
        for n,d in map(_exact_ratio, values):
           count += 1
            partials[d] = partials_get(d, 0) + n
    if None in partials:
        # The sum will be a NAN or INF. We can ignore all the finite
        # partials, and just look at this special one.
        total = partials[None]
        assert not _isfinite(total)
    else:
        # Sum all the partial sums using builtin sum.
        # FIXME is this faster if we sum them in order of the denominator?
        total = sum(Fraction(n, d) for d, n in sorted(partials.items()))
    return (T, total, count)

Here is the code for _convert:

def _convert(value, T):
    """Convert value to given numeric type T."""
    if type(value) is T:
        # This covers the cases where T is Fraction, or where value is
        # a NAN or INF (Decimal or float).
        return value
    if issubclass(T, int) and value.denominator != 1:
        T = float
    try:
        # FIXME: what do we do if this overflows?
        return T(value)
    except TypeError:
        if issubclass(T, Decimal):
            return T(value.numerator)/T(value.denominator)
        else:
            raise

A: No, it is not median. statistics.mean() expect the list, you get the rounded value because you pass a numpy array of integers. To calculate mean of numpy array use np.mean(np.array([1,4,9]))

A: This is due to the definition of the function statistics.mean. The function uses a subroutine _convert.

*

*In the case of a list, it will be called as _convert(Fraction(14, 3), int).
By being int a subclass of int the code executed will be
if issubclass(T, int) and value.denominator != 1:
    T = float
try:
    return T(value)

*In the numpy array case it will be called as _convert(Fraction(14, 3), np.int64) and the code executed will just be
try:
  return T(value)

since np.int64 is not a subclass of int.


text:
Q: How can I implement JPA Auditing like functionality in Quarkus I'm using Quarkus framework, and I want to implement functionality similar to JPA auditing like:
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class EntityAuditInfo {

    @CreatedBy
    @Basic(optional = false)
    @Column(name = "created_by", nullable = false)
    private Integer createdBy;
    @CreatedDate
    @Basic(optional = false)
    @Column(name = "created_on", nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdOn;
    @LastModifiedBy
    @Column(name = "modified_by")
    private Integer modifiedBy;
    @LastModifiedDate
    @Column(name = "modified_on")
    @Temporal(TemporalType.TIMESTAMP)
    private Date modifiedOn;
....

I have tried searching it in Quarkus documention but didn't.

A: Yes, this is supported (although not really documented as it's a standard Hibernate/JPA feature).
You can see some example usages in the Quarkus integration tests here.


text:
Q: Django: Difference between using class and method based view I am concerned about whether having less code is the only benefit of using class-based views or they have also runtime benefits?

A: They're the tiniest bit slower due to more mangling occurring before they get to actual view code, but that's far outweighed by the ease of use and reuse for code time.


text:
Q: Proper way to clear asynchronous work in redux middleware I have the following middleware that I use to call similar async calls:
import { callApi } from '../utils/Api';

import generateUUID from '../utils/UUID';

import { assign } from 'lodash';

export const CALL_API = Symbol('Call API');

export default store => next => action => {
  const callAsync = action[CALL_API];

  if(typeof callAsync === 'undefined') {
    return next(action);
  }

  const { endpoint, types, data, authentication, method, authenticated } = callAsync;

  if (!types.REQUEST || !types.SUCCESS || !types.FAILURE) {
    throw new Error('types must be an object with REQUEST, SUCCESS and FAILURE');
  }

  function actionWith(data) {
    const finalAction = assign({}, action, data);
    delete finalAction[CALL_API];

    return finalAction;
  }

  next(actionWith({ type: types.REQUEST }));

  return callApi(endpoint, method, data, authenticated).then(response => {
    return next(actionWith({
      type: types.SUCCESS,
      payload: {
        response
      }
    }))
  }).catch(error => {
    return next(actionWith({
      type: types.FAILURE,
      error: true,
      payload: {
        error: error,
        id: generateUUID()
      }
    }))
  });
};

I am then making the following calls in componentWillMount of a component:
  componentWillMount() {
    this.props.fetchResults();
    this.props.fetchTeams();
  }

fetchTeams for example will dispatch an action that is handled by the middleware, that looks like this:
export function fetchTeams() {
  return (dispatch, getState) => {
    return dispatch({
      type: 'CALL_API',
      [CALL_API]: {
        types: TEAMS,
        endpoint: '/admin/teams',
        method: 'GET',
        authenticated: true
      }
    });
  };
}

Both the success actions are dispatched and the new state is returned from the reducer.  Both reducers look the same and below is the Teams reducer:
export const initialState = Map({
  isFetching: false,
  teams: List()
});

export default createReducer(initialState, {
  [ActionTypes.TEAMS.REQUEST]: (state, action) => {
    return state.merge({isFetching: true});
  },

  [ActionTypes.TEAMS.SUCCESS]: (state, action) => {
    return state.merge({
      isFetching: false,
      teams: action.payload.response
    });
  },

  [ActionTypes.TEAMS.FAILURE]: (state, action) => {
    return state.merge({isFetching: false});
  }
});

The component then renders another component that dispatches another action:
render() {
  <div>
   <Autocomplete items={teams}/>
  </div>
}

Autocomplete then dispatches an action in its componentWillMount:
class Autocomplete extends Component{
  componentWillMount() {
    this.props.dispatch(actions.init({ props: this.exportProps() }));
  }

if an error happens in the autocomplete reducer that is invoked after the SUCCESS reducers have been invoked for fetchTeams and fetchResults from the original calls in componentWillMount of the parent component and the error will be handled in the Promise.catch of the callApi method that happens in the middleware.

      return callApi(endpoint, method, data, authenticated).then(response => {
        return next(actionWith({
          type: types.SUCCESS,
          payload: {
            response
          }
        }))
      }).catch(error => {
        return next(actionWith({
          type: types.FAILURE,
          error: true,
          payload: {
            error: error,
            id: generateUUID()
          }
        }))
      });
    };

This is because it is happening with in the same tick of the event loop.  If I introduce some asynchronicity in the Autcomplete componentWIllMount function then the error is not handled  in the Promise catch handler of the middleware

    class Autocomplete extends Component{
      componentWillMount() {
        setTimeout(() => {
          this.props.dispatch(actions.init({ props: this.exportProps() }));
        });
      }

Should I have the callApi function execute on a separate event loop tick?


text:
Q: How To Insert Data with Spring Data JPA Relationships hopefully this is an easy question, but I'm pretty new with JPA and having difficulty determining how to format a JSON POST request body that is sent to a Spring API. I have two entities, Product and Barcode with the following relationship:

*

*One Product can have many barcodes that point to it (OneToMany)

*One Barcode can point to only one Product (OneToOne)

The relationship is defined by a product_id column in the Barcode table.
Relationship definition in Barcode entity:
@OneToOne // one barcode relates to one product
private ProductEntity product;

The relationship definition in Product:
@OneToMany(cascade = CascadeType.ALL)
private List<BarcodeEntity> barcodes = new ArrayList<>();

My question is, how can I do a JSON POST request to insert a Barcode that is related to a Product already in the database? Would I need to pass the entire Product entity or is there a way to just pass the product_id alone?
How I would like to create a new Barcode entry when the Product already exists:
{
  "barcode": "string",
  "barcodeStatus": "string",
  "codeStandard": "string",
  "product": 1,
  "title": "string",
  "unitQuantity": 0
}

Instead of having to do the following, which I believe will result in an error because the product already exists:
{
  "barcode": "string",
  "barcodeStatus": "string",
  "codeStandard": "string",
  "product": {
     productInfo: "...",
     ....,
  },
  "title": "string",
  "unitQuantity": 0
}

Essentially, I'm trying to figure out how you can insert a new entity and define its relationship to another entity that is already present in the database. I'm sure I'm over complicating it.
Endpoint in Product controller:
@PostMapping(produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
public ProductRest createProduct(@Valid @RequestBody ProductRequestModel productDetails) throws Exception {
    ProductRest returnValue = new ProductRest();

    ModelMapper modelMapper = new ModelMapper();
    ProductDto productDto = modelMapper.map(productDetails, ProductDto.class);

    ProductDto createdProduct = productService.createProduct(productDto);
    returnValue = modelMapper.map(createdProduct, ProductRest.class);

    return returnValue;
}

createProduct method in Product service file:
public ProductDto createProduct(ProductDto product) {
    if (productRepo.findByTitle(product.getTitle()) != null)
        throw new ServiceException("Record with matching title already exists");

    // Set product id for each barcode
    for (int i = 0; i < product.getBarcodes().size(); i++) {
        ProductBarcodeDto barcode = product.getBarcodes().get(i);
        barcode.setProduct(product);
        product.getBarcodes().set(i, barcode);
    }

    ModelMapper modelMapper = new ModelMapper();
    ProductEntity productEntity = modelMapper.map(product, ProductEntity.class);

    ProductEntity storedProductDetails = productRepo.save(productEntity);

    ProductDto returnValue = modelMapper.map(storedProductDetails, ProductDto.class);
    return returnValue;
}

Fields in ProductDto (defines getters/setters and empty constructor; just not shown):
public class ProductDto {

private long id;
private List<BarcodeDto> barcodes;
private String title;
private String description;
private String SKU;
private ProductVariationDto variation;
private double cost;
private double retailPrice;
private LocalDate launchDate;
private LocalDate discontinueDate;
private String discontinueReason;
private String salesChannel;
private LabelDto label;
private int secondaryStockLevel;
private int primaryStockLevel;
private LocalDateTime modifiedDate;
private LocalDateTime createdDate;
private String productStatus;
private List<SupplierDto> suppliers;
}

I had it set up so that ProductRequestModel expected a BarcodeEntity. Is this the correct or should I change it to expect just an integer value for the Barcode ID?
createBarcode endpoint in Barcode Controller:
@PostMapping(produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
public BarcodeRest createBarcode(@Valid @RequestBody BarcodeRequestModel barcodeDetails) throws Exception {
    BarcodeRest returnValue = new BarcodeRest();

    ModelMapper modelMapper = new ModelMapper();
    BarcodeDto barcodeDto = modelMapper.map(barcodeDetails, BarcodeDto.class);

    BarcodeDto createdBarcode = barcodeService.createBarcode(barcodeDto);
    returnValue = modelMapper.map(createdBarcode, BarcodeRest.class);

    return returnValue;
}

createBarcode method implementation:
public BarcodeDto createBarcode(BarcodeDto barcode) {
    ModelMapper modelMapper = new ModelMapper();

    if (barcodeRepo.findByBarcode(barcode.getBarcode()) != null)
        throw new ServiceException("Barcode value already exists.");

    BarcodeEntity barcodeEntity = modelMapper.map(barcode, BarcodeEntity.class);
    BarcodeEntity storedBarcode = barcodeRepo.save(barcodeEntity);

    BarcodeDto returnValue = modelMapper.map(storedBarcode, BarcodeDto.class);
    return returnValue;
}

A: Firstly, there seems to be an issue with the Database Schema Mapping:
One Product : Many Barcodes (One to Many) [NO ISSUES]
Many Barcodes : One Product (Many to One, instead of One to One) [HAS ISSUES]
Secondly, yes you can use just the 'product_id' to update the barcode. It'd be better if you post the controller code once. Would be easier to find any issues with that.


text:
Q: Adding a UIImageView to a Table View in Storyboard I want to add an ImageView to the bottom of my Table View (in a fixed position over the cells) so that I can place a custom tab bar there. However, when I drag the Image View to the Table view in Storyboard it attaches itself to the bottom of the prototype cells. Does anyone know how to do this?

A: Instead of using an imageview, slect your tableView ViewController in the storyboard, and in the simulated metrics section of the Utilities pane (right pane), select Tab Bar for the "bottom bar" setting.
Then you can drag your tabBarItems to the simulated tab bar.


text:
Q: In JPA, is there a way to prevent an object from being instantiated more than once? If I have an instance of a class like Account it might be desirable to prevent an instance corresponding to one user's account from being instantiated simultaneously more than once. Is this possible using JPA?
To clarify as suggested by Edwin: In a system there are multiple Accounts. When someone logs in, we would probably instantiate that person's Account in order to determine what privileges that person has. What if a system admin wanted to access that same Account, perhaps changing the privileges while the owner of the Account is still using it? Is there a way to prevent this or is there a way to notify the system admin that the Account has been instantiated?

A: It depends on what you mean. The way JPA implementations work already guarantee that when you ask for an entity to your entity manager during a given a transaction, you will always get the  same entity.
So, entities are tied to the existence of their context and in JPA there are different types of contexts.
See the JPA 2.1 Specification chapter 7 on Entity Managers and Persistence Contexts.
Now, this will not prevent anyone from creating instances of your class and use them as they see fit. Or that you have detached entities in your application. For example, prior to you persisting a new entity, it is detached and not under the control of the entity manager.
You may consider reading section 3.2 Entity Instance Life Cycle in the same specification mentioned above.
So, perhaps you should tell us what you want to do and we could help with ideas of how to do it. Instead of giving us what you think is the answer. Start with a description of what you think is the problem that you believe you could solve if you could prevent JPA from providing multiple/different instances of a given entity.


text:
Q: Eigenvalues of a $A^T A$ Given the matrix of order $1\times{n}$,  $A=(a_1, a_2, ..., a_n)$ , where $a_i$ are real;
The question is to find all eigenvalues of $A^T A$.
I have proved that it is a non-invertible matrix, therefore $0$ is one of the values.
And the product matrix is an $nxn$ matrix with the diagonal elements being $a_1^2, a_2^2,...,a_n^2$.
I am struggling with finding the other eigenvalues, tried by calculating the det of $A - aI$, but didn't go anywhere.

A: Hint: Suppose that $v$ is an $n \times 1$ vector orthogonal to $A$ (or more precisely, $w$ is a $1 \times n$ vector orthogonal to $A$, and $v = w^t$). What do you get when you compute $A^{*}Av$?

A: $$A^tA = \begin{pmatrix}
   a_1a_1 & a_1a_2 & a_1a_3 & \dots   & a_1a_n\\
   a_2a_1 & a_2 a_2 & a_2a_3 & \dots & a_2a_n \\
   \vdots &  \vdots & \vdots & \vdots & \vdots \\
   a_na_1 & a_na_2 & a_na_3 & \dots & a_na_n
\end{pmatrix}$$
All the columns can be obtained by mutiplying by a scalar the first column, so $rank(A^tA)=1$. So $0$ is an eigen value with multiplicity $n-1$. The sum of eigen values is equal to the trace of the matrix, thus you can easily find the last eigenvalue.

A: Consider the definition of an eigenvalue / eigenvector pair,
$$
A^T A v = \lambda v.
$$
Now extend $A$ to an orthogonal basis: so let $A_1, A_2, \ldots, A_n$ be an orthogonal basis for $\mathbb{R}^n$, where $A_1 = A^T$. Write $v$ in this basis:
$$
v = a_1 A^T + a_2 A_2 + a_3 A_3 + \cdots + a_n A_n.
$$
Then,
$$
A^T Av = a_1 A^T A A^T + a_2 A^T A A_2 + a_3 A^T A A_3 + \cdots + a_n A^T A A_n.
$$
Because the basis is orthogonal, $A A_k = 0$ for any $k \ge 2$. Also $A A^T$ = $\|A\|^2$. So this just reduces to
$$
A^T A v = a_1 A^T \|A\|^2.
$$
The only way this can be equal to $\lambda v$ is if $\lambda = 0$ and the component $a_1 = 0$, or if $\lambda = \|A\|^2$ and the components $a_2, a_3, \ldots, a_n$ are all $0$.
So the only eigenvalues are $0$ and $\|A\|^2$, and we get the corresponding eigenvectors as well.


text:
Q: Popup at specified position I'm following this W3Schools page to create a modal popup. Below code is copied from the original page.
HTML:
<input id="myInputTextBox" />

<button id="myBtn">Open Modal</button>

    ×

Some text in the Modal..

Style:
 /* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 15% auto; /* 15% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}

Javascript:
// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

How can I position this popup just below or above the myInputTextBox, depending on the space available in the viewport? Note that I need to be able to handle click event on the modal, so that, if click occurs outside the model content, I will close the popup.

A: Here is a CSS based solution:

// Get the modal
        var modal = document.getElementById('myModal');

        // Get the button that opens the modal
        var btn = document.getElementById("myBtn");

        // Get the  element that closes the modal
        var span = document.getElementsByClassName("close")[0];

        // When the user clicks the button, open the modal
        btn.onclick = function () {
            modal.style.display = "block";
        }

        // When the user clicks on  (x), close the modal
        span.onclick = function () {
            modal.style.display = "none";
        }

        // When the user clicks anywhere outside of the modal, close it
        window.onclick = function (event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        }
.modal {
            display: none;
            /* Hidden by default */
            position: fixed;
            /* Stay in place */
            z-index: 1;
            /* Sit on top */
            padding-top: 100px;
            /* Location of the box */
            left: 0;
            top: 0;
            width: 100%;
            /* Full width */
            height: 100%;
            /* Full height */
            overflow: auto;
            /* Enable scroll if needed */
            background-color: rgb(0, 0, 0);
            /* Fallback color */
            background-color: rgba(0, 0, 0, 0.4);
            /* Black w/ opacity */
        }
        /* Modal Content */

        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            left: 8px;
            position: absolute;
            top: 90px;
        }
        /* The Close Button */

        .close {
            color: #aaaaaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: #000;
            text-decoration: none;
            cursor: pointer;
        }

Modal Example

<input id="myInputTextBox" />

    <button id="myBtn">Open Modal</button>

            ×

Some text in the Modal..

https://jsfiddle.net/6esv2vsy/

A: You can move modal like this.
Please check my fiddle. :)
Move modal position
.modal-content{
    position = absolute;
    margin = auto;
    left = (your x) px;
    top = (your y) px;
}


text:
Q: Git problem - checking my users/personal folder I've got a little problem with git.
Today I started larning git, but something go wrong and now in visual studio see statement:
"The git repository at 'c: \ Users \ Personal' has too many active changes, only a subset of Git features will be enabled."
In github desktop I can see few hundred changes mostly in /appdata. I don't know how to stop this.
I tried to remove repository which was opened in this folder but nothing is working.

A: I think you ran git init in your home directory. So now there's a folder at C:\Users\Personal\.git. If you didn't intend this then you can just delete that directory.
It's normal to create a folder for each project. If you're using visual studio the normal thing is to have a C:\Users\You\Source\Repos folder where all your projects will live. So if you have a project in C:\Users\You\Source\Repos\YourProject you can cd into that directory an run git init to create a git repository for that project.


text:
Q: Which build.gradle file should I be updating to add fabric digits in a React Native Android project I'm following the instructions to add Twitter Fabric Digits to my Android React Native app and am at the Digits step where I update my build.gradle file.  Looking at the project I see a build.gradle file in my /android root and also one in my /android/app directory.
If I compare the sample gradle file shown in the Digits example, it seems to be a combination of the two files.  Which one am I supposed to be editing.  And, if one of the files is missing some of the configurations in the example, should I just add it?  For instance, the instructions say to add a maven url to buildscript.respositories and repositories, which suggests that I update the build.gradle in my android root since that has a buildscript config and an allprojects.repositories node.  However, it doesn't have a dependencies node or an android node or a plugin, those things are in the other build.gradle file, which doesn't have a respositories node.  Am I supposed to split the changes from the instructions into both build.gradle files?
Instructions from Digits
buildscript {
    repositories {
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.6.+'
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    compile 'com.android.support:appcompat-v7:18.0.0'
    compile('com.digits.sdk.android:digits:2.0.6@aar') {
        transitive = true;
    }
}

android {
    compileSdkVersion 17
    buildToolsVersion "18.1.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 18
    }
}

build.gradle from /android
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven { url 'https://maven.fabric.io/public' }
    }
}

build.gradle from /android/app
apply plugin: "com.android.application"

import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation
 *   entryFile: "index.android.js",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,somelongstring
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"]
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

apply from: "../../node_modules/react-native/react.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"

    defaultConfig {
        applicationId "com.foo"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile project(':react-native-fabric-digits')
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

A: Looking at the comment in build.gradle would lead me to believe that the dependencies should be placed in the build.gradle file in the app directory.
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files

I'm doing something with the Nearby Services API and placed the dependency in the build.gradle in the app directory and everything worked fine.


text:
Q: How to create a loop of get calls (axios) through a list and return the answer of all How to create a loop of get calls through a list and return the answer of all.
const axios = require('axios');
const id = ['234','9887']
axios.get(`https://myapi/api/id/${id}`, {
method: 'GET',
headers:{'xxxxxxxxxx': 'xxxxxxxxxxx',
}})

      .then(function (response = response.json()) {
// handle success
console.log = (response.data)
     })
.catch(function (error) {
// handle error
console.log(error);
})

A: I think this what you are looking for.
I have changed your fake API for a real one, so you can test.
const axios = require('axios');
const id = ['234','9887']

const promArr = id.map(
  id =>
    axios.get(
      `https://postman-echo.com/get?key=${1234}`,
      {
        method: 'GET',
        headers:{'xxxxxxxxxx': 'xxxxxxxxxxx',}
      }
    )
)

Promise.all(promArr)
  .then(function (responses) {
    // handle success
    responses.map(response => console.log(response.data))
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })


text:
Q: Any reason to save a file before converting to Base64 to pass on? I'm creating an attachment section for a webpage that takes said attachment, converts it to base64 and passes it to xml gateway.
Is there any reason for me to save said file locally? The file size limit is 5mb.
Current set up seems to work;
byte[] attachBytes = new byte[attach.ContentLength];
using (BinaryReader theReader = new BinaryReader(attach.InputStream))
{
      attachBytes = theReader.ReadBytes(attach.ContentLength);
}

model.filename = attach.FileName;
model.base64convert = Convert.ToBase64String(attachBytes);

VS Saving(File isn't required to be stored on the server)
attach.SaveAs("C:/temp/Attachfiles/" + attach.FileName);
byte[] attachBytes = new byte[attach.ContentLength];
using (BinaryReader theReader = new BinaryReader(attach.InputStream))
{
      attachBytes = theReader.ReadBytes(attach.ContentLength);
}

model.filename = attach.FileName;
model.base64convert = Convert.ToBase64String(attachBytes);

Mainly just wondering the downsides of doing it how I am. I'm thinking there is no difference as I am not reading the saved file back in but I'm still learning and don't want to miss anything.

A: Your question is a bit open ended, but answerable.
If you have to have some record of receiving the file before sending it on, then save it. However, there are downsides to saving a file

*

*you could run out of space

*the file, if it contains anything sensitive, is stored in the clear

*you're introducing a point of failure (e.g. can't save file) for no gain

So, as specified, don't do it. If your requirements evolve you can always re-evaluate that decision.
As mentioned in the comments, a save may be reasonable if you are doing something like a resend in case of failure; but even then I suggest not keeping the file around forever, and usually storage at/on a web server is a bad idea for the reasons above.


text:
Q: WSHShell.ExpandEnvironmentStrings with limited priviledges I must run a script on user accounts with limited privileges. In the script, there's a line that find the full path of a file specified and it must work with environment variables, for example %HOMEDRIVE%.
However, the command line
objShell.ExpandEnvironmentStrings("%HOMEDRIVE%")

throws an acess denied exception if the user is not an administrator.
How can I read this environment variable from an account with limited privledges?
Thanks!

A: Try  putting the following at the start of your script:
Set oShell = CreateObject("WScript.Shell")
strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
Const ssfPROFILE = &H28
Set oShell = CreateObject("Shell.Application")
strHomeFolder = oShell.NameSpace(ssfPROFILE).Self.Path

Then, when you need to reference the username you can use the following instead of "C:\Users...\" just put in:
= strHomeFolder & "\...\The Rest Of The Filepath eg.appdata\...\"

This should let you access the user-specific path and then continue on to find a specific file. It accesses which ever user who is logged in's home folder. If another user opens it it will access his/her homefolder instead.
I hope this helps!


text:
Q: How to store video tags into a database (MySQL)? In a video website every video can have more than 1 tag. I have a video table containing information about each video. How do I store tags? Can anyone show me how to insert and select the information about tags?
Thanks.

A: Assuming your video table has one record per video, something like:
Video
----------
ID
Title
etc.

You would then create a separate table for tags, something like:
Tag
----------
ID
Title

And to associate the two, you're create an association table:
VideoTag
----------
VideoID
TagID

The columns in that table would just be foreign keys to the Video and Tag tables.  This intermediary table allows you to maintain a many-to-many relationship between the Video and Tag entities, since each video can have many tags and each tag can be on many videos.

A: One design I can suggest is to create three tables: VideoList, TagList, Video_Tag. VideoList has many-to-many relationship with tagList. Their association is then listed on Video_Tag table.
CREATE TABLE VideoList
(
    ID INT,
    VideoName VARCHAR(150),
    -- other columns here,
    CONSTRAINT tb_pk PRIMARY KEY(ID),
    CONSTRAINT tb_uq UNIQUE(VideoName)
);

I added UNIQUE constraint on column VideoName so that you will have unique values.
CREATE TABLE TagList
(
    ID INT,
    TagName VARCHAR(150),
    -- other columns here,
    CONSTRAINT tb2_pk PRIMARY KEY(ID),
    CONSTRAINT tb2_uq UNIQUE(TagName)
);

I also added UNIQUE constraint on column TagName.
CREATE TABLE  Video_Tag
(
    RecordID INT,
    VideoID INT,
    TagID INT
    CONSTRAINT tb3_pk PRIMARY KEY(RecordID),
    CONSTRAINT tb3_uq UNIQUE(VideoID, TagID),
    CONSTRAINT tb3_fk1 FOREIGN KEY (VideoID) REFERENCES VideoList(ID),
    CONSTRAINT tb3_fk2 FOREIGN KEY (TagD) REFERENCES TagList(ID)
);

A: The most common approach is having 3 tables:

*

*Videos

*Tags

*VideoTags
Where VideoTags serves as association table, having basic set of columns: VideoID, TagID.


text:
Q: JSON data saving using Django 3.3 As we know, Django=3 is supporting JSONField .
I am trying to save JSON data in my Django Project using JavaScript, i have take data in a input field which looks like:
[{"id":1,"Name":"Antenna","Pieces":"","Weight":"","Weight Types":"","Quantity":"12",
    "Cargo Charge":"12","Customs Charge":"12"},

{"id":2,"Name":"Soap","Pieces":"12","Weight":"12","Weight Types":"","Quantity":"",
    "Cargo Charge":"12","Customs Charge":"12"}]

From the input field I save the data to MySql database using .
product_list = self.request.POST['product_list_json']

Hence, product_list_json is the name of the inout field.
But the saving data is given different view, the saved data look like:
"[{\"id\":1,\"Name\":\"Antenna\",\"Pieces\":\"\",\"Weight\":\"\",\"Weight Types\":\"\",
    \"Quantity\":\"12\",\"Cargo Charge\":\"12\",\"Customs Charge\":\"12\"},
{\"id\":2,\"Name\":\"Soap\",\"Pieces\":\"12\",\"Weight\":\"12\",\"Weight Types\":\"\",
    \"Quantity\":\"\",\"Cargo Charge\":\"12\",\"Customs Charge\":\"12\"}]"

The problem is that, data is saving with additional " \ " . What can i do to solve this?

A: Jsonfield in Django, takes a dict or a list and convert them to JSON (str) and saves them in DB, just load the received JSON from request.POST and send it and it will work fine.

A: Simple CharField can work for you. It can work something like this.
models.py
class subscription_info(models.Model):
     info=models.CharField(max_length=2000,null=True,blank=True)

views.py
from myApp.models import subscription_info as sInfo

def For_AJAX(request):
    if request.method=='POST':
        data=request.body.decode('utf-8')
        mymodel=sInfo()
        mymodel.info=data
        mymodel.save()
        return HttpResponse(status=201)
    else:
       return HttpResponse(status=204)

def For_Form(request):
        if request.method=='POST':
            data=request.POST.get('InputFieldName')
            mymodel=sInfo()
            mymodel.info=data
            mymodel.save()
            return HttpResponse(status=201)
        else:
           return HttpResponse(status=204)

Use json.loads() or json.dumps() as per your requirement after retrieving data from db.


text:
Q: Media query not getting fired I am new to web development and I am facing a hard time dealing with media queries.
I am creating a dance website but my following media queries in "media-query.css" are not getting fired.
@media screen and (max-width:1800px)  and (min-width: 399x) {
  .our-services ul li {
    font-size: 2rem;
    padding: 2rem;

  }
}

@media screen and (max-width: 400px) {
  .our-services ul li{
    font-size: 2rem;
    padding-left: 0rem;
    padding-top: 2rem;
    padding-bottom: 2rem;
  }
}

Project link: https://github.com/abhinav700/DanceMasti.com

A: Too lazy to go through all of those files so I'll list some common errors out here in case someone else finds this question and has a different cause:

*

*Maybe you haven't linked the file. Add <link src="your-directory/media-query.css"></link> to your html file.

*Your queries are being overridden by a file with a higher priority. Test this
by leaving !important after your lines, i.e width: 50px !important;. Note that
using important is considered bad code by some(I have no opinion on this,and
have no idea if it's true).

*As posted by another user, your media query is a bit off, so you could be toeing
the line and using exactly 400px. I doubt it though. The lower query should be
taking precedence, so it still should look like a mobile view.

*Check to make sure that you are using the selectors correctly. Your selectors
currently are looking for a <li> inside a <ul> inside any element with a
class of our-services(someone correct me if I'm wrong). The way I like to
check this is just to set a clause:

li{
  position: none;
}

and see if this element disappears. If it does and nothing else pops up... I got nothing.
If this answer helped, please mark it as answer.

A: It says 399x instead of 401px. So it could be both a syntax issue and a overlap issue.


text:
Q: Select-Object throws an exception when used in a constrained session When I configure a restricted PowerShell Session like so:
New-PSSessionConfigurationFile -Path c:\PSScripts\test.pssc `
                               -Description 'Delegation EndPoint Repro' `
                               -ExecutionPolicy Restricted `
                               -SessionType RestrictedRemoteServer `
                               -LanguageMode FullLanguage

Register-PSSessionConfiguration -Path 'c:\PSScripts\test.pssc' `
                                -Name TestSession `
                                -ShowSecurityDescriptorUI `
                                -AccessMode Remote `
                                -Force

Since the session is of type RestrictiedRemoteServer, I expect the Select-Object Cmdlet be available to end-users. Indeed, when users connect to this session and issue a Get-Command, Select-Object is returned as on of the available Cmdlets.
However when Select-Object is used (for example with -Last parameter), the following exception is thrown.
[localhost]: PS> Get-Command | Select-Object -Last 1
A parameter cannot be found that matches parameter name 'Last'.
    + CategoryInfo          : InvalidArgument: (:) [Select-Object], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Select-Object

What am I missing?


text: Q: how to deploy the angular frontend and and java backend to the azure windows virtual machine ci pipeline is ready and the build is ready both frontend backend and published but I want to deploy it into the particular virtual machine so I can later scall it up


text:
Q: Jinja2 ValueError: too many values to unpack (expected 2) {%for feed,tim in feeds,time %}
                        {% set nickname = feed.nick %}
                        {% set like = feed.like %}
                        {% set text = feed.text %}
                        {% set today = tim %}
                        {% set postid = feed.postid %}
                        {% set photo = feed.photo %}
                        {% set profile = feed.profile %}

                                {%for cmt in cmts %}
                                {% set nickname = cmt.nick %}
                                {% set cmt = cmt.cmt %}
                                {% set cmtid = cmt.cmtid %}
                                {% if cmtid == postid %}

{{nickname}}  {{cmt}}

                                {% endif %}
                                {% endfor %}

                                    <input type="text" class="comment-box" id='cmt' placeholder="Add a comment">
                                    <button class="comment-btn" onclick=cmt_write()>post</button>

                        {% endfor %}

succeeded in executing the for statement with one list in jinja2,
but we have to use two lists.
i try 2 list ( feeds, time ) use in jinja2
how to jinja2 for loop from jinja2
Is there a way to use two lists in jinja2?

A: If you want to loop over a combined list of two lists (of same length) you have to apply zip function on them. E.g.:
def view_function():
   feeds = [...]
   time = [...]

   feeds_and_time = zip(feeds, time)
   # Looks like this: [('feed_1', 'time_1'), ('feed_2', 'time_2')]

Then pass this new feeds_and_time variable to the render function. And in the template, modify the loop:
{% for feed,tim in feeds_and_time %}


text:
Q: Page break in PDF sending by batch class I am sending a PDF through batch class. In PDF there are some tables. I want new page every time a new table starts in pdf.
How can I achieve this??

A: You can have a style for tr inside pdf  see w3schools
<style>

{
tr{page-break-after:always;}
}
</style>


text:
Q: AVQueuePlayer: Loop last item in a queue (and eliminate hiccup) or loop last seconds of a video I am using AVQueuePlayer to play videos in sequence (although I have hiccups between plays).
Now I'd like to:
1) Loop the last item in that sequence (not the full one).
2) In doing so, I'd also like to eliminate hiccups.
Below is my code to play the videos sequence. How could I achieve my 2 goals?
[super viewDidLoad];

NSString *secondVideoPath = [[NSBundle mainBundle] pathForResource:@"vid_1" ofType:@"mov"];
NSString *firstVideoPath = [[NSBundle mainBundle] pathForResource:@"vid_2" ofType:@"mov"];

AVPlayerItem *firstVideoItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:firstVideoPath]];
AVPlayerItem *secondVideoItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:secondVideoPath]];

queuePlayer = [AVQueuePlayer queuePlayerWithItems:[NSArray arrayWithObjects:firstVideoItem, secondVideoItem,nil]];

AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:queuePlayer];
avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
layer.frame = CGRectMake(0, 0, 1024, 768);

[self.view.layer addSublayer:layer];

[queuePlayer play];

Another method I'm thinking of would be the play 1 long video and loop the last few seconds of it. Perhaps I could also avoid hiccups that way. Would this approach be something achievable? If so, how to adapt the code below (that plays 1 video)?
[super viewDidLoad];
NSString *filepath = [[NSBundle mainBundle] pathForResource:@"vid_long" ofType:@"mov"];
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
avPlayer = [AVPlayer playerWithURL:fileURL];

AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
layer.frame = CGRectMake(0, 0, 1024, 768);
[self.view.layer addSublayer: layer];

[avPlayer play];

A: Here is the solution to play the video in loop:-
queuePlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
int k=0;
 [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(itemPlayEnded:)
                                               name:AVPlayerItemDidPlayToEndTimeNotification
                                             object:[queuePlayer currentItem]];

- (void)itemPlayEnded:(NSNotification *)notification
{
 k++;
 if(k<10-15 times)
 {
  AVPlayerItem *p = [notification object];
  [p seekToTime:kCMTimeZero];
 }
}

By Edited answer:-
The above answer play the same files but this works for me.
It play the last added file in loop:
- (void)itemPlayEnded1:(NSNotification *)notification
{
    NSString *secondVideoPath = [[NSBundle mainBundle] pathForResource:@"video2" ofType:@"mp4"];
      k=0;
    AVPlayerItem *secondVideoItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:secondVideoPath]];
    // AVPlayerItem *p = [notification object];
    NSMutableArray *currentItemArray = [NSMutableArray arrayWithObjects:secondVideoItem,nil];
    AVQueuePlayer* queuePlayer = [[AVQueuePlayer alloc] initWithItems:currentItemArray];
    [queuePlayer play];
    queuePlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;

    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:queuePlayer];
    avPlayer.actionAtItemEnd = AVPlayerItemStatusReadyToPlay;
    layer.frame = CGRectMake(0, 0, 1024, 768);
    [self.view.layer addSublayer:layer];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(itemPlayEnded:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:[queuePlayer currentItem]];

}

A: best way I could find was this
observe for each playeritem in AVQueuePlayer.
queuePlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
for(AVPlayerItem *item in items) {
    [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(nextVideo:)
            name:AVPlayerItemDidPlayToEndTimeNotification
            object:item ];
}

on each nextVideo insert the currentItem again to queue it for playback. make sure to seek to zero for each item. after advanceToNextItem the AVQueuePlayer will remove the currentItem from queue. we just reinsert.
-(void) nextVideo:(NSNotification*)notif {
    AVPlayerItem *currItem = notif.userInfo[@"object"];
    [currItem seekToTime:kCMTimeZero];
    [queuePlayer advanceToNextItem];
    [queuePlayer insertItem:currItem afterItem:nil];
}

A: The only way I've found to do this that is actually reliable is by adopting Apple's Using AVQueuePlayer to demonstrate loop playback sample. You need to add your own code to play an initial video and then loop a different one, but the method works better than any other I've tried.


text:
Q: Using CSS classes to inherit bootstrap grid system This is probably a really dumb question, but here's what I need to do.
I have this html code:

     ...stuff

how can I get it to look like this instead:
index.html

      ...stuff

index.css
.myClass {
  col-xs-12
  col-md-6
  col-lg-4
}

I made up the syntax in the second part obviously. Point being, I don't want to clutter my HTML with CSS.

A: I should try it with SCSS. Then you can use
@import "node_modules/bootstrap/scss/bootstrap";

.myClass {
  @extend .col-xs-12;
}


text:
Q: How to extend a Bootstrap input on click? I've made a search bar in my navbar, but I would like that when the input is clicked, it extends himself to his normal size. I think I have to use some JavaScript but I don't know how do that.
Below follows my code:
<form action="" method="" class="navbar-form navbar-right" role="search">

      <input type="text" class="form-control" placeholder="Rechercher">

        <button class="btn btn-default" type="button"></button>

</form>

A: That's how you do it in jquery.
$("input.form-control").click(function () {
    $(this).addClass("changeStyle");
});

// the css
.changeStyle
{
    width:300px; //normal size
}

A: If your question is how to change input width on click event, use jQuery Animate.
You will need to change width property on input click event.

A: CSS
.large-input {
    width: 300px; /* whatever you want */
 }

HTML
<form action="" method="" class="navbar-form navbar-right" role="search">

      <input type="text" class="form-control" id="search-input" placeholder="Rechercher">

        <button class="btn btn-default" type="button"></button>

</form>

JS using jQuery
$("#search-input").focus(function(event) { $(event.target).addClass('large-input'); });
$("#search-input").blur(function(event) { $(event.target).removeClass('large-input'); });


text:
Q: Native DLNA client for "Xbox Series X" When I search the web for +xbox +dlna I get lots of hits, but mostly Xbox One. I wish to stream from latest Ubuntu (Raspberry) to Xbox Series X with DLNA. Is there a native client?
I know that VLC, Kodi and Plex exists. But those are 3rd party solutions.

A: According to Microsoft, their Media Player application will play files from USB devices or a DLNA media server.
Microsoft Store link.


text:
Q: How to append Dropzone return value to Form Data I have an Ajax that submit form data with laravel validation.
$('body').on('click', '#submit', function(){
 var form_data = new FormData($('form')[1]);

 $.ajax({
     url:'/admin/products/',
     type:'POST',
     processData: false,
     contentType: false,
     dataType: 'json',
     data:form_data,
     success:function(data) {

     },
 });

then also Dropzone file upload/remove in separate Ajax url.
<div id="fileInput" class="dropzone">
    <input name="p_file" type="file" multiple />
</div>

Dropzone.autoDiscover = false;
new Dropzone('#fileInput', {
    // paramName: 'p_file',
    url: "/admin/products/upload",
    // autoProcessQueue: false,
    addRemoveLinks: true,

    init: function () {
        var myDropzone = this;
        myDropzone.on('success', function (file, serverResponse) {
            var fileuploded = file.previewElement.querySelector("[data-dz-name]");
            fileuploded.innerHTML = serverResponse;
        });

        myDropzone.on('removedfile', function(file, response) {
            var name = file.previewElement.querySelector('[data-dz-name]').innerHTML;
        });

        sending: function (file, xhr, formData) {
            // formData.append("name", $('#name').val());
        }
})

According to documentation, I have to use this to do normal form submission.
sending: function (file, xhr, formData) {
        // formData.append("name", $('#name').val());
    }

but I would like to append Dropzone value into form_data of first Ajax, instead of append other form_data to Dropzone as in documentation.
How can I do ?

A: assign the dropzone file into one varialbe then add it to FormData object
$('body').on('click', '#submit', function(){
var fileUpload = $('#fileInput').get(0).dropzone;
var files = fileUpload.files;
var form_data= new FormData();

// Looping over all files and add it to FormData object
    for (var i = 0; i < files.length; i++) {
        form_data.append(files[i].name, files[i]);
    }

 $.ajax({
     url:'/admin/products/',
     type:'POST',
     processData: false,
     contentType: false,
     dataType: 'json',
     data:form_data,
     success:function(data) {

     },
 });


text:
Q: Temporal noise in images I would like to have a groundtruth image to compare the temporal denoising of Kinect data. However I cannot find a dataset/database for the same. If not a groundtruth then I would like to have a completely de-noised(temporal domain) images and an algorithm that can be used to add temporal noise to these completely denoised images, such that I can have a groundtruth image to compare efficiency of the denoising algorithm.

A: Have you tried looking on

https://www.kaggle.com/

They have a lot of public datasets for any machine learning and data science related work. They could have what you're looking for.


text:
Q: How to embed WKWebView inside custom UIView properly? In my project I have a view controller where i want to show WKWebView embedded inside another UIView titled viewForEmbeddingWebView that i've created in a storyboard (grey on the picture).

I've implemented this logic in my ViewController:
import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate  {

    var webView: WKWebView!

    @IBOutlet weak var viewForEmbeddingWebView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        webView = WKWebView(frame: viewForEmbeddingWebView.frame, configuration: WKWebViewConfiguration() )
        self.viewForEmbeddingWebView.addSubview(webView)
        self.webView.allowsBackForwardNavigationGestures = true
        let myURL = URL(string: "https://www.apple.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)

    }

}

After build and running in Simulator I see the following:

It shows WKWebView but the bounds look wrong (first: it does not fit the viewForEmbeddingWebView's bounds and second: there is a white gap at the top). I've read that I must use WKWebView on the apple's site https://developer.apple.com/reference/webkit/wkwebview but their example is not my situation, because they only showing how to deal in the situation with loading WKWebView in the whole View of ViewController. But I need it to be embedded into another view because i will also need another ui later around this WKWebView. Before WKWebView there was WebView but since iOS 8 appeared we must use WKWebView. Please help, because i've checked lot of materials but have not find the answer working great with Swift 3 and Xcode 8.
I'm using Xcode 8 and Swift 3 with iOS 10.2.

A: WKWebView Swift 5 or Custom WKWebView(Webview deprecated)
Please follow below the Apple link for WKWebView -
https://developer.apple.com/documentation/webkit/wkwebview
If you want to add WKWebView in a custom view. Please follow the Code.
 import WebKit

 class OpenControllerURL: UIViewController,WKNavigationDelegate , WKUIDelegate {

  @IBOutlet weak var CustomView: UIView!

    override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL(string: "https://developer.apple.com/documentation/webkit/wkwebview"!)
    let request = URLRequest(url: url!)
    let webView = WKWebView(frame: self.CustomView.frame)
    webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] //It assigns Custom View height and width
    webView.navigationDelegate = self

    webView.load(request)
    self.CustomView.addSubview(webView)
}

#Happy Coding!!!

A: You want to initialize WKWebView like this (Swift 3.0):
webView = WKWebView(frame: viewForEmbeddingWebView.bounds, configuration: WKWebViewConfiguration())
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.viewForEmbeddingWebView.addSubview(webView)


text:
Q: Development of proprietary WiFi protocol I would like to do some customizations to IEEE 802.11 MAC layer protocol and implement it on hardware. I searched rigorously but I could not find any chipset with 802.11 PHY (RF + baseband chipset) using which I can implement custom MAC layer protocol. Most of the existing WiFi chipsets are integrated with MAC layer as its better and efficient to have it in hardware.
The one approach I think I have is to interface Radio frontend chipset (like MAX2830) with baseband chipset and then controlling everything using some MCU or FPGA. Is there any other easier approach I can use (e.g. SDR)?
Edit: The purpose I want to implement this is to achieve a custom wireless link with better packet priority and scheduling algorithm. I would also be interested in tweaking CSMA thresholds and implementing additional error correction coding in MAC layer itself.


text:
Q: How do you save a recorded macro in TextMate 2? TextMate 2 has a round red button in the bottom right corner of each window that pulses when clicked and records a macro of your actions while it is on.  As far as I can tell the only way to replay a recorded macro is Edit > Macros > Replay Macro.
How do you save multiple recorded macros for later use?  After searching the web I have concluded that the previous version of TextMate could save recorded macros via Bundles > Macros > Save Last Recording....  However, TextMate 2 does not have a Macros submenu under the Bundles menu.
Does the current alpha version of TextMate 2 (2.0-alpha.9399) not support saving recorded macros, or am I looking in the wrong places?

A: Edit → Macros → Save Macro… ⌃⌘M
(as of very late March 2013)


text:
Q: PagedList.Config loads list in the middle with recycleview My RecyclerView loads in the middle of the list instead of the most top item first. The list should load the topmost item. In this case, it's the "latest" post. Which I have set to the reverse layout to true and that works.
My RecyclerView
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:viewBindingIgnore="true">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/postsList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:padding="5dp"
        tools:listitem="@layout/post_item" />

</FrameLayout>

My Post list fragment
 // Set up FirebaseRecyclerAdapter with the Query
        val postsQuery = database.child(Globals().POSTS_ROOT_PATH)

        // This configuration comes from the Paging Support Library
        // https://developer.android.com/reference/androidx/paging/PagedList.Config
        val config = PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPrefetchDistance(5)
            .setPageSize(10)
            .build()

        // The options for the adapter combine the paging configuration with query information
        // and application-specific options for lifecycle, etc.
        val options = DatabasePagingOptions.Builder<Post>()
            .setLifecycleOwner(this)
            .setQuery(postsQuery, config, Post::class.java)
            .build()

        adapter = object : FirebaseRecyclerPagingAdapter<Post, PostViewHolder>(options) {

            override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): PostViewHolder {
                val inflater = LayoutInflater.from(viewGroup.context)

                return PostViewHolder(inflater.inflate(R.layout.post_item, viewGroup, false))
            }

            override fun onBindViewHolder(viewHolder: PostViewHolder, position: Int, model: Post) {
                val postRef = getRef(position)
                // Set click listener for the whole post view
                val postKey = postRef.key
//                Log.d("PostListFragment", "post key id is: " + postKey)
                viewHolder.itemView.setOnClickListener {
                    // Launch PostDetailActivity
                    val intent = Intent(activity, PostDetailActivity::class.java)
                    intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postKey)
                    startActivity(intent)
                }

            }

            override fun onLoadingStateChanged(state: LoadingState) {
                when (state) {
                    LoadingState.LOADING_INITIAL -> {
                        Log.d(TAG, "Initial data loading")
                    }
                    LoadingState.LOADING_MORE -> {

                    }
                    LoadingState.LOADED -> {

                    }
                    LoadingState.FINISHED -> {
                        Log.d(TAG, "All data loaded.")
                    }
                    LoadingState.ERROR -> {
                        Log.d(TAG, "Error occured while loading data")
                    }
                }
            }

            override fun onError(databaseError: DatabaseError) {
                super.onError(databaseError)
                databaseError.toException().printStackTrace()
            }
        }

        // Set up Layout Manager, reverse layout
        manager = LinearLayoutManager(activity)
        manager.reverseLayout = true
        manager.stackFromEnd = true
        recyclerList.layoutManager = manager

        recyclerList.adapter = adapter
    }

When I set the setPageSize() to a very large number then it loads the most top item. What do I need to do so this always loads the most top list item first?
Thanks
Edit:
post_item.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    tools:viewBindingIgnore="true">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <include
            android:id="@+id/postTextLayout"
            layout="@layout/post_text_include"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginLeft="2dp"
            android:layout_marginTop="2dp"
            android:layout_marginStart="2dp" />

        <include
            android:id="@+id/postThumbnailImg"
            layout="@layout/post_video_thumbnail_include"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/postTextLayout"
            android:layout_alignParentStart="true" />

        <include
            android:id="@+id/postAuthorLayout"
            layout="@layout/post_author_thumbnail_include"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/postThumbnailImg"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
    </RelativeLayout>

</com.google.android.material.card.MaterialCardView>

Sub layouts
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/postTitle"
        style="@style/TextAppearance.AppCompat.Medium"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:textStyle="bold"
        android:textColor="@color/colorPrimaryDark"
        tools:text="My First Post"
        android:paddingStart="5dp"
        android:paddingEnd="5dp" />
</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:viewBindingIgnore="true">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ImageView
        android:id="@+id/videoThumbnailImg"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/main_background" />
    />

    <RelativeLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent">

        <ImageView
            android:id="@+id/playButton"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:scaleType="centerCrop"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:src="@drawable/ic_baseline_play_arrow_24" />
    </RelativeLayout>
</FrameLayout>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <androidx.cardview.widget.CardView
        android:layout_width="40dp"
        android:layout_height="40dp"
        app:cardCornerRadius="20dp">

        <ImageView
            android:id="@+id/postAuthorPhoto"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@drawable/ic_person_outline_40" />

    </androidx.cardview.widget.CardView>

    <TextView
        android:id="@+id/postAuthor"
        style="@style/Base.TextAppearance.AppCompat.Small"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:gravity="center_vertical"
        android:textColor="@color/colorPrimaryDark"
        tools:text="someauthor@email.com" />

</LinearLayout>

A: You need to set height wrap_content rather than match_parent for sublayouts.


text:
Q: For each unique record ID, return the most recent record of type Y iff there is a more recent record of type X For each unique record ID, return the most recent record of type Y iff there is a more recent record of type X
To make explaining easier I will put the records sorted by EventDate descending and look only at specific record ID's. (Most recent at the top.)
Case 1

ID
EventDate
Type

1
Some Dates
Otherstuff (multiple records)

1
July 29
X

1
Feb 23
Y

1
Jan 3
Y

1
Some Dates
Otherstuff (multiple records)

Return record from Feb 23 of Type Y (Feb 23 is a closer date to the Jan 1 date of record with type X)
Case 2

ID
EventDate
Type

2
Some Dates
Otherstuff (multiple records)

2
Nov 2
X

2
Oct 31
Y

2
Some Dates
Otherstuff

2
July 2
X

2
Feb 23
Y

2
Jan 5
Y

2
Some Dates
Otherstuff

Return records from Feb 23 of type Y and Oct 31 of Type Y. These are the records that are the closest to the type X records in terms of date respectively. (Feb 23 Type y is closest to July 2 of type X and Oct 31 type Y is closest to Nov 2 type X)
Case 3

ID
EventDate
Type

3
Some Dates
Otherstuff (multiple records)

3
July 2
X

3
Feb 23
Y

3
Some Dates
Otherstuff

3
Jan 5
X

3
Some Dates
Otherstuff

Return Feb 23 of type Y record
Case 4

ID
EventDate
Type

4
Some Dates
Otherstuff (multiple records)

4
Oct 15
Y

4
July 2
X

5
Feb 23
X

5
Some Dates
Otherstuff

5
Jan 5
Y

5
Jan 1
Y

5
Some Dates
Otherstuff

Return ONLY the Jan 5th of type Y record. It is the closest to record of type X in terms of dates that has happened before the type X
SELECT
    *
FROM
    (
        SELECT
            *,
            ROW_NUMBER() OVER ( PARTITION BY A.ID ORDER BY EventDate DESC ) AS pc

        FROM
            SOMETABLE AS "A"
            INNER JOIN
            (
                SELECT
                    ID AS 'BID',
                    MIN(EventDate) AS 'OldestDate'
                FROM
                    SOMETABLE
                WHERE
                    TYPE = 'X'
                GROUP BY
                    ID
            ) AS "B" ON A.ID = B.BID

    WHERE
        EventDate < OldestDate
        AND
        Type = 'Y'

    ) AS "FINAL"

This fails in cases where there are multiple records of type Y that need to be pulled, as it 'filters out' any records newer than the OLDEST instance of type X.

A: This query takes the most recent Y value for a given X value if it exists.
SELECT
    *
    ,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY XDateTime ASC) AS 'Degree'
FROM
    (SELECT
        *
        ,ROW_NUMBER() OVER (PARTITION BY YDateTime ORDER BY XDateTime ASC) AS 'dc'
    FROM
        (SELECT
            ID
            ,EventDateTime AS 'YDateTime'
            ,B.XDateTime
            ,DATEDIFF(SECOND, EventDateTime, B.XDateTime) AS 'Time'
            ,ROW_NUMBER() OVER (PARTITION BY B.XDateTime ORDER BY EventDateTime DESC) AS 'pc'

        FROM vw_A6Productivity AS "A"

        INNER JOIN
            (SELECT
                ID AS 'BID'
                ,EventDateTime AS 'XDateTime'

            FROM TABLE

            WHERE TYPE = 'X'

            GROUP BY
                ID
                ,EventDateTime
            ) AS "B"

        ON A.ID= B.BID

        WHERE
            EventDateTime < XDateTime -- Inner join filters for Nulls automatically
            AND STATUS = 'Y'

        ) AS "C"

    WHERE
        pc = 1

    ) AS "D"

WHERE dc = 1;

A: So the question is looking for the same ID with two different types of events happened closely. Not sure if you're looking for X before Y, Y before X or either.
We can divide the data into two groups:

*

*X events: (ID, 'X', EventDate)

*Y events: (ID, 'Y', EventDate)
Join both on ID and the compare EventDate, then pick the one based on your criteria.

Step 1. Prep data
create table event (
    id          int,
    event_date  date,
    type        char(1));

insert into event
values
(1, '2022-01-01', 'X'),
(1, '2022-01-03', 'X'),
(1, '2022-01-05', 'Y'),
(1, '2022-01-07', 'Y'),
(1, '2022-01-09', 'X'),
(1, '2022-01-11', 'X'),
(1, '2022-01-15', 'Y');

Step 2. Join and compare both events
with
event_x as (select id, type, event_date from event where type='X'),
event_y as (select id, type, event_date from event where type='Y'),
event_xy as (
select x.id,
       x.event_date as x_event_date,
       y.event_date as y_event_date,
       datediff(x.event_date,y.event_date)      as days_from_x_to_y
  from event_x x
  join event_y y
 using (id))
select id,
       x_event_date,
       y_event_date,
       days_from_x_to_y,
       abs(days_from_x_to_y) as days_between_x_and_y
  from event_xy
 where 1 = 1
   -- and days_from_x_to_y <=0   -- x happened after y
   -- and days_from_x_to_y >=0   -- x happened before y
 order by days_between_x_and_y asc;

We get:
id|x_event_date|y_event_date|days_from_x_to_y|days_between_x_and_y|
--+------------+------------+----------------+--------------------+
 1|  2022-01-03|  2022-01-05|              -2|                   2|
 1|  2022-01-09|  2022-01-07|               2|                   2|
 1|  2022-01-09|  2022-01-05|               4|                   4|
 1|  2022-01-01|  2022-01-05|              -4|                   4|
 1|  2022-01-11|  2022-01-07|               4|                   4|
 1|  2022-01-03|  2022-01-07|              -4|                   4|
 1|  2022-01-11|  2022-01-15|              -4|                   4|
 1|  2022-01-11|  2022-01-05|               6|                   6|
 1|  2022-01-01|  2022-01-07|              -6|                   6|
 1|  2022-01-09|  2022-01-15|              -6|                   6|
 1|  2022-01-03|  2022-01-15|             -12|                  12|
 1|  2022-01-01|  2022-01-15|             -14|                  14|

With slight changes in where clause, we can pick the (x, y) event we need.


text:
Q: How to route an IP connection from a network card adapter to a PORT in another card adapter in windows I've got an industrial PC running Windows Embedded with two network card adapters. One of the cards, let's say card1, is connected to a switch in which there are a few IP cameras connected and some others IP peripherals conforming a private net. The other card adapter, card2, is connected to the company network.
What I need to do is routing one of the IP cameras to a port in card2's IP so that it can be seen and accessed from the company network.
Is it possible in windows?
regards
Here is a schema of what I have to do
Somehow I need to access to CAM1 from the COMPANY NET

A: I've solved my problem thanks to marctxk's suggestion.
https://stackoverflow.com/questions/24646165/netsh-port-forwarding-from-local-port-to-local-port-not-working
In windows command line you just have to execute this command
netsh interface portproxy add v4tov4 listenport=xx listenaddress=xxx.xxx.x.xxx connectport=xx connectaddress=xxx.xxx.x.xxx
the listen port and address are the IP seen by company net and the port I want to use. The connect port and address are the IP and port of the IP camera.
You don`t have to forget to add rules to your windows firewall so that you can access the port you want to use


text:
Q: Vignette in cocos2d I want to create a vignette effect in cocos2d. I'm not really sure how I could go about doing this. I thought about just using an image, but a high resolution, fullscreen image (this is for iPad) would take up a lot of memory. Next, I thought about using CCRenderTexture. I've never used it before, but I'm currently looking into it. What advice do you have toward accomplishing this?
I want something similar to this (notice the black near the corners and edges of the image)

Thanks.

A: You could find or write a pixel shader to do it, but I've no experience to advise you there.  Googling vignetting pixel shader yields a few samples that may give you a starting point.
Alternately, the image required to do a vignette effect for 2048 x 1536 would not take up so much memory that I would dismiss it out of hand.  Give it a shot.


text:
Q: MetaMask - RPC Error: execution reverted. Error: cannot estimate gas I have a
MetaMask - RPC Error: execution reverted {code: -32000, message: 'execution reverted'}
next-dev.js?3515:25
Error: cannot estimate gas; transaction may fail or may require manual gas limit [ See: https://links.ethers.org/v5-errors-UNPREDICTABLE_GAS_LIMIT ] (reason="execution reverted", method="estimateGas", transaction={"from":"0x563925491A8B3100c329d05292c059A84165dFB7","to":"0x159bB9B4A6b7f1165141Bc927a32237a143609C9","value":{"type":"BigNumber","hex":"0x016345785d8a0000"},"data":"0xd6febde800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001","accessList":null}, error={"code":-32000,"message":"execution reverted"}, code=UNPREDICTABLE_GAS_LIMIT, version=providers/5.6.8)
        at Logger.makeError (index.js?dd68:219:1)
        at Logger.throwError (index.js?dd68:228:1)
        at checkError (json-rpc-provider.js?8679:76:1)
        at Web3Provider.eval (json-rpc-provider.js?8679:533:1)
        at Generator.throw (<anonymous>)
        at rejected (json-rpc-provider.js?8679:6:42)

I did everything by Clever Programmer's tutorial: https://www.youtube.com/watch?v=x3eRXeMB-4k&list=WL&ab_channel=CleverProgrammer. And now I have this error after running this piece of code:
const buyItem = async (
    listingId = selectedMarketNft.id,
    quantityDesired = 1,
    module = marketPlaceModule
  ) => {
    console.log(listingId, quantityDesired, module, 'david')
    // yo RAZA lets goooo!!!
    //yo Qazi, ok
    // sure okay about to run it...
    // just clicked buy now...
    // still error
    // where can i see the contract address of the marketplace module
    // in [nftId.js]
    await module
      .buyoutDirectListing({listingId, quantityDesired})
      .catch((error) => console.error(error))

    confirmPurchase()
  }


text:
Q: How to provide permission for login in my android application if user has fb account Hello friends i need to get user information from facebook i am using code
String about_me=facebook.request("me");
but this is showing error :---
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
can any body tell me how to resolve this ????

A: that error means that your Facebook object does not have a valid access token. try something like this to see what your access token and its associated expiration time is.
Log.d("myapp", "access token = " + facebook.getAccessToken());
Log.d("myapp", "expiration = " + facebook.getAccessExpires());
Log.d("myapp", "expiration datetime = " + (new Date(facebook.getAccessExpires())).toString());
Log.d("myapp", "is session valid? " + facebook.isSessionValid());

it is your job to check whether you (the user) has an access token and if it is still valid. if not then you must open up the dialog to proceed with authentication.
facebook.authorize(Activity activity, String[] permissions, DialogListener);

the newer android facebook API is supposed to work with single sign on (SSO). meaning, if  a user already has "THE" official facebook app installed and is logged into that official app on the device, then the user does not have to re-authenticate.
otherwise, an (ugly) dialog shows up where the user has to enter in their credentials (which is just a web browser embedded in the dialog).


text:
Q: svn command fail from Maven I have imported a project with Maven that has a module using STP-SCA Tools. The POM of this module tries to download the STP-SCA Tools by SVN.
When I do a mvn install of this POM.xml I get the following on cmd
[INFO]
[INFO] --- maven-scm-plugin:1.6:checkout (checkout) @ sca-model ---
[INFO] Removing C:\WorkSpace\FrascatiTrunk\org.eclipse.stp.sca.model\org.eclipse
.stp.sca\target\checkout
[INFO] Executing: cmd.exe /X /C "svn --non-interactive checkout svn://dev.eclips
e.org/svnroot/soa/org.eclipse.stp.sca-tools/org.eclipse.stp.sca/tags/3.5SR1/org.
eclipse.stp.sca C:\WorkSpace\FrascatiTrunk\org.eclipse.stp.sca.model\org.eclipse
.stp.sca\target\checkout"
[INFO] Working directory: C:\WorkSpace\FrascatiTrunk\org.eclipse.stp.sca.model\o
rg.eclipse.stp.sca\target
[ERROR] Provider message:
[ERROR] The svn command failed.
[ERROR] Command output:
[ERROR] "svn" no se reconoce como un comando interno o externo,
programa o archivo por lotes ejecutable.

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.778s
[INFO] Finished at: Mon Oct 01 16:30:13 CEST 2012
[INFO] Final Memory: 7M/108M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-scm-plugin:1.6:che
ckout (checkout) on project sca-model: Command failed.The svn command failed.

If I try that svn dir on Eclipse it works.
Why does the svn command fail from Maven?

A: The command that is failing for you is
svn --non-interactive checkout svn://dev.eclipse.org/svnroot/soa/org.eclipse.stp.scatools/org.eclipse.stp.sca/tags/3.5SR1/org.eclipse.stp.sca C:\WorkSpace\FrascatiTrunk\org.eclipse.stp.sca.model\org.eclipse.stp.sca\target\checkout
and it fails with "svn" no se reconoce como un comando interno o externo, programa o archivo por lotes ejecutable.
Now I don't speak that language myself, but I'll bet it is saying that command "svn" was not recognized.
Basically, what you need to do is you need to install & configure an SVN client so that you can run svn from the command line.