text:
Q: What might be the definition of a positively oriented chart in From Calculus to Cohomology? My book is From Calculus to Cohomology by Ib Madsen and Jørgen Tornehave.
I recently finished most of An Introduction to Manifolds by Loring W. Tu, so based on the preface of From Calculus to Cohomology, I started at Chapter 8. I don't believe I've missed anything since charts are first introduced in Chapter 8.
Question: What's a positively oriented chart, first mentioned in Proposition 10.2, please?

Some context:
I think this is relevant in answering my other question:
Why is there a form with compact support on a connected oriented manifold with integral one but with support contained in a given open proper subset?

*

*I think I have to prove either the chart $(U, g: U \to g(U) = U')$ or some restriction $(W, g|_W:W \to g(W))$, $W$ open in $U$, is a "positively oriented chart" or at least an "oriented chart" in order to apply Proposition 10.2

My guesses:

*

*The definition of "oriented chart" in the book (see also previous definitions of orientation) is meant to be "positively oriented chart" with "negatively oriented chart" to be for orientation-reversing. I mean that

*

*1.1. a chart $(U,h:U \to U')$ is an oriented chart if and only if it is a member of an oriented atlas of an oriented smooth $n$-dimensional manifold, and we sometimes omit $U$ and $U'$ and call $h$, the coordinate map, an oriented chart (instead of something like "oriented map")

*1.2 An oriented chart $(U,h:U \to U')$, or just $h$, is positively oriented

*

*if and only if $h:U \to U'$ is an orientation-preserving diffeomorphism

*if and only if $\det(D_q(h)) > 0$

*if and only if $D_qh: T_qU = T_qM \to T_{h(q)}U' = T_{h(q)} \mathbb R^n$ is an orientation-preserving diffeomorphism of manifolds  (See here and here)

*if and only if $D_qh: T_qU = T_qM \to T_{h(q)}U' = T_{h(q)} \mathbb R^n$ is an orientation-preserving vector space isomorphism of tangent spaces

*In Proposition 10.2, what is meant by "positively oriented chart" is simply "oriented chart" if we go with the convention that "oriented charts" are "positively oriented charts", as originally in the book.

I also tried looking up other books:

*

*An Introduction to Manifolds by Loring W. Tu:
Based on Section 21.5 and Subsection 23.4, I believe the definition for integration is for a chart in an "oriented atlas" of $M$, where an "oriented atlas" is defined one where overlapping charts have positive Jacobian determinant. Thus, "oriented atlas" in An Introduction to Manifolds seems to be the same as "positive atlas" in From Calculus to Cohomology.

*Manifolds, Tensor Analysis, and Applications by Ralph Abraham, Jerrold E. Marsden, Tudor Ratiu:
It seems a coordinate chart is defined as positively oriented if the coordinate chart's coordinate map has all its differentials to be orientation preserving (as in vector spaces or as in manifolds, if we still have such equivalence of the 2 notions of orientation preserving).

*

*If this is what is meant, then to clarify, do we, once again, have a notion, namely the notion of positively oriented chart, that is actually rooted in some prerequisite algebra notion?

*I'm not sure this is (exactly) what Madsen and Tornehave mean because there is a difference in definition for manifolds.

*Update: Based on the proof of Theorem 11.9, which relies on Lemma 11.8, I think this might be the definition or at least equivalent to, implied by or implies the definition.

*Introduction to Smooth Manifolds by John M. Lee:
It seems the definition is that for an oriented smooth $n$-manifold $M$ with or without boundary, for a coordinate chart $(U,\varphi) = (U,x^1,...,x^n)$ in the differentiable structure of $M$ (see Tu Subsection 5.3), where $x^i=r^i \circ \varphi$, where $r^1, ..., r^n$ are the standard coordinates on $\mathbb R^n$, $(U,\varphi)$ is said to be positively oriented if the frame $\{\frac{\partial}{\partial x^1}, ..., \frac{\partial}{\partial x^n}\}$ is positively oriented. I think there's no explicit concept of "manifold with boundary" or "frame" in From Calculus to Cohomology by Ib Madsen and Jørgen Tornehave so far, and so if we were to adopt this definition,

"if the frame $\{\frac{\partial}{\partial x^1}, ..., \frac{\partial}{\partial x^n}\}$ is positively oriented"

would be translated to

"if each element of the set $\{\frac{\partial}{\partial x^1}|_p, ..., \frac{\partial}{\partial x^n}|_p\}_{p \in M}$ is positively oriented".

Since each element is a basis of the tangent space $T_pM$, based on Tu Subsection 21.3 (Tu says it was in Subsection 12.5, but I'm not sure that was explicit unless Subsection 12.5 was understood in the context of Proposition 8.9), and this is indeed defined after Definition 9.8

A: A very long question!
As you know, the concept of orientation arises in linear algebra by taking equivalence classes of ordered bases of a real vector space $V$, two such bases $\{b_i \}$ and $\{b'_i \}$ being equivalent if the linear automorphism sending $b_i$ to $b'_i$ has positive determinant. There are exactly two orientations of a vector space $V$ with dimension $> 0$. For a general $V$ none of these two orientations is privileged and it would be an arbitrary choice to call one of them positive and the other negative. However, if $\omega$ is an orientations of $V$, it makes sense to write $-\omega$ for the other orientation, i.e. the minus-sign indicates that the orientation is reversed. Note that a linear isomorphism $f : V \to W$ between vectors spaces $V,W$ establishes  a bijection between ordered bases of $V,W$, and thus between orientations of $V,W$. We can therefore say that linear isomorphisms transfer orientations between vectors spaces.
In contrast to the general case, $\mathbb{R}^n$ as the standard model of an $n$-dimensional real vector space has a canonical ordered basis $\{ e_1,\dots,e_n \}$, and its equivalence class is customarily denoted as the positive orientation of $\mathbb{R}^n$. This special situation is due to the fact that the set $\{ 1,\dots,n \}$ has a  natural order.
There are various equivalent approaches to define the concept of an orientation on a differentiable manifold $M$. In my opinion the best approach is to define an orientation of $M$ to be a family $\Omega = (\omega_p)_{p \in M}$ of compatible orientations of the tangent spaces $T_pM$. But what is meaning of compatible? The problem is that $T_{p_i}M$ are distinct for $p_1 \ne p_2$, thus we cannot say that the orientations $\omega_{p_i}$ of $T_{p_i}M$ agree.
Let us first consider the simple case of an open subset $V \subset \mathbb{R}^n$. The tangent spaces $T_xV$, $x \in V$, are all distinct, but there is a canonical linear isomorphism $h_x : T_xV \to \mathbb{R}^n$. This allows to define an orientation of $V$ to be a family of orientations $(\omega_x)_{x \in V}$ of orientations of $T_xV$ such each each $x_0 \in V$ has an open neigborhood  $V_{x_0} \subset V$ such that for each $x \in V_{x_0}$, $h_x$ transfers $\omega_x$ to the same orientation of $\mathbb{R}^n$. It is easy to see that a connected $V$ has exactly two orientations. We can moreover say that an orientation of $V$ is positive if each $h_x$ transfers $\omega_x$ to the positive orientation of $\mathbb{R}^n$. Finally, if $R : \mathbb{R}^n \to \mathbb{R}^n$ is a reflection at a hyperplane, e.g. $R(x_1,\dots,x_n) = (-x_1,x_2\dots, x_n)$, then we see that the diffeomorphism $R_V =  R : V \to R(V)$ has the property $h_{R(x)} \circ T_xR_V = -h_x$, i.e. $R_V$ is orientation reversing.
An orientation of a differentiable manifold $M$ is now defined as a family of orientations $\Omega = (\omega_p)_{p \in M}$ of $T_pM$ such that for each chart $\phi : U \to V \subset \mathbb{R}^n$ the family $\phi_*(\Omega) = (T_{\phi^{-1}(x)}\phi(\omega_{\phi^{-1}(x)})_{x \in V})$ is an orientation of $V$. The chart $\phi$ is said to be positively (negatively) oriented with respect to $\Omega$ if $\phi_*(\Omega)$ is the positive (negative) orientation of $V$. Obviously each chart on a connected $U$ is either positively or negatively oriented. If $U$ is not connected, we can only say that the restriction $\phi_\alpha$ of $\phi$ to each component $U_\alpha$ of $U$ is either positively or negatively oriented. Moreover, for each chart $\phi : U \to V$ there exists a chart $\phi' : U \to V'$ such that $h_{\phi'(p)}(\phi'_*(\omega_p)) = - h_{\phi(p)}(\phi_*(\omega_p))$ for all $p \in U$ (simply take a reflection $R : \mathbb{R}^n \to \mathbb{R}^n$ and define $\phi' = R_V \circ \phi : U \to V' = R(V)$). Working componentwise, we see that on each chart domain (which is an open subset $U \subset M$ which occurs as the domain of a chart) there exist both positively and negatively oriented charts.
The collection of all positively oriented charts forms an atlas for $M$. All transition functions between charts in this atlas have the property that the sign of the determinant of the Jacobian matrix is $+1$ at each point. Note that the collection of all negatively oriented charts has the same property.
Any atlas having the above property it called an orientable atlas, and this is an alternative way to introduce the concept of orientation on manifolds.
Note, however, that there are no open subsets $U \subset M$ which are positively oriented in an absolute sense: Positive orientation is a property of charts with respect to an orientation $\Omega$.


text:
Q: What does 'ground this thing out' means? What does this senior defense official means by saying this: "He is signaling that he's trying to ground this thing out," a senior defense official said in an interview.
Source: https://www.nytimes.com/2022/09/20/us/politics/biden-gas-russia-europe.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: como validar campo data para se nao for passado nada vir a data atual Possuo um endpoint da seguinte forma:
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<TestsDto>), (int)HttpStatusCode.OK)]
public async Task<ActionResult<IEnumerable<TestsDto>>> GetAsync(Guid textId, Guid phraseId, Guid heightId, Guid? weightId, Guid? productId, decimal? value, DateTime? date)
{

    var test= await _testingHandler.GetAsync(textId, phraseId, currencyId, heightId, weightId, value, date );
    return Ok(apps);
}

Como eu faço para validar, se o ultimo campo que é date nao for passado valor algum pra ele eu atribuir sempre a data atual nesse campo ?

A: Você quer fazer essa verificação apenas na API certo?
Não tem magica, você vai precisar criar um método ou apenas um condicional para verificar para você.
if (date == null)
date = DateTime.Now;
Ou você poderia criar uma classe de validação utilizando bibliotecas como a FluentValidation /AbstractValidator para realizar essa ação para você.
https://codigosimples.net/2018/11/14/usando-o-fluentvalidation-no-net-core/
https://docs.fluentvalidation.net/en/latest/custom-validators.html

A: Olá, veja se isso funciona para você:
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<TestsDto>), (int)HttpStatusCode.OK)]
public async Task<ActionResult<IEnumerable<TestsDto>>> GetAsync(Guid textId, Guid phraseId, Guid heightId, Guid? weightId, Guid? productId, decimal? value, DateTime? date)
{
    if (date == null)
         date = DateTime.Now;
    var test= await _testingHandler.GetAsync(textId, phraseId, currencyId, heightId, weightId, value, date );
    return Ok(apps);
}


text:
Q: BeanItemContainer cannot be resolved to a type Vaadin I am new to Vaadin and webapp developement, and just wanted to try this because it suits on of my use-case perfectly. Thing is, upon building and running the project, I get the following error message when connecting to the localhost through my browser: "cannot infer type arguments for BeanItemContainer<>" (VaadinUI Class in the updateGrid() Method.
Can anyone help me? The tutorial is supposed to run and it isn't that old either...

A: BeanItemContainer<> required "Company" as type


text:
Q: Show div when click on its ::before element with only CSS? I wish to hide div contents and show only its ::before pseudo-element. Click on ::before element should show the
 contents.
As I read I cannot use div::before:hover, selector.
I can do this by adding another element to the page like tag A. But no, I need a solution where I cannot add any other element, only pseudo-elements and only CSS (no-js, no-HTML).
I tried here: jsfiddle Show on click on ::before

/* show hide quoted email text */
div.gmail_quote {
    background: pink;
}

div.gmail_quote:before {
    font-size: 1em !important;
    visibility: visible;
    display: block;
    content: 'show';
    display: block;
    padding: 5px;
    background: #E9A;
}

div.gmail_quote>* {
    font-size: 2px;
}

div.gmail_quote:hover>* {
    font-size: 1em;
    background: magenta;
}

div.gmail_quote::before:active+div.gmail_quote {
    background: white;
}

.shower:focus+div.gmail_quote {
    background: yellow;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

    permanent block shower on click

Hello

            Would you be so kind to show an example?

            Is it still possible to get a solution?
            How to show this block not on hover on it but on click on its ::before?

            Block content.

    I need to show block on click on its ::before element

There click on A element changes the div background and works fine. But in my task I cannot add any HTML code, I should use only CSS for that div.gmail_quote.
Could you, please, advise?


text:
Q: Socket undefined, send don't send if undefined Hello I wrote the following function to get someone his socket;
var getSocket = function(persId){
    var socketid = users[persId].socket;
    if(io.sockets.connected[socketid]){
        return io.sockets.connected[socketid];
    }
}

They are being emitted like so;
getSocket(372).emit({ ... });

Now if an user has disconnected before the socket is sent out it will result in a undefined socket error, which may cause issues.
is there any way by modifying the function (without having to check for if getSocket(372)) to make it not throw out an error? it's causing problems right now.
Thanks!

A: What you should do instead, is use socket.io function, that will check for that already.
io.to(room).emit()
On connection just join the user to a room named 372 (I believe that's the user id), and then emit to it:
io.on('connection', socket => {

    const room = 372; // Get user id somehow
    socket.join(room);

});

// Somewhere
io.to(372).emit(..)

Answering your specific question, you can return an object with an emit nop method. Also you have to check if the user exist before accessing to .socket. You can do that using destructuring.
const { socket: socketId } = users[persId] || {};

The full function should be:
const getSocket = function(persId){
    const { socket: socketId } = users[persId] || {};
    if(socketId && io.sockets.connected[socketId]){
        return io.sockets.connected[socketId];
    }

    return { emit: () => {} }
}

And now you don't have to perform a check, since .emit will always exist.
getSocket(23123213).emit(); // Will no throw if 23123213 doesn't exist


text:
Q: Video saving and display in the iOS app. I'm developing an app where user can record video and save it in the library/or custom album. I'm able to create the custom album and record the video and save it in the default photo library i.e., camera roll.. But i'm unable to save it to the custom album. and other thing is the saved videos in the album must be showed in the collection view of the app i.e., like the gallery view.. so that user can able to click on the videos for the play.. it might be in the grid view/ collection view or might be in the table view where the UIImage should should display the videos saved in the album..
Here's code section which i used in the app development for creating the custom album.
ALAssetsLibrary* libraryFolder = [[ALAssetsLibrary alloc] init];
[libraryFolder addAssetsGroupAlbumWithName:@"HEP" resultBlock:^(ALAssetsGroup *group)
 {
     NSLog(@"Adding Folder:'My Album', success: %s", group.editable ? "Success" : "Already created: Not Success");
 } failureBlock:^(NSError *error)
 {
     NSLog(@"Error: Adding on Folder");
 }];

For recording the video in the app.
- (IBAction)StartRecord:(id)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
    [self presentViewController:picker animated:YES completion:NULL];

}

For saving it in the album i.e., default photo album not the custom album i created.
-(BOOL)startMediaBrowserFromViewController:(UIViewController*)controller usingDelegate:(id )delegate {
    // 1 - Validations
    if (([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum] == NO)
        || (delegate == nil)
        || (controller == nil)) {
        return NO;
    }
    // 2 - Get image picker
    UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
    mediaUI.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    mediaUI.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
    // Hides the controls for moving & scaling pictures, or for
    // trimming movies. To instead show the controls, use YES.
    mediaUI.allowsEditing = YES;
    mediaUI.delegate = delegate;
    // 3 - Display image picker
    [controller presentModalViewController:mediaUI animated:YES];
    return YES;
}

Since i'm beginner in iOS still learning.. I'm searching since for a month now. So please help me.

A: First create your album folder with below code & make sure this code paste in AppDelegate.m file didFinishLaunchingWithOptions method :
ALAssetsLibrary* libraryFolderSozialConnectVideo = [[ALAssetsLibrary alloc] init];
[libraryFolderSozialConnectVideo addAssetsGroupAlbumWithName:@"HEP" resultBlock:^(ALAssetsGroup *group)
 {
     NSLog(@"HEP Folder Created");
 } failureBlock:^(NSError *error) {
     NSLog(@"Error: Adding on Folder");
 }];

Now, use below function for download your video in HEP folder :
- (void)downloadVideo:(NSURL *)videoURL {
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSLog(@"Downloading Started");
    NSData *urlData = [NSData dataWithContentsOfURL:videoURL];
    if (urlData) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"thefile.mp4"];
        [urlData writeToFile:filePath atomically:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [self.library saveVideo:[NSURL fileURLWithPath:filePath] toAlbum:@"HEP" completion:^(NSURL *assetURL, NSError *error)
             {
                 NSLog(@"Success downloaded");
             } failure:^(NSError *error) {
                 NSLog(@"Error : %@", [error localizedDescription]);
                 [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                 [self.navigationController popViewControllerAnimated:YES];
             }];
        });
    }
}); }

for videoURL in your didFinishPickingMediaWithInfo method call above function with below code :
self.library = [[ALAssetsLibrary alloc] init];
[self downloadVideo:[info valueForKey:UIImagePickerControllerMediaURL]];

I hope this works . . .


text:
Q: cannot add multiple textbox values in html and jq sir i have 10 text boxes .1st two take values from user and display the multiplication result on 3rd text box when it clicked.4th and 5th textboxes also take values and display the multiplication result in 6th text box when it clicked. like same as above 7th and 8th textbox will work accordingly and 9th textbox will display the multiplication result when it clicked.10th textbox takes the values from 3rd  6th and 9th textbox and add them. my problem is that i can do the multiplication bt cannot display the total sum in 10th  textbox  in html and jscript.plz help me.....i am attached the code...
my code

Text1 : <input type="text"value="0" id="text1" value="">

Text2 : <input type="text" value="0"id="text2" value="">

Text3 : <input type="text"value="0"id="text3" value="0" onclick="getext3()">

Text4 : <input type="text"value="0"id="text4" value="">

Text5 : <input type="text" value="0"id="text5" value="">

Text6 : <input type="text" id="text6" value="0" onclick="getext6()">

Text7 : <input type="text"value="0"id="text7" value="">

Text8 : <input type="text" value="0"id="text8" value="">

Text9 : <input type="text" id="text9" value="0" onclick="getext9()">

Text10 : <input type="text" id="text10" value="" onclick="getext10()">

A: Update
document.getElementById("text7").value = txt4;
To
document.getElementById("text10").value = txt4;
in function getext10()
Here is a Demo


text:
Q: How to retrieve data from sql/Mysql Query? I want to retrieve data from sql query but I am not able to retrieve the data correctly.
I have two tables:
Table UserPost:
id       userID     postText         status
1        abc        hello world!     0
2        xyz        hello Test!      0
3        abc        hello Que!       0
4        qwe        hello All!       0
5        abc        hello Post!      0
6        rty        hello RTY!       0
7        jkl        hello JKL!       0
8        jkl        hello JKL2!      0
9        jkl        hello JKL3!      0
10       jkl        hello JKL4!      0

Table UserFollow:
id       followerID     followedID         status
1        abc            xyz                 1
2        xyz            qwe                 1
3        abc            rty                 1
4        qwe            abc                 1
5        abc            jkl                 1

I want to write a query to select posts from user and followed users
(Both USER And User's followers Post LIKE 'abc' and all posts whom 'abc' followed)
WHERE UserPost.Status = 0 AND UserFollow.status = 1
I have tried this but failed:
SELECT * FROM UserPost INNER JOIN UserFollow
  ON UserPost.userID = UserFollow.followedID
    WHERE UserFollow.followerID = 'abc'
      AND UserFollow.status=1
        AND UserPost.status=0

// This is not working

I tried with another query:
select p.*, u.* from ( select * from UserPost
 where userID = 'abc'  or userID in (select followedID
 from UserFollow where followedID = 'abc') ) p inner join UserFollow u
 on u.followedID = p.userID order by p.id
// This query is also not working

What am I doing wrong?

A: If I am understanding correctly, you can use exists:
select p.*
from userpost p
where
    p.status = 0
    and (
        p.userid = 'abc'
        or exists (
            select 1
            from userfollow f
            where f.follower_id = 'abc' and f.followedid = p.userid and f.status = 1
        )
    )

A: There are several ways to do this, but the following is pretty intuitive.
SELECT *
FROM UserPost
where UserPost.status = 0
and (userID = 'abc'
      or UserID in (select followedID
                    from UserFollow
                    where followerID = 'abc'
                    AND status=1))

Which returns
id  userid  posttext    status
1   abc     hello world!    0
2   xyz     hello Test!     0
3   abc     hello Que!      0
5   abc     hello Post!     0
6   rty     hello RTY!      0
7   jkl     hello JKL!      0
8   jkl     hello JKL2!     0
9   jkl     hello JKL3!     0
10  jkl     hello JKL4!     0


text:
Q: QPainter methods return "Painter not active" error I'm new to Qt5/PyQt5 and want to create a single rectangle object, append it to a list and draw it in a window, but it fails with Painter not active errors.
What's the reason for this?
Errors:

QPainter::setBrush: Painter not active
QPainter::drawRects: Painter not active

Code:
from PyQt5.QtCore import QRectF
from PyQt5 import QtCore

from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QGraphicsRectItem
from PyQt5.QtGui import QPainter, QBrush

rectangles = []

class Rectangle(QGraphicsRectItem):
    def __init__(self):
        super(Rectangle, self).__init__()
        self.brush = QBrush(QtCore.Qt.blue)

    def paint(self, painter, option, widget):
        painter = QPainter()
        painter.setBrush(self.brush)

        self.setRect(10, 10, 300, 300)
        painter.drawRect(10, 10, 200, 200)

    def boundingRect(self):
        return QRectF(0,0,800,800)

class GraphicsWindow(QGraphicsView):
    def __init__(self, parent=None):
        super(GraphicsWindow, self).__init__(parent)
        scene = QGraphicsScene(self)

        rectangle = Rectangle()
        rectangles.append(rectangle)
        scene.addItem(rectangle)

        scene.setSceneRect(0, 0, 800, 800)
        self.setScene(scene)
        self.setCacheMode(QGraphicsView.CacheBackground)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    graphics_window = GraphicsWindow()
    graphics_window.show()
    sys.exit(app.exec_())

A: in your paint method you already have a painter object, I am not sure hy you are doing painter = QPainter() instead of using that painter(if that is valid refernce to an object), anyways, you are creating a new painter object, so before you paint anything, the following code is actually c++ code but since qt is a language independent framework, the way to go is the same...
painter.begin(this);
painter.doSomePicasso(); //paint what you need
painter.end();

in python should be something like
qp.begin(self)
self.drawText(event, qp)
qp.end()


text:
Q: I want to capturing only icmp packet but getting error only I am making a packet capture tool using pyshark and python argparse module. so I want to make a feature that only print the imcp when the command -ieth0 -I is used. but I am getting error.
as well the code only show the tcp and udp protocol . it does not show other protocol like imp, arp, etc while capturing the packet.
my code is below.
import argparse
import pyshark
import time
#import psutil

parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', help = 'to save the file in pcap format')
parser.add_argument('-c','--count', help = 'to print limited number of packet',type=int)
parser.add_argument('-d','--dns', help = 'to print dns packet', required=False, action='store_ture)
parser.add_argument('-I', '--ICMP', required=False, action='store_true', help = 'to capture icm packet)
parser.add_argument('-t', '--tcp',required=False, action='store_true', help='to capture tcp packet)
parser.add_argument('-u','--udp',required=False, action='store_true', help='to cpature only udp)
parser.add_argument('-v', '--verbose', help='be more specific', default=False, action='store_true)
parser.add_argument('-i', '--interface',metavar="", type=str, required=True, help='network interface)
args = parser.parse_args()

if args.dns:
   print ("-----------------------------DNS packets only---------------------")
   capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='icmp')

#elif args.output:
 #  print ("---------------------------capture and save the packet-----------------")
   #capture = pyshark.LiveCapture(output_file=args.output)

elif args.count:
   capture = pyshark.LiveCapture(interface=args.interface)
   for packet in capture.sniff_continuously(packet_count=args.count):
       if packet == args.count:
          break

elif args.ICMP:
    print ("--------------------------ICMP packets only----------------------------")
    capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='icmp')

elif args.tcp:
    print ("--------------------------TCP packets only-----------------------------")
    capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='tcp')

elif args.udp:
    print ("------------------------UDP Packets only -----------------------------")
    capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='udp port 53')

else:
    capture = pyshark.LiveCapture(interface=args.interface, output_file=args.output)

packet_list =[]
for packet in capture.sniff_continuously():
    packet_list.append(packet)
    localtime = time.asctime(time.localtime(time.time()))
    protocol = packet.transport_layer
    src_addr = packet.ip.src
    src_port = packet[protocol].srcport
    dst_addr = packet.ip.dst
    dst_port = packet[protocol].dstport
    print(localtime,"\t",protocol,"\t", src_addr,"\t", src_port,"\t", dst_addr, "\t", dst_port)
    if args.verbose:
        print (packet.show())

output
--------------------------ICMP packets only----------------------------
Traceback (most recent call last):
  File "/home/kali/help.py", line 54, in <module>
    src_port = packet[protocol].srcport
  File "/home/kali/.local/lib/python3.10/site-packages/pyshark/packet/packet.py", line 50, in __getitem__
    if layer.layer_name == item.lower():
AttributeError: 'NoneType' object has no attribute 'lower'


text:
Q: AJAX URL request doesn't work from desktop Running this simple AJAX with WAMP localhost I can pull JSON from a web address.
$(document).ready(function(){
   $.ajax({
      url: 'http://time.jsontest.com/',
      dataType: 'jsonp',
      success: function(json)
      {
          console.log(json);
      }
  });
});

However I cannot connect if I try running normally through a browser, why is that?
Google CDN:
<src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">

A: If by "standard browser" you mean you're viewing the page through a file:// URL, then yes, that src for the script tag is not going to work.
A URL starting with // is a protocol-relative URL. Just like /foo is relative to the current protocol, server, and port, // is relative to just the protocol. So it inherits the protocol of the containing document.
This is usually used so that you use http or https for the script depending on the container document. But if you do that and you're using a local file (the file protocol), then your relative URL ends up resolving to:
file://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js
...which won't work (well, unless you have a directory at the root of your file system called ajax.googleapis.com with the subdirectory ajax containing libs containing jquery containing 1.10.1 that has the file in it).
Just put http: or https: before the // in the URL to make it absolute.

A: The only thing I can think is that you're using a local copy of jQuery and it doesn't exist on the server relative to where you've uploaded it? Do you have any errors?

A: your local server acts as a compiler. just running it on your browser without a server means no compiler. NO COMPILER NO SUCCESSFUL EXECUTION
just a theory subject to debate. i hope you find it helpful


text:
Q: Run virtualenvwrapper commands from python script When I'm trying to create a new Python 3 virtual environment by using mkvirtualenv (virtualenvwrapper command) and os.system like this
import os
os.system('mkvirtualenv foo')

nothing happens.
os.system("mate-terminal -e 'workon foo'")

doesn't work either.
The point is to quickly create a new virtual env and work on it later for each project (it's an automation script). virtualenvwrapper is the most convenient option.

A: The mkvirtualenv and workon commands are shell functions, not executables in your PATH[0].
 To make them available in the shell you execute them in, you need to source the virtualenvwrapper.sh shell script defining them. You might be better off calling virtualenv /path/to/foo directly.
How to activate that virtualenv is another story, though, and will depend on the context you want to use it in. If you activate it in a subprocess, each process using it will have to be run in or under that child.
Hth,
dtk
PS In addition, you might look into the subprocess module (or even the third-party sh) for calling external programs. Happy coding :)
[0]: See $ which workon in a terminal vs $ which bash

A: The following codes in the bash shell script
env_name="<your env name>"
echo "Create virtual environment"
source `which virtualenvwrapper.sh`
mkvirtualenv $env_name -p python<$version>
source $HOME/.virtualenvs/$env_name/bin/activate
workon $env_name

then run bash script (for example: test.sh) from terminal source test.sh


text:
Q: want to view sql latest data in top and old data last. means latest to old I make php form for sql data view. problem is i want view latest data in top and old data last. can some help me??
Here is my php form view code.
all details here for get data from sql. and its work fine, but in need view latest to old.

        S.No
        Notice Title
        Publish Date
        Type
        View
        Delete
        Download

    <?php
      while($r = mysqli_fetch_assoc($result)){
     ?>

        <?php echo $r['id'] ?>
        <?php echo $r['name'] ?>
        <?php echo $r['date'] ?>
        <?php echo $r['type'] ?>

          <a type="button" class="btn btn-success" href="<?php echo $r['location'] ?>">View

          <a type="button" class="btn btn-danger delete" title="Delete this notice" href="#" onclick='DeleteFile(<?php echo $r['id'] ?>)'>

          <a type="button" class="btn btn-primary download" href="<?php echo $r['location'] ?>" title="Download <?php echo $r['name'] ?>" download="<?php echo $r['name'] ?>" {%=file.thumbnailUrl?'data-gallery':''%}>

      <?php
      }
      ?>

          S.No
          Notice Title
          Publish Date
          Type
          View
          Delete
          Download

please help me

A: You can try this feature. This will order your first and second column in ascending order.
where 0 and 1 are index of your columns
$('#table_id').dataTable( {
    "order": [[ 0, 'asc' ], [ 1, 'asc' ]]
});


text:
Q: VS Code, HTML autocomplete, single quotes instead of double quotes In VS code, typing img then hitting tab gives
I would like it to autocomplete with single quotes, i.e.
I changed the setting html.completion.attributeDefaultValue from doublequotes to singlequotes but this has not had the desired effect.
The html.completion.attributeDefaultValue setting seems to only have an impact if you have <img src, and then hit tab, in which case it gives <img src=''
Does anyone know if there is a setting which can be changed which would allow img to autocomplete with single quotes directly?

A: For things like that most people, me included, use the extension prettier.
After installing it, create a ".prettierrc" file in your projects root and add  the following to it.
{
  "singleQuote": true,
}

A: I used prettier too, but couldn't make it work with the ".prettierrc" file when writing JSX, but if you go to your extension settings and scroll down a bit you will find "Prettier: Jsx Single Quote" with a checkbox, just turn that one on and it will work. Also at the very bottom of the setting is a second checkbox for "Prettier: Single Quote".
EDIT: I still had some issues with the quotes even after trying this, solved it again by checking on the settings for all format files, since I was editing a JS and not a "JSX" file it had a separate setting.
Settings window containing "quote" on the search bar
Just type "quote" on the search bar of the settings window and you can find all the related rules for all file formats. hope this helps someone :)


text:
Q: How to search google programatically with a keyword and get my website rank? I want to call a google service using javascript with a keyword and a website url, and get from google the position of this site while searching with this keyword.
This is possible? can be done just using javascript or will need a server side language?

A: This link looks promising: Getting google page rank using javascript

A: You're going to have security issues using JavaScript to query another domain that isn't the one that served the HTML.
If you can write your own service, your best bet (for scraping) would be to send a query to this page: http://www.google.com/ie.  It provides clean HTML that can be parsed with a regular expression.  This page is also nice in that you can pass in a 'num' parameter and get more than just 10 results at a time.  (if you're looking for perfect results, when doing this you aren't going to get exactly the same results as going 10 at a time).
With a service like this running on your server, your JavaScript code won't have any problems, until Google notices too many queries coming from your server's IP address and decides to blacklist you.  ;)
I'd also suggest using Google's AJAX Search API, if you can live with it being limited to 64 total results.

A: You can use my PHP Class, it searches via Google AJAX Search API and checks the results for your Domain/URL. You can also check for different Domains/URLs if you want to know the ranking for your competitors:
http://bohuco.net/blog/2010/07/google-ranking-checker-class-in-php/

A: You can use the Google Search API to develop any search from applications or pages in AJAX

A: Not exactly what you want, but Google Webmaster Tools will list top searches for your site and how far down the results you are.

A: You can just use curl and regexp to get the results but Google will catch on to you scraping results if you do a lot of calls (and return bogus results) so you have to have full header support.

A: The 1st link given by Kevin Pullin, indeed works.
You can get what you want to with SEO Analyzer
Download from code.google.com/p/seoanalyzer


text:
Q: Ingesting an array of JSON objects and transforming to tabular data I have an array of JSON objects like such.  Each array encapsulated by [ and ] are on a single line.
[{"event":0,"properties":{"color":"red","connectionType":2}}{"event":30,"properties":{"color":"blue","connectionType":4}},{"event":45,"properties":{"color":"green","connectionType":3}}]
[{"event":0,"properties":{"color":"red","connectionType":5}},
{"event":1,"properties":{"color",:"blue","connectionType":6}}]
Here it is in an easier to read format.
[
    {"event":0, "properties":{"color":"red","connectionType":2}},
    {"event":3, "properties":{"color":"blue",'connectionType":4}},
    {"event":45, "properties":{"color":"green","connectionType":3}}
]
[
    {"event":0, "properties":{"color":"red","connectionType":5}},
    {"event":1, "properties":{"color":"blue","connectionType":6}}
]

Some things to note, so each JSON object inside an [ ] are in a single line. The number of objects in each line varies. The number of fields inside properties also varies.
What I want with this data, is to take each JSON object and convert it to tabular format in the form of comma separated or tab separated values
| event    | color    | connectionType
  0          red        2
  3          blue       4

I've looked at a few tools that are used by PIG to read JSON structures - namely elephant-bird, but can't quite get it to work on my data.
I'm hoping to get pointers on alternative solutions, or example code using elephant-bird / other pig json parsers. My end goal is really to just capture a subset of events and properties and load them into Hive.

A: in your json file. you don't have start object. So it is not differentiate between rows. I found solution but i have put start object in your json object.
{"startObject":[{"event":0, "properties":{"color":"red","connectionType":2}},{"event":3, "properties":{"color":"blue","connectionType":4}},{"event":45, "properties":{"color":"green","connectionType":3}}]}

A = LOAD '/home/kishore/Data/Pig/pig.json' USING JsonLoader('{(event:chararray,properties: (color:chararray,connectionType:chararray))}');
B = foreach A generate Flatten($0);
C = foreach B generate $0,Flatten($1);
Dump C;

Result

(0,red,2)
(3,blue,4)
(45,green,3)

if you want to parse your json object without putting start object, in this case you should write your own custom UDF.
https://gist.github.com/kimsterv/601331
or go for elephant-bird
https://github.com/twitter/elephant-bird


text:
Q: how to truncate dataset plot Assume I have a data set plot vector with 2 columns(x,y)
However, I do not want to plot out the entire set, but truncate the plot from x1 to x2, some set x value that I know. How would I do this?

A: Two options I can think of, if you know the indices of the range, then:
plot(x(x1:x2),y(x1:x2)); % here x1 and x2 are indices, not values

Otherwise you can always:
range=find(x>x1 & x<x2); % here x1 and x2 are actual values, you can use any other condition needed...
plot(x(range),y(range))


text:
Q: Gstreamer multifilesink wav files splitting I have problem with recording streams using gstreamer.
I have to write audio and video separately and cut in when signal arrived. I have correctly working video, but still have problems with wav files.
Even simple pipeline in gst-launch don't work correctly. I have wave file and I am trying to split it using multifilesink:
gst-launch filesrc location=test.wav ! multifilesink location=test2%d.wav next-file=4 max-file-size=512000
But final wav files are corrupted while the same pipeline with ts files is working ok:
gst-launch-1.0 filesrc location=test.ts ! multifilesink location=test2%d.ts next-file=4 max-file-size=2000000

A: multifilesink doesn't know anything about the data it splits up, so it won't take care of adding headers to each of the files it writes.
The reason why your .ts files work is because it was designed to be a streaming format where each separate packet will be treated independently. Therefore, one can just 'tune in' to the stream whenever one likes. The decoder will simply look for the next packet header it finds and start decoding there (for Details have a look at MPEG TS' wiki page.
The WAV file format however was designed as pure file (and not as a streaming) format. Therefore, there's only one header at the start of the file. When you split that file up into multiple files, these headers are missing (the file contains only raw PCM data then).
To work around that issue, you can...

*

*manually copy the .wav header from the first file to all the other ones

*use programs that support PCM files and either work directly with them or convert the files  (you'll have to set the channel count, sample rate and bitrate manually when opening those files though).

*use another, stream oriented file format like .mp3 which comes from the same family of codecs as .ts and also uses a separate 4-byte header for each frame (Keep in mind though that MP3 is a lossy file format).
An example pipeline would be:
gst-launch filesrc location=test.wav ! wavparse ! lame ! multifilesink location=test%d.mp3 next-file=4 max-file-size=100000

A: If you're willing to use some scripting as well and split the task up into different gst-launch calls, I can offer you another possible way to solve your little problem:
The following script is a Linux bash script. You should be able to translate that to Windows batch script (or a C or python app if you want):
#!/bin/bash -e

# First write the buffer stream to .buff files (annotated using GStreamer's GDP format)
gst-launch -e filesrc location=test.wav ! wavparse ! gdppay ! multifilesink next-file=4 max-file-size=1000000 location=foo%05d.buff

# use the following instead for any other source (e.g. internet radio streams)
#gst-launch -e uridecodebin uri=http://url.to/stream ! gdppay ! multifilesink next-file=4 max-file-size=1000000 location=foo%05d.buff

# After we're done, convert each of the resulting files to proper .wav files with headers
for file in *.buff; do
    tgtFile="$(echo "$file"|sed 's/.buff$/.wav/')"

    gst-launch-0.10 filesrc "location=$file" ! gdpdepay ! wavenc ! filesink "location=$tgtFile"
done

# Uncomment the following line to remove the .buff files here, but to avoid accidentally
# deleting stuff we haven't properly converted if something went wrong, I'm not gonna do that now.
#rm *.buff

Now to what the script does:

*

*First we're gonna use multifilesink to create a set of .buff files, each under 1MB of size (gdppay will annotate each buffer with its caps; the -e flag of gst-launch will cause it to trigger an EOS if the process gets killed prematurely which is useful if you're reading and decoding an internet stream)

*The second gst-launch invocation within the for loop takes one of the .buff files, parses the GDP headers using gdpdepay (and strips them), adds a WAV header and writes the result to a .wav file.

Hope this is a solution you can live with, because I doubt there's a way to do it with one single gst-launch run.


text:
Q: Command PhaseScriptExecution failed with a nonzero exit code after revoking all certificates in a keychain I have replaced my keychain password and it deleted all the items in it. I started getting the
Item not found in a keychain error, so I regenerated development certificates, and now on every project, I get Command PhaseScriptExecution failed with a nonzero exit code
I have tried

*

*locking and unlocking login in Keychain Acess

*cleaning build folder

*restarting my mac

*pod deintegrate pod install

*re-deleting keychain

*restore previous keychain

This issue shows itself only while building on a real device
At this point I have no idea what can I do to make this error go away.

A: Ok, this situation is an absolute joke, but that what helped me to solve this.

*

*Restoring all my previous keychains

*Deleting all certificates to my name in each of them.


text:
Q: Xcode всплывающее меню подсказок Всплывающее меню подсказок Xcode-а, рядом с функциями находится цветной буквенный символ - V, M, C, T и т.д. Что он означает?

A: C - class
M - method
T - type
V - variable
P - property
f - function
{} - code snippet
Ну и далее по аналогии


text:
Q: silverlight accept invalid certificate I'm doing https web requests in silverlight using "WebRequest"/"WebResponse" framework classes.
Problem is: I do a request to an url like: https://12.34.56.78
I receive back a versign signed certificate which has as subject a domain name like: www.mydomain.com.
Hence this results in a remote certificate mismatch error.
First question: Can I somehow accept the invalid certificate, and get the WebBresponse content ? (even if it involves using other libraries, I'm open to it)
Additional details: (for those interested on why I need this scenario)
I'm trying to give a client access to a silverlight app deployed on a test server.
Client accesses the silverlight app at: www.mydomain.com/app
Then I do some rest requests to: https://xx.mydomain.com
Problem is I don't want to do requests on https://xx.mydomain.com, since that is on our  productive server. For this reason I use https://12.34.56.78 instead of https://xx.mydomain.com.
Client has some firewalls/proxies and if I simply change his hosts file and map https://xx.mydomain.com  to 12.34.56.78, web requests don't resolve to the mapped IP.
I say this because on his network webrequests fail if I try that, on my network I can use the hosts changing without problems.
UPDATE: Fixed the problem by deploying test releases to an alternative: https://yy.domain.com and allowing the user to configure for test purposes, the base url to which I do requests to be: https://yy.domain.com.
Using an certificate that contained the IP in the subject or an alternative subject would've probably worked too, but would have cost some money to be issued by a certified provider and would not be so good because IP's might change.

A: After doing more research looks like Microsoft won't add this feature too soon, unless there's a scenario for non-testing/debugging uses.
See: http://connect.microsoft.com/VisualStudio/feedback/details/368047/add-system-net-servicepointmanager-servercertificatevalidationcallback-property


text:
Q: How to return a list of items from a different py file I have 2 .py files (data.py, access.py)
In access.py, I have a few strings:
Japan = ['brown', 'cow', 'around']
Korea = ['black', 'chicken', '344']
China = ['grey', '3411', 'leaf']
Indonesia = ['red', 'green', '']

In data.py, I have a module:
def whichcolour(country)
       print("access + country[1]")  # Doesn't work

My Results
What I am trying to achieve is, to run whichcolour through data.py and it will return/ print out whatever is in that list.
I know print(access.Japan[1]) works.. It returns cow.
How should the print statement be written such that it gives me the same result?

A: Use a dictionary.
access.py
countries = {
    'Japan': ['brown', 'cow', 'around'],
    'Korea': ['black', 'chicken', '344'],
    'China': ['grey', '3411', 'leaf'],
    'Indonesia': ['red', 'green', '']
}

data.py
from access import countries

def whichcolour(country, countries):
    print('{} has the color {}'.format(country, countries[country][0]))

for country in countries:
    whichcolour(country, countries)

output:
Japan has the color brown
Korea has the color black
China has the color grey
Indonesia has the color red

I'm not 100% sure what you want to do (there are two colors for Indonesia) but this should get you started.


text:
Q: Integer conversion to floating point type by python I am a newer in python study,when I run the following program:
 self.QRSpeaks -= 40 * (self.samplingrate / 1000)

The problom I encounted is :
self.QRSpeaks -= 40 *(self.samplingrate / 1000)
    TypeError: Cannot cast ufunc subtract output from dtype('float64') to  dtype('int32') with casting rule 'same_kind'

How to solve this problem? Thank you for your reply

A: Casting mean this self.QRSpeaks -= 40 * (self.samplingrate / float(1000))
Or self.QRSpeaks -= 40 * (self.samplingrate / (1000*1.0))
and the main problem discuss here :
https://github.com/numpy/numpy/issues/7225
you can use: casting='unsafe'
example: np.add(a, b, out=a, casting="unsafe")


text:
Q: How can I modify the maximum value of my progress bar So, I'm making a progress bar that is getting its values from some variables I have declared, all is working well except there is one issue. When my aria-value now meets my aria-value max there is still space left over in the progress bar since it fills the width of it to only 80% and not 100%. So I'm kind of stuck on a fix for this. Here's my Code
 <?php
      $current_players=$infosprp['players'];
      $max_players=$infosprp['places'];
      $width = $current_players;

      echo '

           '.$width.'/'.$max_players.'

';
?>

Here is a picture of the result when the progress bar is filled
I'm bad at explaining things, so I hope you were able to understand. Thanks.

A: The width should be the percentage of $current_players divided by the $max_players. It is only filling up to 80% because the $width is only 80 (players) as shown in the image you linked. The computation for $width should be the following:
$width = $current_players / $max_players * 100;

A: The width of process bar is 100%. In your image displaying 80% completed, so you use
new varibale like   $statusBar = ($current_players * 100) / $max_players;
Please see below example, I think it's should work for you.
 <?php
          $current_players=$infosprp['players'];
          $max_players=$infosprp['places'];
          $width = $current_players;
          $statusBar = ($current_players * 100) / $max_players;

          echo '

               '.$width.'/'.$max_players.'

';
    ?>


text:
Q: How to test if an application (.exe) is built with runtime package How may I test in coding if my .exe Delphi application is built with runtime package or is single .exe?

A: Another possibility:
function UsesRuntimePackages: Boolean;
begin
  Result := FindClassHInstance(TObject) <> HInstance;
end;

A: Another possibility, in case you need this for an external executable (without running it):
procedure InfoProc(const Name: string; NameType: TNameType; Flags: Byte; Param: Pointer);
begin
  case NameType of
    ntContainsUnit:
      if Name = 'System' then
        PBoolean(Param)^ := False;
  end;
end;

function UsesRuntimePackages(const ExeName: TFileName): Boolean;
var
  Module: HMODULE;
  Flags: Integer;
begin
  Result := True;

  Module := LoadLibraryEx(PChar(ExeName), 0, LOAD_LIBRARY_AS_DATAFILE);
  try
    Flags := 0;
    GetPackageInfo(Module, @Result, Flags, InfoProc);
  finally
    FreeLibrary(Module);
  end;
end;

A: Use could use the EnumModules() procedure, like so:
function EnumModuleProc(HInstance: Integer; Data: Pointer): Boolean;
begin
  Result := True;
  if HInstance <> MainInstance then begin
    Inc(PInteger(Data)^);
    Result := False;
  end;
end;

function UsesRuntimePackages: boolean;
var
  PckgCount: integer;
begin
  PckgCount := 0;
  EnumModules(EnumModuleProc, @PckgCount);
  Result := PckgCount > 0;
end;

A: Did you try "Islibrary" ?


text:
Q: @RequestHeader in spring not accepting fake headers I am using
@RequestHeader(value = "channel") String channel

in Spring application controller to get headers and it works fine for normal headers, however, in some cases, I need to trap a request using filter and use HttpServletRequestWrapper to add some extra headers. The new headers added by overriding getHeader method are not being accepted by @RequestHeader annotation and throws error. However, if I manually get headers using
HttpServletRequest.getHeader("channel")

the new headers work fine. Is there any bug in @RequestHeader implementation? If so, is there any work-around so that I wouldn't have to change the same thing in 50+ APIs.

A: When resolving @RequestHeader, Spring is using getHeaders(), not getHeader(). You need to override this one.


text:
Q: What is Gdx.graphics.getWitdth() measured in? I'm using getWidth and getHeight a lot for scaling textures in my Libgdx project.  What units are these in (pixels?)
Also, if I want the texture to look consistent on different phones, should I use getWidth/Height to scale, or some number value like width = 100, height = 50?

A: Yes, getWidth and getHeight are both measured in pixels. Although you can use these for your dimensions, usually what you'll want to do to get a consistent look across phones is to use a camera of some sort (for 2d games, generally an OrthographicCamera).
What you'll probably want to do is give the camera some fixed width and height, and then do all of your drawing through the camera's transformations. Something like:
SpriteBatch batch = new SpriteBatch();
OrthographicCamera camera = new OrthographicCamera(800, 600);
//some code here
batch.setProjectionMatrix(camera.combined);
batch.begin();
//draw your textures here
batch.end();

This should keep the scale of your images consistent across phones. Keep in mind that if there is too much of a stretch/compress, your textures may look distorted.

A: @clearlyspam23 that's exactly what I'm looking for, thank you!  Just a note, set it up like:
OrthographicCamera camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 600);

The other way looks like it positioned the camera origin at 800, 600.
Thanks again!


text:
Q: Sendinblue SMTP not working in CodeIgniter I am using CodeIgniter and I have set up a bunch of emails for my customers and sending them through SMTP ... Now the requirement of the job is to use Sendinblue for sending emails... So I simply replaced my SMTP credentials with ones provided by Sendinblue... and mails are not being sent.. please help
Older Code (When mails were sending)
$config = array(
                'protocol' => 'smtp', // 'mail', 'sendmail', or 'smtp'
                'smtp_host' => smtp.example.com,
                'smtp_port' => 465,
                'smtp_user' => MY_USER,
                'smtp_pass' => '',

                'smtp_crypto' => 'ssl', //can be 'ssl' or 'tls' for example
                'mailtype' => 'html', //plaintext 'text' mails or 'html'
                'smtp_timeout' => '4000', //in seconds
                'charset' => 'iso-8859-1',
                'wordwrap' => TRUE
            );

SendinBlue SMTP details (mails are not working now)
$config = array(
                'protocol' => 'smtp', // 'mail', 'sendmail', or 'smtp'
                'smtp_host' => smtp-relay.sendinblue.com,
                'smtp_port' => 587,
                'smtp_user' => MY_USER,
                'smtp_pass' => MY_PASS,

                'smtp_crypto' => 'ssl', //can be 'ssl' or 'tls' for example
                'mailtype' => 'html', //plaintext 'text' mails or 'html'
                'smtp_timeout' => '4000', //in seconds
                'charset' => 'iso-8859-1',
                'wordwrap' => TRUE
            );

A: I have found an alternative simple solution.. pasting my answer if anyone needs in future...
I have used this CURL request, Mailin Provided by SendinBlue
https://github.com/mailin-api/mailin-api-php/tree/master/src/Sendinblue


text:
Q: Process responses from xmlrpclib I use my own class X, that has api attribute which is ServerProxy from xmlrpclib. It looks more or less like this:
class X:
    def __init__(self):
        self.api = xmlrpclib(...)

I call a lot of xmlrequests by self.api.something(), but I'd like to parse response and if I find errorcode defined by my custom API (For example response looks like: ERROR CODE 0001), I'd like to raise custom Exception. otherwise return result.
One idea I had is to somehow derive by ServerProxy, but tbh. I have no idea how to do that correctly, so it works in given situation.


text:
Q: How to find field lines? Let $F(x,y)=x \hat{i}+ y\hat{j}$. Its field lines satisfy
$$\cfrac{dx}{x}=\cfrac{dy}{y}.$$ Then, I write $ydx = xdy$ so that $xy +C_1 = xy +C_2 $ which implies $xy=C$ for some constant $C$. This is how its found in the examples.
 However, the book says that $\cfrac{dx}{x}=\cfrac{dy}{y} \implies \ln(x)+C_1 = \ln(y)+C_2 \implies \ln(y) = \ln(x) +C \implies y =Dx$.
So, what is the argument that I am missing? Thanks.


text:
Q: Android testing onActivityResult errors with Espresso I have a fragment in my activity, that it will get some data on its onActivityResult(), And try to update the UI. This is my onActivityResult() code:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {

            GET_USER_AUDIO_TO_TEXT_REQUEST_CODE -> {

                if (resultCode == RESULT_OK) {
                    data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)?.let {
                    val receivedCityName = it[0]
                    binding.homeCityNameEditTextView.setText(receivedCityName)//Update UI at this line
                    viewModel.fetchWeatherCity(receivedCityName)
                }
                } else {
                    Toast.makeText(activity, R.string.error_while_getting_data_from_recognizer, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

So I tried to create some Instrumentation test with the Espresso for this part as bellow:
 @Test
 fun checkActionsAfterReceivingDataInOnActivityResult() {

        val intent = Intent()
        intent.putStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS, arrayListOf(DEFAULT_CITY_NAME))

        activityRule.activity.supportFragmentManager
                .findFragmentByTag(HomeFragment.CLASS_NAME)
                ?.onActivityResult(
                        HomeFragment.GET_USER_AUDIO_TO_TEXT_REQUEST_CODE,
                        Activity.RESULT_OK,
                        intent
                )

    }

But I will get an error after running this Test method that says:
This error is because of my ViewModel methods that will run. by calling this line in onActivityResult():
viewModel.fetchWeatherCity(receivedCityName)

This is its error:
java.lang.IllegalStateException: Cannot invoke setValue on a background thread
at android.arch.lifecycle.LiveData.assertMainThread(LiveData.java:435)
at android.arch.lifecycle.LiveData.setValue(LiveData.java:279)

And because of updating my UI by this line:
binding.homeCityNameEditTextView.setText(receivedCityName)//Update UI at this line

I will get this error too:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

A: Test instrumentation runs on a different thread, so wrap up the test method-body with run on UI thread.
activityRule.activity.runOnUiThread {
  // the test method body goes in here
}

In your case:-
activityRule.activity.runOnUiThread {
   activityRule.activity.supportFragmentManager
                .findFragmentByTag(HomeFragment.CLASS_NAME)
                ?.onActivityResult(
                        HomeFragment.GET_USER_AUDIO_TO_TEXT_REQUEST_CODE,
                        Activity.RESULT_OK,
                        intent)
}

A: You shouldn't invoke methods such as onActivityResult directly in your Espresso test. You will always get the same error because these tests are executed on different threads. If you want to test it correctly, you should consider using Espresso-Intents:
@Test
fun checkActionsAfterReceivingDataInOnActivityResult() {
    val intent = Intent()
    intent.putStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS, arrayListOf(DEFAULT_CITY_NAME))

    intending(hasComponent(YourActivity.class.getName())).respondWith(ActivityResult(Activity.RESULT_OK, intent))

    // onView(...).perform(click())
    // First do something to cause your app to launch the intended activity

    // onView(...).check(matches(...))
    // Then test something on activity result
}


text:
Q: SQL Server query with multiple joins I have a query to build with multiple joins. I would like to know which one is the best practice (fastest) between the 2 below. They both return the same result. Thank you
SELECT A.ID FROM RE7.DBO.RECORDS AS A
LEFT OUTER JOIN [re7].[dbo].[ADDRESS] AS B ON A.ID=B.ID
WHERE B.COUNTRY = 1670

SELECT A.ID FROM RE7.DBO.RECORDS AS A
INNER JOIN (SELECT ID FROM [re7].[dbo].[ADDRESS] WHERE COUNTRY = 1670) AS B
ON A.ID=B.ID

A: SELECT A.ID FROM RE7.DBO.RECORDS AS A
INNER JOIN (SELECT ID FROM [re7].[dbo].[ADDRESS] WHERE COUNTRY = 1670) AS B
ON A.ID=B.ID

INNER JOINS are almost always faster than LEFT OUTER JOIN.   LEFT OUTER JOIN takes the longest of all the joins.
You might not see a big difference in query time in this case, but INNER JOINS are best practice.


text:
Q: Sub New() has multiple definitions with identical signatures I was working in ASP.Net web forms application (website not web application) on Win 7 and everything was fine.
I had to transfer my solution to another machine also win 7, once I did that everything became NOT OK.
when I build my solution I got tons of building errors in files existing in
c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
most of these errors such
Protected Sub New(info As System.Runtime.Serialization.SerializationInfo, context As System.Runtime.Serialization.StreamingContext) has multiple definitions with identical signatures.
and
Public Sub New()' has multiple definitions with identical signatures.
I googled it and tried all solution stated in all sites. clearing my solution and rebuild it,
clearing Temporary ASP.NET Files folder, clearing C:\Users\user\AppData\Local\Temp and also manually deleted .NETFramework,Version=v4.0.AssemblyAttributes.cs exists in Temp folder
even I created new solution with different name but of course I imported files from old solution.
Nothing work for me, I don't know what is the problem exactly and why it happen and how can I solve it and back my solution to live?

A: Usually when you use Visual Studio to generate some code for you (for data or whatever) it does them as Partial Class ... so you can create another partial class and add your own code to the same class without loosing your changes when the tool regenerates it's code. Long story.
Anyway, since this is a web site, all files in the folder are part of the project. If you accidently copy the same file twice, it is automatically added and your partial class with the same methods and properties (like NEW) now have multiple definitions.
Look for copies of the same classes.


text:
Q: "subscript out of range" in excel vba I am getting "subscript out of range" in excel vba at the line "Workbooks("source").Sheets("Sheet1").Activate"
Sub one()
    Dim target As Object
    Set target = ThisWorkbook

    source = Application.GetOpenFilename( _
        FileFilter:="Excel 2003 (*.xls),*.xls,Excel 2007 (*.xlsx),*.xlsx,Excel 2007 (*.xlsm),*.xlsm", _
        Title:="Select an the sdlc workbook", _
        MultiSelect:=File)
    If source = False Then
        Exit Sub
    Else
        Workbooks.Open Filename:=source
    End If
    Workbooks("source").Sheets("Sheet1").Activate
End Sub

A: It appears source is a variable, not the actual name of the workbook. It would be easier to use a Workbook variable rather than the name:
Sub one()
    Dim target As Excel.Workbook
    Set target = ThisWorkbook
    Dim wbSource as Excel.Workbook

    source = Application.GetOpenFilename( _
        FileFilter:="Excel 2003 (*.xls),*.xls,Excel 2007 (*.xlsx),*.xlsx,Excel 2007 (*.xlsm),*.xlsm", _
        Title:="Select an the sdlc workbook", _
        MultiSelect:=File)
    If source = False Then
        Exit Sub
    Else
        Set wbSource = Workbooks.Open(Filename:=source)
    End If
    wbSource.Sheets("Sheet1").Activate
End Sub


text:
Q: Rails as_json with conditions In my application, :foos have many :bars, and I'm serializing each foo as JSON like so:
@foo.as_json(
  except: [:created_at, :updated_at],
  include: {
    bars: { only: [:ip_addr, :active] }
  }
)

This gives me the following:
{
  "id" => 2,
  "name" => "Hello World",
  "bars" => [
    { "ip_addr" => "192.123.12.32", "active" => 0 },
    { "ip_addr" => "192.123.12.33", "active" => 1 }
  ]
}

As you can see, my serialized hash includes an inactive bar. How can I exclude inactive bars from my hash?
It would be great if I could do this:
include: { bars: { only: { :active => true }}}

Have I taken as_json as far as it will go? Do I need to switch to active model serializers now?

A: I think you could try add some method like active_bars which will return exactly what you need like:
def active_bars
  bars.where active: true
end

or you could even add new relation:
has_many :active_bars, -> { where active: true }, class_name: '..', foreign_id: '..'

and then you will be able write:
@foo.as_json(
  except: [:created_at, :updated_at],
  include: {
    active_bars: { only: [:ip_addr, :active] }
  }
)

A: you use as_json with conditions for customize json response for some actions, but model serializers  for default json response that you needed for the most responses.
Read these Model_Serializer VS. as_json, record-serializers-from-scratch.


text:
Q: How to divide digits and compare them, in C Write a program that will find the largest number smaller than N that is totally different from a given number X. One number is totally different from other only if it doesn't contain any of the digits from the other number. N and X are read from standard input. The problem should be solved without the use of arrays.
Example Input 1:  400 897
Example Output 1: 366
Example Input 2: 1000 1236498
Example Output 2:777
No it's not homework, it was on one of the midterms and it's been killing me. I though about taking the first numbers last digit with %10 then taking the second numbers digit with %10 comparing them but...I just can't get it to work...I ended up with an endless loop...I just don't understand how to get every digit of the numbers and compare them to the other number.
#include <stdio.h>

int main () {
int N, X, num_N, num_X, i, lastDigit_N, lastDigit_X, flag, smaller_than_N;

scanf("%d%d", &N, &X);
smaller_than_N = N - 1;

for (i = smaller_than_N; i > 0; i--) {
num_N = i;
num_X = X;
flag = 0;

while (num_N > 0) {
lastDigit_N = num_N % 10;

while (num_X > 0) {
lastDigit_X = num_X % 10;

if (lastDigit_N == lastDigit_X) {
break;
}

else {
flag = 1;
}

num_X /= 10;
}
num_N /= 10;
}

if(flag) {
printf("%d", i);
break;
}
}

return 0;
}

A: You could build a bitmask for your numbers showing the digits which are contained.
uint16_t num2bitmask(int number)
{
    uint16_t result = 0;
    while (number) {
        int digit = number % 10;
        number /= 10;
        result |= (1 << digit);
    }
    return result;
}

With this function, you can create your bitmask for X and then iterate from N-1 down to 1 until you find a value which doesn't have any bits in common with the other value.

A: If you have a number with digits d_1, d_2, ..., d_n, and you're allowed to use digits in the set D, then possible solutions look like:
d_1, ..., d_{i-1}, max(d in D | d < d_i), max(d in D), ..., max(d in D).

That is, the digits are the same up to some point, then the next digit is as large as possible while being below the input digit, then the rest are just as large as possible.
Not all these "solutions" will be valid, but if you iterate through them in reverse order (there's exactly n for an input number of size n), the first valid one you find is the answer.
Some code, including tests:
#include <stdio.h>

int digit_length(int a) {
    int r = 0;
    while (a) {
        a /= 10;
        r += 1;
    }
    return r;
}

int get_digit(int a, int k) {
    while (k--) a /= 10;
    return a % 10;
}

int largest_different(int a, int b) {
    int lena = digit_length(a);
    int invalid = b ? 0 : 1;
    for (; b; b /= 10) invalid |= 1 << (b % 10);
    int max_valid = 9;
    while (max_valid >= 0 && (invalid & (1 << max_valid)))
        max_valid--;
    if (max_valid == -1) return -1;
    for (int i = 0; i < lena; i++) {
        int d = get_digit(a, i) - 1;
        while (d >= 0 && (invalid & (1 << d)))d--;
        if (d < 0) continue;
        int solution = 0;
        for (int k = lena - 1; k >= 0; k--) {
            solution *= 10;
            solution += (k < i ? max_valid : k > i ? get_digit(a, k) : d);
        }
        return solution;
    }
    return -1;
}

int main(int argc, char *argv[]) {
    struct {int n; int x; int want;} examples[] = {
        {400, 897, 366},
        {1000, 1236498, 777},
        {998, 123, 997},
    };
    int error = 0;
    for (int i = 0; i < sizeof(examples) / sizeof(*examples); i++) {
        int got = largest_different(examples[i].n, examples[i].x);
        if (got != examples[i].want) {
            error = 1;
            printf("largest_different(%d, %d) = %d, want %d\n",
                examples[i].n, examples[i].x, got, examples[i].want);
        }
    }
    return error;
}

There's not always a solution. In that case, the function returns -1.


text:
Q: How to save PDF into Documents in external storage in Android 30? How to save pdf files in default Documents folder in external storage of the android?
I have tried with:
       Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
       intent.addCategory(Intent.CATEGORY_OPENABLE);
       intent.setType("application/pdf");
       intent.putExtra(Intent.EXTRA_TITLE, name);
       startActivityForResult(intent,PDF_REQUEST_CODE);

But this opens another Document provider activity with save option. I want that the pdf file saves directly into Document folder from a single click on my application.


text:
Q: Trying to understand using a service to open a dialog I've read through discussions on opening a dialog using mvvm pattern. I've seen several examples that say to use a service, but I'm not understanding how all the pieces fit together. I'm posting this question asking for guidance in what I should read up on to better understand what I'm missing. I'll post what I have below, and it does work, but from what I'm seeing in these posts i'm not doing it right, or maybe not doing efficiently. I see where a dialog interface is created, then a class that uses the interface to do the actual work. Then in the ViewModel a constructor passes in this interface, this is the part that really confuses me, not sure what's passing it in, don't have enough information to connect the dots and not sure what i'm missing.
Here is one post I looked at: https://stackoverflow.com/a/1044304/4593652 I kind of see what they are suggesting, but it's not enough information for someone learning. I'm not asking anyone to write this for me, just hoping for some advice on what I should read up on to understand how these pieces fit together.
In my code I have a class like this: (This works, I just feel like i'm missing something from what I'm reading on other posts)
public class OpenDialogService
    {
    public string GetOpenDialog(string title)
    {
        CommonOpenFileDialog dlg = new CommonOpenFileDialog();
        dlg.Title = title;
        dlg.IsFolderPicker = true;
        dlg.AddToMostRecentlyUsedList = true;
        dlg.AllowNonFileSystemItems = false;
        dlg.EnsureFileExists = false;
        dlg.EnsurePathExists = true;
        dlg.EnsureReadOnly = false;
        dlg.EnsureValidNames = true;
        dlg.Multiselect = false;
        dlg.ShowPlacesList = true;

        if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
        {
            return dlg.FileName;
        }
        return null;
    }
}

Then I use this in my ViewModel when my command is called.
path = new OpenDialogService().GetOpenDialog("...");

A: Walther is basicly right.
The other post says that he could change his service implementation via IOC  Container. IOC means the "Inversion of Control"-Pattern, you could read this article to get a basic overview. I think "Service" comes also from that Pattern. Another buzzword is Dependency Injection you can look for.

A: Ok, there's a couple of problems here.
As @ec8or pointed out, you should read up on "Inversion of Control" (IoC) as almost all MVVM frameworks use it. The service pattern also relies on IoC so that testing is easier.
The bits missing from your code is an interface for the service, and using the IoC to inject that code into your ViewModels.
public interface IOpenDialogService
{
    string GetOpenDialog(string title);
}

public class OpenDialogService : IOpenDialogService ...

And then to use it in a ViewModel
public class MyViewModel
{
    private IOpenDialogService openDialogService;

    // service injected by the IoC
    public MyViewModel(IOpenDialogService openDialogService)
    {
        this.openDialogService = openDialogService;
    }

    public void DoCommand()
    {
        var path = openDialogService.GetOpenDialog("...");
    }
}

So why do this?
When you test the ViewModel you don't want open dialogs to suddenly pop up, causing the test to fail or hang. So during testing we can change the implementation of IOpenDialogService to something that returns a constant, for example. Then when you test the ViewModel instead of a dialog opening the code will just get the constant and continue running, allowing the test to complete.
This way you don't need to modify the ViewModel code just to get it working during testing.


text:
Q: Maven/Java-how to specify which jar file to use I have feeling I will get down voted. Please pardon my ignorance on this subject as I need to get this working soon.
Basically, I have two dependencies.  Same GroupId, Same Version, but different artifactID.
There are duplicated Classes in these two artifacts, but one of them has some beta features.
How do I ensure part of my code use classes from Jar1, the rest of my code use classes from Jar2 ?
My bad. There is no overlap. Sorry for all the confusion :-(

A: What about creating two projects? One dependent on artifactID1 other other dependent on artifactID2. One project would then depend on the other project. This is predicated on all the code using one version of the jar not being dependent on code that uses the other version.


text:
Q: ReactNative TextInput not letting me type For both iOS and Android simulators
The text just disappears/flickers when I start typing. I tried having an initial state of texts with some value instead of keeping it empty. With this the TextInput sticks to this initial state and does not update itself with new text entered.
I think the state is not updating with 'onChangeText' property, but I am not completely sure.
People have seem to solve this, as they had few typos or missing pieces in code. However I have checked mine thoroughly.
Please help if I have missed anything in the below code.
LoginForm.js
import React, { Component } from 'react';
import { Card, Button, CardSection, Input } from './common';

class LoginForm extends Component {

  state = { email: '', password: '' }

  render() {
    return (
      <Card>
        <CardSection>
          <Input
            label="Email"
            placeHolder="user@gmail.com"
            onChangeText={text => this.setState({ email: text })}
            value={this.state.email}
          />
        </CardSection>

        <CardSection>
          <Input
            secureTextEntry
            label="Password"
            placeHolder="password"
            onChangeText={text => this.setState({ password: text })}
            value={this.state.password}
          />
        </CardSection>

        <CardSection>
          <Button>
            Log In
          </Button>
        </CardSection>
      </Card>
    );
  }
}

export default LoginForm;

Input.js
import React from 'react';
import { TextInput, View, Text } from 'react-native';

const Input = ({ label, value, onChangeText, placeholder, secureTextEntry }) => {
  const { inputStyle, labelStyle, containerStyle } = styles;

  return (
    <View style={containerStyle}>
      <Text style={labelStyle}>{label}</Text>
      <TextInput
        secureTextEntry={secureTextEntry}
        placeholder={placeholder}
        autoCorrect={false}
        style={inputStyle}
        value={value}
        onChangeText={onChangeText}
      />
    </View>
  );
};

const styles = {
  inputStyle: {
    color: '#000',
    paddingRight: 5,
    paddingLeft: 5,
    fontSize: 18,
    lineHeight: 23,
    flex: 2
  },
  labelStyle: {
    fontSize: 18,
    paddingLeft: 20,
    flex: 1
  },
  containerStyle: {
    height: 40,
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center'
  }
};

export { Input };

A: The only way to solve this was to change the way the values of TextInput fields are updated, with this code below.
value={this.state.email.value}
value={this.state.password.value}

A: You problem is how the Input component is written.
There is a render function written inside the stateless component which is not a React class component:
const Input = ({ label, value, onChangeText, placeHolder, secureTextEntry }) => ( // ← remove the wrapping parentheses
  {
    render() { // <--- this should not be here
      ↑
      const { inputStyle, labelStyle, containerStyle } = styles;
      return (
        <View style={containerStyle} >
          <Text style={labelStyle}>{label}</Text>
          <TextInput
            secureTextEntry={secureTextEntry}
            autoCorrect={false}
            placeholder={placeHolder}
            style={inputStyle}
            onChangeText={onChangeText}
            value={value}
            underlineColorAndroid="transparent"
          />
        </View>
      );
    }

  }
);

Change it to this:
const Input = ({ label, value, onChangeText, placeHolder, secureTextEntry }) => {
  const { inputStyle, labelStyle, containerStyle } = styles;
  return (
    <View style={containerStyle} >
      <Text style={labelStyle}>{label}</Text>
      <TextInput
        secureTextEntry={secureTextEntry}
        autoCorrect={false}
        placeholder={placeHolder}
        style={inputStyle}
        onChangeText={onChangeText}
        value={value}
        underlineColorAndroid="transparent"
      />
    </View>
  );
};

See running example


text:
Q: Magento 2.3 How to show Out of Stock Products only in Search? My site is supposed to show out of stock products in some places in the catalogue, so the Catalog > Inventory > Display Out of Stock Products setting is set to "Yes."
But I do not want out of stock products to show up in the search. Before upgrading to M2.3, we accomplished this by overriding \Magento\CatalogInventory\Model\Plugin\Layer's  beforePrepareProductCollection() function:
 public function beforePrepareProductCollection(
        \Magento\Catalog\Model\Layer $subject,
        \Magento\Catalog\Model\ResourceModel\Collection\AbstractCollection $collection
    ) {

        $_category = $subject->getCurrentCategory();
        if (is_object($_category) and in_array($_category->getId(), array(161, 184)))// don't apply to Recently Sold, Our Archive categories
        {
            return;
        }

        parent::beforePrepareProductCollection($subject, $collection);
        $stockFlag = 'has_stock_status_filter';
        if (!$collection->hasFlag($stockFlag)) {
            $resource = $this->getStockStatusResource();
            $resource->addStockDataToCollection(
                $collection,
                true // force
            );
            $collection->setFlag($stockFlag, true);
        }
    }

    protected function getStockStatusResource()
    {
        if (empty($this->stockStatusResource)) {
            $this->stockStatusResource = $this->stockStatusFactory->create();
        }
        return $this->stockStatusResource;
    }

Now that Layer.php is gone in Magento 2.3, I don't know where to start with trying to hide out of stock products in search. I thought maybe I could use Magento\CatalogInventory\Model\Plugin\ProductSearch, but that isn't used at all as far as I can tell.

A: I solved this by adding the Layer plugin directly to my module Wfx_Stock which previously extended Layer.php
in di.xml:
<type name="Magento\Catalog\Model\Layer">
        <plugin name="addStockStatusOnPrepareFrontCollection" type="Wfx\Stock\Model\Plugin\Layer" sortOrder="1"/>
</type>

Then in app\code\Wfx\Stock\Model\Plugin\Layer.php
<?php
namespace Wfx\Stock\Model\Plugin;

class Layer
{

    /**
     * @param \Magento\CatalogInventory\Helper\Stock $stockHelper
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param StatusFactory $stockStatusFactory
     */
    public function __construct(
        \Magento\CatalogInventory\Helper\Stock $stockHelper,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\CatalogInventory\Model\ResourceModel\Stock\StatusFactory $stockStatusFactory
    ) {
        $this->stockStatusFactory  = $stockStatusFactory;
        $this->stockHelper = $stockHelper;
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * Before prepare product collection handler
     *  - Hide out of stock products in search, unless in "Recently Sold" or Our Archive
     *
     * @param \Magento\Catalog\Model\Layer $subject
     * @param \Magento\Catalog\Model\ResourceModel\Collection\AbstractCollection $collection
     *
     * @return void
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function beforePrepareProductCollection(
        \Magento\Catalog\Model\Layer $subject,
        \Magento\Catalog\Model\ResourceModel\Collection\AbstractCollection $collection
    ) {
        $_category = $subject->getCurrentCategory();
        if (is_object($_category) and in_array($_category->getId(), array(161, 184)))// Recently Sold, Our Archive
        {
            return;
        }

        $stockFlag = 'has_stock_status_filter';
        if (!$collection->hasFlag($stockFlag)) {
            $resource = $this->getStockStatusResource();
            $resource->addStockDataToCollection(
                $collection,
                true // force
            );
            $collection->setFlag($stockFlag, true);
        }
    }

    /**
     * Get config value for 'display out of stock' option
     *
     * @return bool
     */
    protected function _isEnabledShowOutOfStock()
    {
        return $this->scopeConfig->isSetFlag(
            'cataloginventory/options/show_out_of_stock',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * @return Status
     */
    protected function getStockStatusResource()
    {
        if (empty($this->stockStatusResource)) {
            $this->stockStatusResource = $this->stockStatusFactory->create();
        }
        return $this->stockStatusResource;
    }

}


text:
Q: Getting imageview inside ListView Adapter I made an adapter for a ListView where I can get the id and the name, but I can't get the image.
Here is some code samples:
private class MyCustomAdapter extends BaseAdapter {
    public ArrayList<Exercise> exercises ;

    public MyCustomAdapter(ArrayList<Exercise>  exercises) {
        this.exercises=exercises;
    }

    @Override
    public int getCount() {
        return exercises.size();
    }

    @Override
    public String getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater mInflater = getLayoutInflater();
        View myView = mInflater.inflate(R.layout.detail_item, null);

        final   Exercise s = exercises.get(position);

        TextView txtid=( TextView)myView.findViewById(R.id.tv_id);
        txtid.setText(""+s.id);

        TextView txtname=( TextView)myView.findViewById(R.id.tv_name);
        txtname.setText(s.name);

        ImageView img = (ImageView) myView.findViewById(R.id.img_id);
        img.setImageResource(s.img);

        return myView;
    }

}

The error is  here:

(ImageView img = (ImageView)
  myView.findViewById(R.id.img_id);
              img.setImageResource(s.img);)

The Exception:

:::  Process: com.example.simo.gym_programs, PID: 11826
                    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
                        at com.example.simo.gym_programs.Detail_Activity$MyCustomAdapter.getView(Detail_Activity.java:73)


text:
Q: How can I have one Docker container link to a postgres db in another Docker container? This is my docker-compose.yml:
version: '2'
services:
  postgres:
    image: "postgres:9.4"
    ports:
      - "5432:5432"

I use it to bring up the postgres db like this:
docker-compose up

Now I can connect to the db locally:
> psql postgres://postgres:postgres@docker-machine:5432
psql (9.6.4, server 9.4.13)
Type "help" for help.

postgres=#

My app is a Ruby/Sinatra app which connects to the postgres db.
When I start the app directly, using a bin/server script, the app boots up and connects to the db just fine.
This is how I build and run the dockerized app:
docker build -t my_app .

docker run \
  -p 3001:3001 \
  -e DATABASE_URI="postgres://postgres:postgres@docker-machine:5432" \
  my_app bin/server

When I run the app via Docker like this, it fails to connect to the db, and prints this error:
Sequel::DatabaseConnectionError: PG::ConnectionBad: could not connect to server: Connection refused
Is the server running on host "docker-machine" (127.0.0.1) and accepting
TCP/IP connections on port 5432?

How can I get my dockerized app to connect to the postgres db at the provided URI?

A: You could do one of the followings:

*

*Bring up both containers at the same time using the same docker-compose fil

*You could use a name server which will allow you to use a name for your DB container so that would be visible from inside your App container

*You could just use the DB container IP address, however, in case the DB container crashes and restarts it would have a different IP address which will make your App container brake.
Your App container tries to connect to localhost (inside the container itself) of course it cant because there's no Postgres running.

A: As the error states docker-machine isn't found. While this will work on the host as it wouldn't in the container. You could pass in the hostname as an environment variable like
docker run .. -e HOST_HOSTNAME=hostname ..
Then use that variable in your connection string

A: Docker Compose creates a user defined network by default for version 2+ compose files.
User defined networks come with an embedded DNS server that can respond for the local container names. In this case, the service name postgres will resolve to the IP of your database on the user defined network compose creates.
To connect your app to the same network, modify your existing compose file, or create a new compose file in the same directory with your apps details.
version: '2'
services:
  postgres:
    image: "postgres:9.4"
    ports:
      - "5432:5432"

  my_app:
    build: .
    image: my/app
    ports:
      - '3001:3001'
    environment:
      DATABASE_URI: 'postgres://postgres:postgres@postgres:5432'
    command: 'bin/server'

Then each containers IP will be available by its service name.


text:
Q: Json type mismatch my json data
 {"status":"true","c_id":"72","u_name":"navneet","dob":"2015-01-12","description":"login sucessful"}

code for parsing json data
try {
    Log.d("oooooooooooo",registerResponse);
    JSONObject responseObject = new JSONObject(registerResponse);
    Log.d("", "responseObjectresponseObject" + responseObject);
    Status = responseObject.getString("status");
    Log.d("", "StatusStatusStatus" + Status);
    res_Desp = responseObject.getString("description");
    Log.d("", "Status_DespStatus_DespStatus_Desp" + res_Desp);
} catch (Throwable t) {
    Log.e("zxxxxxxxxxx",
    "Error parsing response of change password web service - "
    + t.getMessage());
    t.printStackTrace();
    // return Boolean.FALSE;
}

errors are:
01-13 11:07:02.049  11363-11490/com.example.welcome.kids_chat D/oooooooooooo﹕ <script> function     abc(){if(window.location.href=="http://corouter.com/res/kidschat/login.php"){ window.location.assign('http://corouter.com/res/kidschat/login.php?username=&password='); }}</script><body onload="abc()"></body> {"status":"true","c_id":"72","u_name":"navneet","dob":"2015-01-12","description":"login sucessful"}
01-13 11:07:02.049  11363-11490/com.example.welcome.kids_chat E/zxxxxxxxxxx﹕ Error parsing response of change password web service - Value http of type java.lang.String cannot be converted to JSONObject
01-13 11:07:02.049  11363-11490/com.example.welcome.kids_chat W/System.err﹕ org.json.JSONException: Value http of type java.lang.String cannot be converted to JSONObject
01-13 11:07:02.059  11363-11490/com.example.welcome.kids_chat W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
01-13 11:07:02.059  11363-11490/com.example.welcome.kids_chat W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:159)
01-13 11:07:02.059  11363-11490/com.example.welcome.kids_chat W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:172)
01-13 11:07:02.059  11363-11490/com.example.welcome.kids_chat W/System.err﹕ at com.example.welcome.kids_chat.Login_Screen$loadslashscreenTask1.doInBackground(Login_Screen.java:162)
01-13 11:07:02.059  11363-11490/com.example.welcome.kids_chat W/System.err﹕ at com.example.welcome.kids_chat.Login_Screen$loadslashscreenTask1.doInBackground(Login_Screen.java:80)
01-13 11:07:02.059  11363-11490/com.example.welcome.kids_chat W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
01-13 11:07:02.059  11363-11490/com.example.welcome.kids_chat W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-13 11:07:02.059  11363-11490/com.example.welcome.kids_chat W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-13 11:07:02.059  11363-11490/com.example.welcome.kids_chat W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-13 11:07:02.059  11363-11490/com.example.welcome.kids_chat W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-13 11:07:02.059  11363-11490/com.example.welcome.kids_chat W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
01-13 11:07:02.079  11363-11363/com.example.welcome.kids_chat D/AndroidRuntime﹕ Shutting down VM

A: Yes Got your Problem You are not getting JSON response as response you are having all service in response see the first line of log cat.
Thats why you are unable to convert it to JSONObject. Edit your service and just return JSONObject from that.

A: The registerResponse is not having the value you specified above as JSON. You can see 'script' tag in the logs.
I guess you are by mistake loading an html or some web url which returns html content to get JSON. Your server should return the JSON as plain text without html tags.

A: Just checked your source code found some script and html. We strictly need "application/json" mimetype as a response from server.


text:
Q: gitlab-ci: Dynamic artifact names I am running a gitlab-ci job that will fetch locally a file from a remote server, more or less as follows:
retrieve_docs:
    stage: fetch_docs
    image: debian:jessie
    script:
      - ssh $USERNAME@$SERVER /perform/some/work
      - INSTFILE=$(ssh $USERNAME@$SERVER bash -c 'find /root -iname "somepattern*" | tail -n 1 | xargs readlink -f')
      - echo "Will retrieve locally $INSTFILE"
      - scp $USERNAME@$SERVER:$INSTFILE .
      - BASEFILE=$(basename $INSTFILE)
      - mv $BASEFILE downloads/
    artifacts:
      name: $BASEFILE
      paths:
        - downloads/

The above job definition however does not seem to work, as the BASEFILE variable is rendered as empty when providing the filename.

*

*Is there a way to use dynamic artifact name(s)?

*Is there a reason that this artifact is also never copied in my (empty/tracked) downloads folder?

*The above process will actually fetch a .zip file locally. Is there a way (although I have set expiration of 1 week) to have each job delete old artifacts and keep only the latest artifact / zip file?

A: For example if you use something like CI_JOB_ID CI_JOB_NAME you can have dynamic artifact names per JOB. You can have a combination of varibales defined in https://docs.gitlab.com/ee/ci/yaml/README.html#artifacts-name to get dynamic artifact names for your stage or job or pipeline.
Normally in a job, git lab compresses whatever specified in the path and upload it to the runner manager so that the next job can download the artifacts from the runner manager. If the job fails you cant upload any artifacts to other jobs. Do a find . and check wether the required dirs are there. You can use when option to continue the pipline no matter it fails or not. See https://docs.gitlab.com/ee/ci/yaml/README.html#artifacts-when
Yes you can expire the artifcat at your timers. See https://docs.gitlab.com/ee/ci/yaml/README.html#artifacts-expire_in


text:
Q: Storing canvas images in array I have multiple canvases with several layers on it. I need to store all generated images in an array and then display them on page.
var final_images = {};
var imageProcessing = function(source, images) {
for (var key in source) {

    switch(key){
        case "one":
        case "two":
        case "three":
        default:
            context.drawImage(images[key], 0, 0, 921, 680);
        case "top_layer":
            context.drawImage(images.top_layer, 0, 0, 921, 57);
        case "badge":
            context.drawImage(images.badge, 700, -20, 175, 175);
    }
}
}

Function for loading images.
function loadImages(source) {
var images = {};
var loadedImages = 0;
var numImages = 0;
// get num of sources
for (var src in source) {
    numImages++;
}
for (var src in source) {
    images[src] = new Image();
    images[src].onload = function () {
        if (++loadedImages >= numImages) {
            imageProcessing(source, images);
        }
    };
    images[src].src = source[src];
}
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

loadImages(source);

How can I combine all layers into one image and store it in an array?


text:
Q: Format DateTime.Now to yyyy-mm-dd I want to convert the DateTime.Now to the format of yyyy-mm-dd since that is the only format that i can use in my query that i want to include.
The default format of DateTime.Now looks like 5/1/2008 6:32:06 PM.
If i want to change the format of it to yyyyMMdd I could use this line of code:
var dateString1 = DateTime.Now.ToString("yyyyMMdd");

But, when i try the same for this yyyy-mm-dd format like below:
var dateString2 = DateTime.Now.ToString("yyyy-mm-dd");

the result i get is wrong.
For the following lines of code:
var dateString1 = DateTime.Now.ToString("yyyyMMdd");
var dateString2 = DateTime.Now.ToString("yyyy-mm-dd");

Console.WriteLine("yyyyMMdd " + dateString1);
Console.WriteLine("yyyy-mm-dd "+ dateString2);

I get the following result:

which is wrong for the second case.
What am i missing?

A: According to msdn MM format specifier stands for month and mm - for minutes.

"mm" | The minute, from 00 through 59.
"MM" | The month, from 01 through 12.

So your code should look like the following:
    var dateString1 = DateTime.Now.ToString("yyyyMMdd");
    var dateString2 = DateTime.Now.ToString("yyyy-MM-dd");

    Console.WriteLine("yyyyMMdd " + dateString1);
    Console.WriteLine("yyyy-MM-dd "+ dateString2);

And you will get the desired result

A: Your miss is lower-case "m" in second format, that determine MINUTES, but you need "M" instead of "m" for MONTHS.

A:     var dateString1 = DateTime.Now.ToString("yyyyMMdd");
    var dateString2 = DateTime.Now.ToString("yyyy-MM-dd");

    Console.WriteLine("yyyyMMdd " + dateString1);
    Console.WriteLine("yyyy-MM-dd "+ dateString2);

You are using "mm" instead of "MM" in your second format. mm is for minutes, MM is for month.