text:
Q: Global Max Pooling in Pytorch: RuntimeError: mat1 and mat2 shapes cannot be multiplied (128x2048 and 128x1024) In the model I'm building I'm trying to improve performance by replacing the Flatten layer with global max pooling.
To check that shapes are in order I ran a single random sample through the net:
test = torch.rand((1, 3, 224, 224))     # [N, C, H, W]

foo = nn.Sequential(
            nn.Conv2d(3, 32, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.BatchNorm2d(32),
            nn.Conv2d(32, 32, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.BatchNorm2d(32),
            nn.MaxPool2d(2)
        )

foo2 = nn.Sequential(
            nn.Conv2d(32, 64, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.BatchNorm2d(64),
            nn.Conv2d(64, 64, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.BatchNorm2d(64),
            nn.MaxPool2d(2)
        )

foo3 = nn.Sequential(
            nn.Conv2d(64, 128, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.BatchNorm2d(128),
            nn.Conv2d(128, 128, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.BatchNorm2d(128),
            nn.MaxPool2d(2)
        )

l1 = nn.Sequential(
            nn.Dropout(0.5),
            nn.Linear(128,  1024),
            nn.ReLU(),
            nn.Dropout(0.2),
            nn.Linear(1024, 10)
        )

r1 = foo(test)
print(r1.shape)    # torch.Size([1, 32, 112, 112])
r2 = foo2(r1)
print(r2.shape)    # torch.Size([1, 64, 56, 56])
r3 = foo3(r2)
print(r3.shape)    # torch.Size([1, 128, 28, 28])

# applying global max pooling and reshaping the layer to [N, C]
flat = F.adaptive_max_pool2d(r3, (1, 1))
ff = flat.reshape(flat.size(0), -1)

print(ff.shape)    # torch.Size([1, 128])
res = l1(ff)
print(res.shape)   # torch.Size([1, 10])

Here all seems to work as expected.
My model class has these same layers with the forward method like so:
    def forward(self, batch: torch.Tensor) -> torch.Tensor:
        r1 = self.conv1(batch)
        r2 = self.conv2(r1)
        r3 = self.conv3(r2)

        tmp = F.adaptive_max_pool2d(r3, (1, 1))
        flat = r3.view(tmp.size(0), -1)

        out = self.linear(flat)

        return out

Unfortunately, when I try to run the actual images through (Fashion MNIST dataset) I get the error: mat1 and mat2 shapes cannot be multiplied (128x2048 and 128x1024)
My batch size is 128 but I don't understand where 2048 might be coming from. None of my layers should output anything of that shape.
The full error message is as follows:
RuntimeError                              Traceback (most recent call last)
/root/fashion_mnist.ipynb Cell 7 in <cell line: 1>()
----> 1 runner.train_model(epochs=80, batch_size=128, criterion=loss_fn, optimizer=optim)

/root/fashion_mnist.ipynb Cell 7 in RunModel.train_model(self, epochs, batch_size, criterion, optimizer, device)
    113 t_ep = datetime.now()
    115 # run train routine
--> 116 train_loss, train_acc = self._run_train(train_loader, criterion, optimizer)
    117 self.train_losses[ep] = train_loss
    118 self.train_accuracies[ep] = train_acc

/root/fashion_mnist.ipynb Cell 7 in RunModel._run_train(self, train_data, criterion, optimizer)
    141 inputs, targets = inputs.cuda(), targets.cuda()
    142 optimizer.zero_grad()
--> 144 outputs: torch.Tensor = self.model(inputs)
    145 loss: torch.Tensor = criterion(outputs, targets)
    147 loss.backward()

File /opt/conda/lib/python3.8/site-packages/torch/nn/modules/module.py:1186, in Module._call_impl(self, *input, **kwargs)
   1182 # If we don't have any hooks, we want to skip the rest of the logic in
   1183 # this function, and just call forward.
   1184 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1185         or _global_forward_hooks or _global_forward_pre_hooks):
-> 1186     return forward_call(*input, **kwargs)
...
File /opt/conda/lib/python3.8/site-packages/torch/nn/modules/linear.py:114, in Linear.forward(self, input)
    113 def forward(self, input: Tensor) -> Tensor:
--> 114     return F.linear(input, self.weight, self.bias)

RuntimeError: mat1 and mat2 shapes cannot be multiplied (128x2048 and 128x1024)

Any ideas what's happening here?
The notebook is available here:
https://colab.research.google.com/drive/1QGpSpUCbuDz-dktmLCv_YpG6LZjYZ1TM?usp=sharing

A: Use Flatten() in the layers instead of view(). So your linear layer should look like this:
    self.linear = nn.Sequential(
        nn.Flatten(),
        nn.Dropout(0.5),
        nn.Linear(128,  1024),
        nn.ReLU(),
        nn.Dropout(0.2),
        nn.Linear(1024, 10)
    )

And your forward function look like:
def forward(self, batch: torch.Tensor) -> torch.Tensor:
    r1 = self.conv1(batch)
    r2 = self.conv2(r1)
    r3 = self.conv3(r2)

    tmp = F.adaptive_max_pool2d(r3, (1, 1))

    out = self.linear(tmp)

    return out

I have tested it on colab and it works fine.
Here is a summary output:
----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1           [-1, 32, 32, 32]             896
              ReLU-2           [-1, 32, 32, 32]               0
       BatchNorm2d-3           [-1, 32, 32, 32]              64
            Conv2d-4           [-1, 32, 32, 32]           9,248
              ReLU-5           [-1, 32, 32, 32]               0
       BatchNorm2d-6           [-1, 32, 32, 32]              64
         MaxPool2d-7           [-1, 32, 16, 16]               0
            Conv2d-8           [-1, 64, 16, 16]          18,496
              ReLU-9           [-1, 64, 16, 16]               0
      BatchNorm2d-10           [-1, 64, 16, 16]             128
           Conv2d-11           [-1, 64, 16, 16]          36,928
             ReLU-12           [-1, 64, 16, 16]               0
      BatchNorm2d-13           [-1, 64, 16, 16]             128
        MaxPool2d-14             [-1, 64, 8, 8]               0
           Conv2d-15            [-1, 128, 8, 8]          73,856
             ReLU-16            [-1, 128, 8, 8]               0
      BatchNorm2d-17            [-1, 128, 8, 8]             256
           Conv2d-18            [-1, 128, 8, 8]         147,584
             ReLU-19            [-1, 128, 8, 8]               0
      BatchNorm2d-20            [-1, 128, 8, 8]             256
        MaxPool2d-21            [-1, 128, 4, 4]               0
          Flatten-22                  [-1, 128]               0
          Dropout-23                  [-1, 128]               0
           Linear-24                 [-1, 1024]         132,096
             ReLU-25                 [-1, 1024]               0
          Dropout-26                 [-1, 1024]               0
           Linear-27                   [-1, 10]          10,250
================================================================
Total params: 430,250
Trainable params: 430,250
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.01
Forward/backward pass size (MB): 2.76
Params size (MB): 1.64
Estimated Total Size (MB): 4.41
----------------------------------------------------------------

Trainer Output:
Epoch 1/80 completed in 0:00:32.994402. Train_loss:  1.0680, train accuracy:  0.6225 Test loss:  1.0435, test accuracy:  0.6271
Epoch 2/80 completed in 0:00:32.939861. Train_loss:  0.9726, train accuracy:  0.6578 Test loss:  0.9616, test accuracy:  0.6662
Epoch 3/80 completed in 0:00:32.811203. Train_loss:  0.9015, train accuracy:  0.6851 Test loss:  0.9015, test accuracy:  0.6883
Epoch 4/80 completed in 0:00:32.836747. Train_loss:  0.8361, train accuracy:  0.7119 Test loss:  0.8336, test accuracy:  0.7173


text:
Q: How to calculate the overlap significance between two gene list in R This was my question suggested me to ask here.
I have two gene sets from coming from expression and accessible region. So I have to compare the degree of overlap between these two sets.
RNA_seq_cds <- read.csv("~/Downloads/RNA_seq_gene_set.txt", header=TRUE, sep="\t")
head(RNA_seq_cds)
ATAC_seq <- read.csv("~/Downloads/ATAC_seq_gene_set.txt", header=TRUE, sep="\t")
head(ATAC_seq)
RNA_seq <- RNA_seq_cds
ATAC_seq <- ATAC_seq

My  data files for the two sets.
I read in this paper " P values calculated using a hypergeometric probability test."
How can I do the same in R.Suggestion or help would be really appreciated
My original question where i was suggested to ask my question here how to perform the test.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does Requests raise this SSLError when trying to access Twitter's API? I am attempting to use rauth to do oauth with twitter, but it seems to be failing with the following error:
requests.exceptions.SSLError: [Errno 1] _ssl.c:504: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

After some testing, I find that requests seems to be breaking when attempting to access api.twitter.com and verifying the https connection.  Here is an example, It appears to work for https://github.com, but fails for https://api.twitter.com:
>>> import requests
>>> requests.get('https://github.com', verify=True)
<Response [200]>
>>> requests.get('https://api.twitter.com/oauth/request_token',verify=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/api.py", line 65, in get
    return request('get', url, **kwargs)
  File "requests/safe_mode.py", line 39, in wrapped
    return function(method, url, **kwargs)
  File "requests/api.py", line 51, in request
    return session.request(method=method, url=url, **kwargs)
  File "requests/sessions.py", line 252, in request
    r.send(prefetch=prefetch)
  File "requests/models.py", line 632, in send
    raise SSLError(e)
requests.exceptions.SSLError: [Errno 1] _ssl.c:504: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
>>> requests.get('https://api.twitter.com',verify=True)
[SNIP] Same error as above

Is this a bug in requests?  This should be similar to what rauth is running, so I am not sure why it is not working on my machine.
With some great disccusion from @thomas-orozco it appears to be an openssl being unable to verify the G2 VeriSign certificate: http://pastebin.com/ZZj3s5uN
It does appear that I have the VeriSign CA by using certool:
certtool y k=/System/Library/Keychains/SystemCACertificates.keychain | grep -i verisign

Which is being used by chrome / safari, just not by openssl on the command line.  Is there something that I can do so that Requests will load the right certificate?

A: I gave this a shot with rauth 0.5.3 and Requests 1.1.0; for reference, I'm on a fresh install of OS X 10.8.3. It seems to be working as expected. Here's the example script I used:
from rauth import OAuth1Service

# Get a real consumer key & secret from https://dev.twitter.com/apps/new
twitter = OAuth1Service(
    name='twitter',
    consumer_key='J8MoJG4bQ9gcmGh8H7XhMg',
    consumer_secret='7WAscbSy65GmiVOvMU5EBYn5z80fhQkcFWSLMJJu4',
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    base_url='https://api.twitter.com/1/')

request_token, request_token_secret = twitter.get_request_token(verify=True)

authorize_url = twitter.get_authorize_url(request_token)

print 'Visit this URL in your browser: ' + authorize_url
pin = raw_input('Enter PIN from browser: ')

session = twitter.get_auth_session(request_token,
                                   request_token_secret,
                                   method='POST',
                                   data={'oauth_verifier': pin},
                                   verify=True)

params = {'include_rts': 1,  # Include retweets
          'count': 10}       # 10 tweets

r = session.get('statuses/home_timeline.json', params=params, verify=True)

for i, tweet in enumerate(r.json(), 1):
    handle = tweet['user']['screen_name'].encode('utf-8')
    text = tweet['text'].encode('utf-8')
    print '{0}. @{1} - {2}'.format(i, handle, text)

My advice is to try updating, if you can, and see what results that yields. I suspect that the underlying updates to urllib3 with help remedy this situation. Please note that in order to use rauth with > Requests 1.0.0 you must be using rauth 0.5.x; older version are not compatible with Requests 1.0.0 API changes.


text:
Q: Cannot call value of non-function type 'AnyObject!?" Swift I'm trying to fix this error but no see solution.
In other codes that works! No sense!
Support Class ScrolledString: print string in a view that is scrolled.
class ScrolledString: NSView{
var text: NSString = "";

init(frame frameRect: NSRect, string:NSString){
    self.text = string
    super.init(frame: frameRect)
}

required init?(coder: NSCoder) {
    self.text = ""
    super.init(coder:coder)
}

override func drawRect(dirtyRect: NSRect) {
    let font = NSFont(name: "Helvetica", size: 40.0)
    let attrs : [String: AnyObject] = [
        NSFontAttributeName: font!,
        NSForegroundColorAttributeName: NSColor.whiteColor()
    ]
    text.drawInRect(self.frame, withAttributes: attrs)
}

Than in mainView I'm trying to add a ScrollView
let scrollStringContainer = NSScrollView(frame: NSRect(x: myRect.width*4/9, y: 0, width: myRect.width*8/9, height: myRect.height))
let view = NSView()
view.addSubview(ScrolledString(frame: scrollStringContainer.frame, string: self.name))
scrollStringContainer.documentView(view)

Last line return error "Cannot call value of nun-function type 'AnyObject'". I'm simply trying to add a view to scrollView

A:
unowned(unsafe) var documentView: AnyObject?

documentView is an optional property of type AnyObject, so you can't call it like a function. I'm not clear if you mean to be using contentView, as in:
scrollStringContainer.contentView.addSubview(view)


text:
Q: Anybody have/know of a delta star transform algorithm/code? Do you guys know any delta star code/program. I would do it myself but I don't have enough time, and it would be a good way to let other people know your work.
Complex impedances pleas

A: It's a basic transformation that is documented e.g. in wikipedia. See attached screenshot.

Please, note also that it is written that you ca replace complex "objects" (impedance, admittance) to resistance terms.


text:
Q: Next.js webhook returns a 301 (redirect) instead of 200 I have a Next.js app and I created an endpoint to handle a webhook from a third-party payment application.
The code for that endpoint is very simple, it checks that the order was paid and updates my database:
export default async function WebhookHandler(req, res) {
    if (req.method === 'POST') {
    const requestData = JSON.parse(req)

        if (requestData.status === "paid") {
            // Code to update database
    }

        res.status(200).json({ received: true });
    } else {
        res.setHeader('Allow', 'POST');
        res.status(405).end('Method not allowed.');
    }
}

The problem is that this webhook is falling. When I go to my payment application logs, I can see the webhook requests are going to the right endpoint, but my endpoint response is a 301 (redirect) and the payment application expects a 200.
Any ideas why Next.js is creating this redirect? I don't even know where to look for this...

A: After a lot of digging, I found that it was my server configuration. It was redirecting my www.site.com to site.com ♂


text:
Q: Json to html table. Cannot parse to table heading because json object's field name starts with capital? I am trying to use Dynatable library to convert json objects to html table.
PS: This problem also persists for other library such as DataTable
However, currently my entire table's cell value is undefined.
Here is my sample Json data
[
   {"Adult":2,"Child":1},
   {"Adult":3,"Child":2},
   {"Adult":4,"Child":1}
]

And here is my HTML table

            Adult
            Child

And here is the javascript code
$(document).ready(function () {
    $.ajax({
        type: 'GET',
        url: 'http://localhost:51071/api/Foo',
        success: function (response) {
            console.log(response);
            $("#myTable").dynatable({
                dataset: {
                    records: response
                }
            });
        },
        dataType: 'json'
    });
});

Any particular reason why I am getting undefined value?
In their documentation for converting attribute names they mention default naming convention to be camelcase and example given was favoriteMusic.
Are they expecting my field name to start with small letter?
Update 1:
Turns out it is because the field names start with capital letter.
I changed my json data to following and it worked
[
   {"adult":2,"child":1},
   {"adult":3,"child":2},
   {"adult":4,"child":1}
]

Any idea for a work around to make it work with field name starting with capital letter?

A: This is what I ended up doing
    function firstLetterLowerCase(str) {
        return str.charAt(0).toLowerCase() + str.substr(1);
    }
    $(document).ready(function () {

        $.ajax({
            type: 'GET',
            url: 'http://localhost:51071/api/Foo',
            success: function (response) {

                response = response.map(function(resObj) {
                    var obj = {};
                    for (key in resObj) {
                        if (resObj.hasOwnProperty(key)) {
                            obj[firstLetterLowerCase(key)] = resObj[key];
                        }
                    }
                    return obj;
                });
                $("#myTable").dynatable({
                    dataset: {
                        records:response
                    }
                });                },
            dataType: 'json'
        });
    });

So basically wrote a function to convert first letter of json object's field name from capital to small.
This might not be as performant when number of entries are huge.


text:
Q: Can I put a workflow or or build a process builder flow around the GroupMember object? I am trying to send an email to a single person every time someone gets added to or is removed from a Public Group. Can I do this via standard workflow or using the process builder?
If no, can this be done using a trigger? Want to avoid writing a trigger if there is an easier solution!


text:
Q: resource efficient join and filter method I have the following condensed data set:
tbl1 <- data.frame(Name = c(rep("A",3), rep("B",2), rep("C",3)), Dat = c(1,1,2,1,1,3,4,4),
                   Var1 = sample(1:8,8), Var2 = sample(1:8,8))

tbl2 <- data.frame(Name = c("A","A","B","C","C"), Dat = c(1,2,1,3,4), x = c("a","b","b","b","a"))

I need to filter from tbl1 all data sets with the condition x, found in table tbl2. This is my current solution.
tbl11 <- tbl1 %>% mutate(key = paste(Name, Dat, sep = "_"))
tbl2 <- tbl2 %>% mutate(key = paste(Name, Dat, sep = "_"))

tbl3 <- left_join(tbl11, tbl2)
tbl4 <- tbl3 %>% filter(x == "a")

Unfortunately I run into resource issues. For small tables it works. I think there are more efficient way so that I don't have to store the intermediate steps. Your help is much appreciated.

A: You can subset the data before joining :
tbl4 <- merge(tbl1, subset(tbl2, x == 'a'), by = c('Name', 'Dat'))

A: Thanks for sharing your ideas. Just for completeness, I have tested the suggested and came up with a correct and more efficient way:
tbl3 <- inner_join(filter(tbl2, x == 'a'), tbl1, by = c('Name', 'Dat'))

Inner_join is significantly faster than merge. And the order of the input is important of course.


text:
Q: Existence of a map connecting two marginals of a product measure Let $X$ and $\bar X$ be two standard Borel spaces, and let $A\subseteq X\times\bar X$ be an analytic subset of the product space. Let $P$ be any probability measure such that $P(A) = 1$, and denote by $p$ and $\bar p$ marginals of $P$ on $X$ and $\bar X$ respectively. Does there exist a universally measurable map $f:X\to \bar X$ such that $\bar p = p\circ f^{-1}$ and such that the graph of $f$ is contained in $A$?

A: No.  The measures $p, \bar{p}$ could be almost anything; there's nothing in the given conditions that forces $\bar{p}$ to be a possible pushforward of $p$.
As an extreme example, take $X = \{0\}$ to be a singleton, $\bar{X} = [0,1]$, $A = X \times \bar{X}$, $P= \delta_0 \times m$ where $m$ is Lebesgue measure on $[0,1]$.  Then $p = \delta_0$, $\bar{p} = m$, but for any $f : X \to \bar{X}$, $p \circ f^{-1}$ can only be a point mass at $f(0)$.


text:
Q: How to use a model field for multiple models in Django Rest Framework I have a model BstUserActionLog with a foreign key to Django model User. I have another model for user profile information, BstUserProfile. When I do serialize BstUserActionLog with ModelSerializer I do have Django User info serialized as it is supposed to be. But I also need to add BstUserProfile serialized using the same user_id used for User model.
How can I serialize BstUserActionLog with model User and BstUserProfile are both serialized?
From my models.py:
class BstUserActionLog(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User)
    bst_action_type = models.ForeignKey(BstActionType)
    action_date = models.DateTimeField(auto_now_add=True)
    bst_book = models.ForeignKey(BstBook)
    new_value_id = models.IntegerField(blank=True, null=True)
    old_value_id = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'bst_user_action_log'

class BstUserProfile(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User, unique=True)
    website = models.CharField(max_length=200)
    picture = models.CharField(max_length=100)
    is_avatar_uploaded = models.BooleanField(default=False)
    is_cover_uploaded = models.BooleanField(default=False)

    class Meta:
        managed = False
        db_table = 'bst_user_profile'
        app_label = 'bst'

From my serializers.py:
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id','username',)

class BstUserActionLogSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = BstUserActionLog
        fields = ('id', 'user', 'bst_action_type', 'action_date', 'bst_book', 'new_value_id', 'old_value_id')
        depth = 3

A: The key to my solution is SerializerMethodField. With this a new field can be added which is calculated with a method. This method signature contains the object to be serialized. After that a regular method serializer is used to return the serialized object.
From my serializers.py
class BstUserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = BstUserProfile
        fields = ('is_avatar_uploaded', 'is_cover_uploaded')

class BstUserActionLogSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    user_profile = serializers.SerializerMethodField()

    def get_user_profile(self, obj):
        try:
            user_profile = BstUserProfile.objects.get(user_id=obj.user_id)
            return BstUserProfileSerializer(user_profile).data
        except Exception as e:
            return {}

    class Meta:
        model = BstUserActionLog
        fields = ('id', 'user', 'user_profile', 'bst_action_type', 'action_date', 'bst_book', 'new_value_id', 'old_value_id')
        depth = 3


text:
Q: How to compute geo distance between all pairs of objects in MongoDb I have setup one MongoDb (3.4) collection of N points with a 2DSphere index based on the 2D coordinates (ra, dec).
I want all the distances between all pairs of those objects
p1 = {ra1, dec1}
p2 = {ra2, dec2}
..
pn = {ran, decn}
=> d11 = 0, d12 = d(p1, p2), d13 = d(p1, p3), ... dnn = 0
How to construct the Mongo aggregation to obtain this?
Then I will sort this result, or select distances lower then some value in order to obtain the neighbours of each point.
Thanks for any hint


text:
Q: How to handle string data characters that are illegal in XML? Consider this web service implemented in Java:
@WebMethod(operationName = "test1")
@WebResult(name = "test1", targetNamespace = "http://test.example.org/")
public String test1()
{
    return "foo\u0000bar"; // "foo" + NUL + "bar"
}

Using (versions 2.5.10 and 2.7.18 of) apache CXF, this will return (SOAP envelope omitted):
<ns2:test1>foo[NULL byte here]bar</ns2:test1>

Which is invalid XML.
Do other web service libraries handle the NULL (and other characters that are invalid in XML) differently? What is the correct standard handling?

A: The ideal is to have some XML mechanism for whatever the control character is meant to do.
If that isn't possible, or if you need to send non-characters for some reason (almost always a sign of a very bad idea, but you might have to deal with someone else's bad idea) then it's best sent as base-64 encoded or some other way of wrapping non-textual data in text.

A: Standard ways for handling XML content that would be invalid in XML is to use CDATA section(s) or base64-encoded values (preferably with base64Binary data type).


text:
Q: Cron does not run shell script properly im having the problem that a bash script is not running from cron. When i instead run it as root from the cli it works well. As you can see i write to a txt file when the script has finished. This is also done when the script runs from cron, only the Oracle dmp is not saved (and obviously not zipped). The job is done extremely quick, so i guess it does not do the oracle export...
Thank you for you help!
backup.sh
#!/bin/bash
#makes an Oracle  backup and zips the created file
TIME=`date +%F_%H:%M:%S`
FILENAME=Backup-$TIME

exp userid=user/password file=/home/user/DatabaseBackup/$FILENAME.dmp
zip /home/user/DatabaseBackup/$FILENAME.zip /home/user/DatabaseBackup/$FILENAME$
find /home/user/DatabaseBackup/ -mtime +0 -type f -delete

echo "Backup completed:" `date +%F_%H:%M:%S` >> /home/user/scripts/logBackup.txt
#END

crontab -e
26 * * * * /home/user/scripts/backup.sh

A: Ok, what i did is:
I added
>> /home/user/cron.txt 2>&1

this to my cronjob declaration, wiht this i have now the output of the cornjob.
With this it was easy to find out that some evironmet variables for oracle were missing...
Thanks for any help provided!


text:
Q: Wordpress add_rewrite_rule gives 404 I want to change the permalink structure for specific custom post type.i.e
http://test.com/brand/calvin-klien?mtype=tab2
                     ^this is dynamic

To
http://test.com/brand/calvin-klien/mtype/tab2
                      ^this is dynamic

Here is a piece of code I tried.
Registering add_rewrite_tag
function custom_rewrite_tag() {
        add_rewrite_tag('%mtype%', '([a-z0-9\-]+)');
    }
    add_action('init', 'custom_rewrite_tag', 10, 0);

add_action('init', 'wpse50530_journal_archive_rewrite', 10, 0);

Code1
function wpse50530_journal_archive_rewrite(){

   add_rewrite_rule('brand/([a-z0-9\-]+)/([a-z0-9\-]+)/$','index.php?name=$matches[1]/?mtype=$matches[2]','top');
}

Code2
add_action('generate_rewrite_rules', 'work_list');
function work_list($wp_rewrite) {
    $newrules = array();
    $newrules['brand/([a-z0-9\-]+)/([a-z0-9\-]+)/$'] = 'index.php?name=$matches[1]&mtype=$matches[2]';
    $wp_rewrite->rules = $newrules + $wp_rewrite->rules;

I have tried both above codes, flushed permalinks but still a 404. I dont know why it is creating $matches in htaccess as htacces doesnt know WHAT IS $matches
Also I have tried monkeyman-rewrite-analyzer plugin which is showing the correct matched result for my permalink but still word press showing 404. See attached screenshots for Code1 & Code2

A: The following code should help
add_action( 'init', 'so_27487849' );

function so_27487849() {

    add_rewrite_rule(
        '^brand/([^/]*)/mtype/([^/]*)/?',
        'index.php?name=$matches[1]&mtype=$matches[2]',
        'top');

}

Flush your permalinks and it should work.

A: I will continue Anand's code for some further changes. It was redirecting on name=$matches[1] and I need to stay at the same URL I hit, for this it must include the custom post type name.
add_action( 'init', 'so_27487849' );
function so_27487849() {
    add_rewrite_rule('^brand/([^/]*)/([^/]*)/?','index.php?brand=$matches[1]&mtype=$matches[2]','top');
                                                             ^--this
}

I got the Pretty URL... Yaaay!!!
BUT URL doesn't contain query string(i.e: mtype=tab1) and the rest of my code is useless, so we can achieve this by doing get_query_var('mtype') and I got the same value which was working in $_REQUEST['mtype'] and my code worked like a charm.
Also I deactivated the monkeyman pluggin

A: Just in case anyone has the same problem and checks out this page.
In the permalink settings page, check how the permalink structure is configured. The most common is to enter /%postname%/ in the custom structure field to let the rewrite_rules work properly.

A: before or after the call the function add_rewrite.. insert this code status_header(200);


text:
Q: Cannot source tmux config file in a Dockerfile I'm building a Docker image where I need tmux, and rather than having to run tmux source-file ~/.tmux.conf every time I start the container (that way madness lies), I'd like to source the config file at build time. However, this isn't working:
ARG PYTORCH="1.6.0"
ARG CUDA="10.1"
ARG CUDNN="7"

FROM pytorch/pytorch:${PYTORCH}-cuda${CUDA}-cudnn${CUDNN}-devel

RUN apt-get update && apt-get install -y man-db manpages-posix vim screen tmux\
  && apt-get clean \
  && rm -rf /var/lib/apt/lists/*
# configuration for tmux
COPY src/.tmux.conf ~/.tmux.conf
RUN tmux source-file ~/.tmux.conf

I get the error:
error connecting to /tmp/tmux-0/default (No such file or directory)
The command '/bin/sh -c tmux source-file ~/.tmux.conf' returned a non-zero code: 1

What's happening? It doesn't seem to be a file not found error.

A: There's no tmux server running (no server at all has been running yet, hence the missing file). The config file will be loaded automatically when you run tmux in the container, so the failing line can be dropped
Also, docker doesn't expand the ~, so you'll need to provide the absolute path. The resulting Dockerfile should look something like this, assuming you're running as root in the container:
ARG PYTORCH="1.6.0"
ARG CUDA="10.1"
ARG CUDNN="7"

FROM pytorch/pytorch:${PYTORCH}-cuda${CUDA}-cudnn${CUDNN}-devel

RUN apt-get update && apt-get install -y man-db manpages-posix vim screen tmux\
  && apt-get clean \
  && rm -rf /var/lib/apt/lists/*
# configuration for tmux
COPY src/.tmux.conf /root/.tmux.conf


text:
Q: how to change proxy every 5min by extension automatically? How to use proxy extension to change proxy after sometimes in selenium python ?
Currently I am using this code to add proxy by the help of an extension.But now need to modify this to change proxy after sometimes multiple time.I want to convert this extension code to sometihing like "Proxy Switcher ".
manifest_json = """
    {
        "version": "1.0.0",
        "manifest_version": 2,
        "name": "Chrome Proxy",
        "permissions": [
            "proxy",
            "tabs",
            "unlimitedStorage",
            "storage",
            "<all_urls>",
            "webRequest",
            "webRequestBlocking"
        ],
        "background": {"scripts": ["background.js"]},
        "minimum_chrome_version": "76.0.0"
    }"""
background_js = """
var config = {
    mode: "fixed_servers",
    rules: {
        singleProxy: {
            scheme: "http",
            host: "%s",
            port: %d
        },
        bypassList: ["localhost"]
    }
};

chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});

function callbackFn(details) {
    return {
        authCredentials: {
            username: "%s",
            password: "%s"
        }
    };
}

chrome.webRequest.onAuthRequired.addListener(
    callbackFn,
    { urls: ["<all_urls>"] },
    ['blocking']
);
"""

A: Just use a loop like this:
arr = array('proxy1', 'proxy2')
for (element in arr):
    proxyip = element


text:
Q: How do I get MVCSiteMap to include all my custom route I want to use the route attribute defined in my C# files for create the xml site map (MVCSiteMap) file like this:
[RoutePrefix("{culture}/Registration/Person")]
public partial class PersonController : BaseController
{
   [HttpPost]
   [Route("Step1")]
   public ActionResult StartStep1() {}
}

and create an xml file like this:
 <mvcSiteMapNode title="Registration" controller="Person" action="Index" >
  <mvcSiteMapNode title="Registration Person" route="Step1" controller="Person" action="Index" />
</mvcSiteMapNode>

But route attribute is ignored and the result was:
Additional information: A route named 'Step1' could not be found in the route collection.

My web.config file is configured like this:
 <add key="MvcSiteMapProvider_IncludeRootNodeFromSiteMapFile" value="true" />
<add key="MvcSiteMapProvider_AttributesToIgnore" value="" />
<add key="MvcSiteMapProvider_CacheDuration" value="5" />
<add key="MvcSiteMapProvider_UseExternalDIContainer" value="false" />
<add key="MvcSiteMapProvider_ScanAssembliesForSiteMapNodes" value="true" />

A:
I want to use the route attribute defined in my C# files for create the xml site map (MVCSiteMap) file

You can't.
The purpose of nodes is to define a parent-child relationship between different controller actions. Route attributes do not provide a way to do this, so there is no way to automatically include every possible match for a route in a .sitemap file or define the hierarchy.
You must provide a node configuration to fill in the missing piece that MVC does not provide. You can provide the node configuration one of 4 ways:

*

*.sitemap XML file

*MvcSiteMapNodeAttribute

*Dynamic Node Providers

*Implement ISiteMapNodeProvider and inject your implementation using external DI (see this answer for details)

I think that the option that is most similar to what you want is to use MvcSiteMapNodeAttribute.
[RoutePrefix("{culture}/Registration/Person")]
public partial class PersonController : BaseController
{
    // NOTE: This assumes you have defined a node on your
    // Home/Index action with a key "HomeKey"
    [MvcSiteMapNode(Title = "Registration",
        Key = "RegistrationKey", ParentKey = "HomeKey")]
    public ActionResult Index() {}

    [HttpPost]
    [Route("Step1")]
    [MvcSiteMapNode(Title = "Registration Person",
        Key = "RegistrationPersonKey", ParentKey = "RegistrationKey")]
    public ActionResult StartStep1() {}
}

Additional information: A route named 'Step1' could not be found in the route collection.

The route attribute is to identify a registered route by name, not by URL. So to make your configuration work, you would need to name your route.
[Route("Step1", Name = "TheRouteName")]

And then use the same name in your node configuration.
<mvcSiteMapNode title="Registration Person" route="TheRouteName" controller="Person" action="Index" />


text:
Q: Failed to fetch Error - How do I send an axios response in Polka? I try to fetch login datas in a Svelte/Sapper app as in the code below and I use polka and axios for the api request on the server.
I don't understand the behaviour in the axios call. The console.log(JSON.stringify(result.data)) logs the correct result as I expected. But the fetch request on the client throws this exception:

Error: Failed to fetch

Can anyone explain me what I do wrong?
//client
try {
      const res = await fetch("login.json", {
        method: "POST",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({ user: email, passw: password }),
      });
      let result = await res.json();

      if (!res) {
        throw new Error(result.error);
      }else{
        console.log("result: "+JSON.stringify(result));
      }
    } catch (e) {
      error = e.message;
      console.log("Error: "+error); //Error: Failed to fetch
    }
  }

//server
export async function post(req, res) {
    const password = sha3_512(req.body.password);
    const qs = require('qs');
    const data = qs.stringify({ user: req.body.user, password: password })
    const config = {
        method: 'post',
        url: 'https://****login',
        httpsAgent: agent,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: data
    }

    axios(config)
    .then(result => {
        console.log(JSON.stringify(result.data));//successful response
        res.end(JSON.stringify(result.data));
    })
    .catch(err => res.end(err));
}

A: The problem is solved after add preventDefault in the form element.
 <form on:submit|preventDefault={() => submit()}>


text:
Q: ERROR 1215 (HY000): Cannot add foreign key constraint, I've checked for syntax and spelling errors I am getting a ERROR 1215 (HY000): Cannot add foreign key constraint error with:
Foreign Key (locationID) references Location (locationID). When I comment it out the query goes through with no problem
I can't seem to find the problem I have checked for spelling errors, notepad++ highlights "Location" and "locationID" on both statements. They are also both varchar(3).
create table Location
(
    warehouseID varchar(3),
    locationID varchar(3),
    Aisle int,
    Shelf int,
    Bin int,
    capacity Double,
    Primary Key (warehouseID,locationID),
    Foreign Key (warehouseID) references Warehouse(warehouseID)
) Engine = InnoDB;

create table Prod_Location
(
    warehouseID varchar(3),
    locationID varchar(3),
    productNum int,
    quantityOnHand int,
    Foreign Key (warehouseID) references Warehouse(warehouseID),
    Foreign Key (productNum) references Product(productNum),
    Foreign Key (locationID) references Location(locationID),
    Primary Key (warehouseID, locationID, productNum)
) Engine = InnoDB;

Thank you.
Edit:
Full code
create database WareMart30119267;
use WareMart30119267;

create table Department (
    dptNumber int Auto_Increment,
    dptName varchar(20),
    Primary Key (dptNumber))
    Engine = InnoDB;

create table Product (
    productNum int Auto_Increment,
    description varchar(30),
    packSize int,
    Price Decimal(10,2),
    dptNumber int,
    Primary Key (productNum),
    Foreign Key (dptNumber) references Department(dptNumber))
    Engine = InnoDB;

create table CLient (
    clientNum int Auto_Increment,
    clientName varchar(40),
    Primary Key (clientNum))
    Engine = InnoDB;

create table Client_Address (
    clientNum int Auto_Increment,
    addressType varchar(1),
    street varchar(20),
    city varchar(3),
    state varchar(3),
    postcode varchar(4),
    Primary Key (clientNum, addressType),
    Foreign Key (clientNum) references Client(clientNum))
    Engine = InnoDB;

create table Stock_Request (
    requestNum int Auto_Increment,
    requestDate date,
    clientNum int,
    Primary Key (requestNum),
    Foreign Key (clientNum) references Client(clientNum))
    Engine = InnoDB;

create table Request_List (
    requestNum int,
    productNum int,
    qtyRequested int,
    Primary Key (requestNum, productNum),
    Foreign Key (requestNum) references Stock_Request(requestNum),
    Foreign Key (productNum) references Product(productNum))
    Engine = InnoDB;

create table Warehouse (
    warehouseID varchar(3),
    street varchar(20),
    city varchar(15),
    state varchar(3),
    postcode varchar(4),
    managerID int,
    Primary Key (warehouseID))
    Engine = InnoDB;

create table Location (
    warehouseID varchar(3),
    locationID varchar(3),
    Aisle int,
    Shelf int,
    Bin int,
    capacity Double,
    Primary Key (warehouseID, locationID),
    Foreign Key (warehouseID) references Warehouse(warehouseID))
    Engine = InnoDB;

create table Employee (
    staffID int Auto_Increment,
    surname varchar(20),
    firstName varchar(15),
    dob date,
    street varchar(20),
    city varchar(15),
    state varchar(3),
    postcode varchar(4),
    salary Decimal(19,4),
    warehouseID varchar(3),
    supervisedBy int,
    Primary Key (staffID),
    Foreign Key (supervisedBy) references Employee(staffID))
    Engine = InnoDB;
/*Add Foreign Keys to Warehouse and Employee */

alter table Warehouse
    add Foreign Key (managerID) references Employee(staffID);

alter table Employee
    add Foreign Key (warehouseID) references Warehouse(warehouseID);

create table Prod_Location (
    warehouseID varchar(3),
    locationID varchar(3),
    productNum int,
    quantityOnHand int,
    Foreign Key (warehouseID) references Warehouse(warehouseID),
    Foreign Key (productNum) references Product(productNum),
    Foreign Key (locationID) references Location(locationID),
    Primary Key (warehouseID,locationID,productNum))
    Engine = InnoDB;

create table Picking_List (
    warehouseID varchar(3),
    locationID varchar(3),
    productNum int,
    requestNum int,
    quantityPicked int,
    datePicked date,
    pickerStaffID int,
    Primary Key (warehouseID, locationID, productNum, requestNum),
    /* Foreign Key (warehouseID) references Warehouse(warehouseID), */
    Foreign Key (locationID, warehouseID) references Location(locationID, warehouseID),
    Foreign Key (productNum) references Product(productNum),
    Foreign Key (requestNum) references Stock_Request(requestNum))
    Engine = InnoDB;

I feel stupid now, the answer was to move warehouseID and locationID in the primary key so it was like this
create table Location (
warehouseID varchar(3),
locationID varchar(3),
Aisle int,
Shelf int,
Bin int,
capacity Double,
Primary Key (locationID, warehouseID),
Foreign Key (warehouseID) references Warehouse(warehouseID))
Engine = InnoDB;

I don't know why the order made a difference but it fixed the error.

A: Your primary key on location is defined as the composite key:
Primary Key (warehouseID,locationID),

Whereas you are trying to reference this in Prod_Location as a foreign key via just one of its components:
Foreign Key (locationID) references Location(locationID)

You'll need to change the foreign key to be composite with all fields of the referenced key:
Foreign Key (warehouseID, locationID) references Location(warehouseID, locationID)

Or, alternatively, change the primary key of Location to be simple, e.g. just locationID
Edit After the full schema posted
My apologies - the order of the composite keys is important - you'll need to keep the same order of the primary key definition in the foreign key references, viz (warehouseID, locationID).
This also needs to be done for the composite foreign key to Location in Picking_List.
Also, since clientNum is a foreign key in table Client_Address back to client, it itself should not be declared as Auto_Increment, since it must stay in synch with Client and be explicitly assigned in code.
One of the common problems with composite foreign keys is the temptation to reference and join to the ultimate component key tables directly, instead of to the link table via the composite keys. I believe that the direct relationship between Prod_Location and warehouseId via Foreign Key (warehouseID) references Warehouse(warehouseID) may be an example of this.
SqlFiddle here

A: Remove Primary key from Pro_Location Table:
create table Location (
    warehouseID varchar(3),
    locationID varchar(3),
    Aisle int,
    Shelf int,
    Bin int,
    capacity Double,
    Primary Key (warehouseID,locationID),
    Foreign Key (warehouseID) references Warehouse(warehouseID))
    Engine = InnoDB;

create table Prod_Location (
    warehouseID varchar(3),
    locationID varchar(3),
    productNum int,
    quantityOnHand int,
    Foreign Key (warehouseID) references Warehouse (warehouseID),
    Foreign Key (productNum) references Product (productNum),
    Foreign Key (locationID) references Location (locationID)
    Engine = InnoDB;

A: I feel stupid now, the answer was to move warehouseID and locationID in the primary key so it was like this
create table Location (
warehouseID varchar(3),
locationID varchar(3),
Aisle int,
Shelf int,
Bin int,
capacity Double,
Primary Key (locationID, warehouseID),
Foreign Key (warehouseID) references Warehouse(warehouseID))
Engine = InnoDB;

I don't know why the order made a difference but it fixed the error.


text:
Q: How to join CSS transformY and jQuery UI sortable I have a task box that MUST to have limited height. Why? Because I have a button that scroll down tasks by CSS transformY and it let me to see more tasks that were hidden before. In my fiddle I created 2 examples. First is before tapping "scroll button" and second is after 3 tapes (so we can see 3 more tasks).
Then I made that boxes sortable. And problem is that after "scrolling" dragged element is jumping up.
Please try it yourself, to drag and drop tasks in first box and in second:

$(".barbox").sortable();

$("#scrolled").children(".bar").css("transform", "translateY(-153px)");
.barbox{
  height: 307px;
  overflow: hidden;
}

h1{
  margin-top: 30px;
}

.bar{
  display: flex;
  align-items: center;
  height: 50px;
  width: 300px;
  background-color: yellow;
  border-top: 1px solid red;
  overflow: hidden;
  vertical-align:bottom;
}

Example 1:

Task 1.

Task 2.

Task 3.

Task 4.

Task 5.

Task 6.

Task 7.

Task 8.

Task 9.

Example 2:

Task 1.

Task 2.

Task 3.

Task 4.

Task 5.

Task 6.

Task 7.

Task 8.

Task 9.

How to come up with that? How to join transformY and jQuery UI sortable?


text:
Q: php mysql search all special characters I cant figure out how to search for all special characters in mysql databse in single query.
For eg. search mysql and return the row whose column contains any of the special character like ",'#~;%*{ , etc. (means if some field have characters except 0-9, a-z, A-Z).
sample query type i want ---
SELECT * FROM mytable where column = 'PATTERN TO DETECT ALL SPECIAL CHARACTERS';

please also help with another query if i want to exclude some special chareacters like & ( ) . - from being searched.

A: Your query would like this, check the regex
SELECT *
FROM mytable
WHERE column regexp '[^a-zA-Z0-9]'

And the second query would be similar
SELECT *
FROM mytable
WHERE column regexp '[^a-zA-Z0-9\&]'

\ + character to ignore

A: Something like:
SELECT * FROM mytable where NOT(column REGEXP '^([:alnum:]|[:blank:])*$');

The '|' is an OR, the '[:alnum:]' matches anything alphanumeric, and [:blank:] matches whitespace (which you may or may not want), ^ matches the start and $ matches the end. So it returns where column is NOT made up of alphanumerics or whitespace from start to finish. Alternatively you could list all the disallowed chars in a single [] clause and match them.
You can add other chars if some special chars are OK:
SELECT * FROM mytable where NOT(column REGEXP '^([:alnum:]|[:blank:]|[()&])*$');

See the documentation for more here: http://dev.mysql.com/doc/refman/5.1/en/regexp.html
(I can't test the SQL from here, but I think I've got the syntax correct).

A: This is the simplest way:
SELECT *
FROM mytable
WHERE column REGEXP '[^a-zA-Z0-9]'

A: Try Using this query for searching special character records.
SELECT *
FROM tableName
WHERE fieldName REGEXP '[^a-zA-Z0-9@:. \'\-`,\&]'

We have removed symbols @ : dot(.) apostrophe (') hyphen (-) asterick(`) and comma(,) alphabets and numbers, so that we can see remaining special characters records.

A: SELECT *
  FROM table
 WHERE column1 REGEXP '[$&+,:;=?@#|]';

For More Info: http://dev.mysql.com/doc/refman/5.0/en/regexp.html


text:
Q: How to install Git Large File Storage on Windows? According to its doc, double-click should be enough. But when I opened git bash and ran git lfs init, it doesn't work:
$ git lfs init
git: 'lfs' is not a git command. See 'git --help'.

A: The only reason why "git lfs" would not be a git command would be because the git-lfs.exe hasn't been put in your %PATH%.
That is what the git-lfs-windows-amd64-0.5.3\install.bat is supposed to do.
set GIT_LFS_BIN_PATH="%LOCALAPPDATA%\GitLFS\bin"
IF EXIST %GIT_LFS_BIN_PATH% GOTO DIRECTORY_EXISTS
mkdir %GIT_LFS_BIN_PATH%
set "path=%PATH%;%GIT_LFS_BIN_PATH:"=%"

So:

*

*Make sure install.bat was successfully executed

*Check the content of "%LOCALAPPDATA%\GitLFS\bin"

*make sure to open a new CMD Windows

*Check your %PATH% environment variable

A: Just adding my 2c in case someone lands on this page..
The easiest (and I believe most "correct") option to install LFS on Windows is to use the windows' built-in winget package manager
winget install -e --id GitHub.GitLFS

I was getting the same error as you after simply running the downloaded installer, however the winget command fixed it for me.
PS. Even if you don't have winget - running winget will automatically install it from MS Store


text:
Q: Problem with reading a .Json File in Kotlin/Android I am writing something to read a Json in Android with Kotlin.
The Goal is to either start the ChooseLoginActicity if there is no User.Json available or to otherwise read the Json and start the MainActivity.
The problem is that the line to open the File into a Input Stream always gets an FileNotFoundException even if the User.Json exists with the Permission -rw-rw---- and got created with Context.MODE_PRIVATE, by the same Application.
This Function got called in the onCreate Function of the Activity.
fun readJsonFile() {
        try {
            val inputStream = openFileInput("User.json")

            val json = inputStream.bufferedReader().use { it.readText() }
            val gson = Gson()
            val user = gson.fromJson(json, User::class.java)

            CurrentUser.initUser(user.id,user.name)
            startActivity(Intent(this, MainActivity::class.java))
        } catch (e: FileNotFoundException) {
            startActivity(Intent(this, ChooseLoginActivity::class.java))
        }
    }

A: Make sure you wrote the correct file name. Pay attention about case sensitivity.
The code itself should work fine.


text:
Q: Insert or Update MySQL database if 3 fields match I have the following schema
CREATE TABLE `list` (
  `name` text NOT NULL,
  `value` text NOT NULL,
  `id` int(11) NOT NULL,
  `note` text,
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

and I would like to INSERT a new row into the database if a row with given name, value and id don't exist, otherwise I would like to update the note field. My insert query looks as follows:
INSERT INTO list (name, value, id, note)
VALUES("test", 2, 221222, "this is a test")

I am not sure what to do, as I don't have a primary key in the list and haven't been able to figure out how to set unique fields. Thank you in advance!

A:
I would like to insert a new row into the database if a row with given name, value and id don't exist.

Option 1
You can write a query that checks if the record already exists before inserting it:
INSERT INTO list (name, value, id, note)
SELECT 'test', 2, 221222, 'this is a test'
WHERE NOT EXISTS (
    SELECT 1
    FROM list
    WHERE name = 'test' AND value = 2 AND id = 221222 AND note = 'this is a test'
);

The downside of this approach is that you need to specify the values to insert twice. The advantage is that it does not require you to alter the table strucutre, hence it won't have side effects on other potential queries.
Option 2
You can take advantage of MySQL INSERT ... ON DUPLICATE KEY syntax. First of all, you  would need to create a composiye unique constraint on all 3 columns:
ALTER TABLE list ADD UNIQUE list_unique_index(id, name, value);

This actually prevents duplicates from being inserted (by any mean). Then you can express the query as follows:
INSERT INTO list (name, value, id, note)
    VALUES("test", 2, 221222, "this is a test")
    ON DUPLICATE KEYS UPDATE id = id

If the unique constraint validation fails, MySQL executes the UPDATE id = id clause, which is basically a no-op.
Note: there is a third option that consists in using INSERT ... IGNORE. I would not recommend that since that actually hides all error that could happen in the query (not only those related to the unique constraint); this behavior can bite you somehow.


text:
Q: Saving text from file as variable in Bash I have a text file called test.txt that looks like this:
================
Date = XXXXXX
Path = /path/to/file/

I'm writing a bash script that needs to go into test.txt and save the directory (not a consistent character length) listed after Path and save it as a variable to be used later in the bash script. (i.e. save the file path as Dir and and later in the script be able to call echo $Dir)

A: Here is one solution:
Dir=$(sed -ne 's/^Path *= *//p' test.txt)

However many other solutions are possibles

A: An awk-based possibility:
Dir=$(awk '{if ($1 == "Path") print $3}' test.txt)

or, if you want to stay purely within bash built-ins:
while read var eq value
do
    if [[ $var = Path ]]
    then
        Dir="$value"
    fi
done < test.txt


text:
Q: How to configure UITableView inside custom UITableViewCell in a Storyboard? I have a layout in which I will have 2 UITableViews with custom cells. The second UITableView must be inside the first.
My question is: how to delegate second UITableView?
Can I delegate both to my ViewController? In that case it will use the same methods and I have to find out which UITableView is managed right now.
Or I have to delegate it inside custom UITableViewCell of the first UITableView?
Any recommendations are appreciated.
EDIT: I don't know how to implement solutions here, because I have Storyboard. Inside my current UIViewController I set delegate and dataSource of the first UITableView to my View Controller.
My problem is that I don't know how to set the same properties of the second Table View (which will be inside UITableViewCell). I can not set them to UITableViewCell (IB does not allow that).
Where and how to set then in the IB?

A: A far better solution would be to abstract the DataSource and Delegate implementations away from your view controller so that they can be personalised per tableview as required (please note that the code is taken from the objc.io article Lighter View Controllers.
E.g.
@implementation ArrayDataSource

- (id)itemAtIndexPath:(NSIndexPath*)indexPath {
    return items[(NSUInteger)indexPath.row];
}

- (NSInteger)tableView:(UITableView*)tableView
 numberOfRowsInSection:(NSInteger)section {
    return items.count;
}

- (UITableViewCell*)tableView:(UITableView*)tableView
        cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    id cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier
                                              forIndexPath:indexPath];
    id item = [self itemAtIndexPath:indexPath];
    configureCellBlock(cell,item);
    return cell;
}

@end

Then you could utilise it as follows:
void (^configureCell)(PhotoCell*, Photo*) = ^(PhotoCell* cell, Photo* photo) {
   cell.label.text = photo.name;
};
photosArrayDataSource = [[ArrayDataSource alloc] initWithItems:photos
                                                cellIdentifier:PhotoCellIdentifier
                                            configureCellBlock:configureCell];
self.tableView.dataSource = photosArrayDataSource;

The same process could be followed with the UITableViewDelegate implementations to provide you with a very clean, separated and de-coupled code base. Your requirement for two tableviews will then be intrinsically easier to implement.

A: My answer is
  For identifying two table view data source and delegate method is,better to set tag for the table views.

Set this below coding in your tableview delegates method.
 if(tableView.tag==0)
 {
 }
 else
 {
 }

Also you can vary this by assigning different name to these table view.
 if(tableView==FirstTableView)
 {
 }
 else
 {
 }

A: You just check table condition for every delegate method
Use this code to register custom cell.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == self.yourFirstTable)
{
    CustomCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cellModifier"];
    // your code
}
else
{
    // second table cell code
}
return cell;
}

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
   {
        if(tableView == self.yourFirstTable)
        {
             // first tableView number of row return
        }
        else
        {
             // second table number of row return
        }
   }

And create prototype cell in TableView

And Set CellReusableId like this way


text:
Q: Cucumber/gradle example not generating report? I'm investigating using gradle and cucumber together, and found this lovely example in cucumber's github.
So, I cloned the repository and ran it myself. It failed, as it's configured to do, but I couldn't find the HTML or JSON report that it appears to be configured to output. I say appear because I'm brand new to cucumber, but this class would seem to indicate where it'll put it:
@RunWith(Cucumber.class)
@Cucumber.Options(format = {"pretty", "html:build/cucumber-html-report", "json-pretty:build/cucumber-report.json"})
public class RunCukesTest {

}

However, it's not appearing in the build directory after running gradle cucumber.There's no cucumber-html-report directory, not is there a cucumber-report.json file. I'm running it with Java 7 and Gradle 1.6, if it matters.
Ideas? Is this a known issue with the Cucumber/Gradle integration?

A: The class name changed depending on the version of Cucumber you are using. It changed from json-pretty to json.

A: When running the 'cucumber' task on this example the generated cucumber report is located at 'build/cucumber-html-report/index.html'. Running the 'test' task fails as it seems that gradle has problems to create the test report for the cucumber created tests (file name contains spaces) I need to dig a bit into this to see how this can be fixed in gradle.
cheers,
René

A: The cucumber-jvm-example doesn't do reporting using gradle cucumber, but does do it with gradle test. However, gradle test will have a couple issues, namely showing a "null" test of sorts.
A workaround to this, if need be, is to add the formats to the args of the javaexec that runs cucumber. For example, in build.gradle:
javaexec {
    main = "cucumber.api.cli.Main"
    classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
    args = ['--format', 'html:cucumber-html-report', '-f', 'pretty', '--glue', 'gradle.cucumber', 'src/test/resources']
}

A: I had an error with that very same line (taken from this tutorial).
In order to resolve, had to change the third parameter from "json-pretty" to just "pretty"
So this is my final code line:
@CucumberOptions(format = {"pretty", "html:target/cucumber-html-report", "pretty:target/cucumber-report.json"})
BTW,
@Cucumber.Options is deprecated, we should use CucumberOptions


text:
Q: Scala Json(json4s) parse return None $             "properties": [
                {
                   "name": "Armour",
                   "values": [
                      [
                         "258",
                         1
                      ]
                   ],
                   "displayMode": 0
                },...]

I have this JSON array.
I use json4s and scala for parse this code.
case class Property(
    name: String,
    values: Option[Option[(String, Int)]] = None,
    displayMode: Int
)

I write case class for this block, but I get "None" when get values...
I need get "258" in this example.  What am I doing wrong?

A: Your Json looks like you have a list of lists under your values property. I guess you want to have something like dictionary which should be with curly brackets instead of just brackets. Other thing is why would you parse that into Option[Option[(String, Int)]]? Try defining that as optional Map[String, Int].

A: Could this work?
values: List[(String, Int)] = Nil


text:
Q: Magento 2 : Restrict payment method by country not working I am facing issue related payment method show for the specific country using Magento 2.2.6. Below are the steps followed by me

*

*Set "Payment from Applicable Countries" to Specific Countries and a select couple of countries.

*On Frontend - open checkout and select any allowed country and click NEXT. It will show desired payment methods in the next step.

*Go back to Step #1 and select any other country which doesn't allow Check and Money Order and click NEXT.

*It will still show Check and Money Order though it is set to NO for the selected country.

This issue is also available on git hub community but I didn't find any solution.
https://github.com/magento/magento2/issues/10234
Please help me to solve this default Magento 2 issue.

A: Not sure if this has been fixed or not or in what terms it can be reproduced but I found it and had some problems with it in version 2.3.5. I tracked the code down to this file:
vendor/magento/module-payment/Model/Checks/CanUseForCountry/CountryProvider.php
For whatever reason it seems that (on a multi store at least) the billing address country always gets to be NULL and goes back to the default country set in configurations. I don't exactly know why it gets null on billing address country but I wrote a workaround to always get the shipping address country (that seems to always be the right one).
I made a plugin with an after for the method getCountry() and replaced this:
    $address = $quote->getBillingAddress() ? : $quote->getShippingAddress();

with this:
    $address = $quote->getShippingAddress();

Now I don't have any problems. I really don't know where this bug comes from and why that billing country is always NULL but at least now it works as intended. Hope it helps.


text:
Q: Basic Collision problems I have a sprite class which I am working on making a function for collision. I want the function to return true if two sprites collide. When I call the function I pass the moving objects desired X and Y position along with it's height and width. The invoking sprite is the object I that I would like to check.  For example if I wanted to check if player 1's move will intersect player 2's sprite I would say Player2.Collide(p1X, p1Y, p1H, p1W).
bool Sprite::Collides(int x, int y, unsigned short w, unsigned short h) const
{
    if ((x == this->GetWidth() + this->GetLeft()) &&
        (y >= this->GetTop() && y <= this->GetTop() + this->GetHeight()) ||
        ((x + w) == this->GetLeft()) &&
        (y >= this->GetTop() && y <= this->GetTop() + this->GetHeight()))
        return true;
else if ( (y == this->GetHeight() + this->GetTop()) &&
              ((x >= this->GetLeft() && x <= this->GetLeft() + this->GetWidth()) ||
              ((y + h) == this->GetTop() && (x >= this->GetLeft() && x <= this->GetLeft() + this->GetWidth()))))
        return true;
    return false;
}

The sprites are always rectangles. It seems I am forgetting to check some conditions for my collision. If the rectanges collide perfectly then everything works, however if I shift one up then try to butt against the other, it will glide right through. It seems each direction I approach has a similar behavior where it will work only for certain sections. Can you guys help me find what I'm forgetting to check?

A: I think you need to check the logic of your actual conditions again, shouldn't
(x == this->GetWidth() + this->GetLeft())

just that part of your if statement create a collision?  right after that you have an &&.  So in this case it needs to be touching on the top AND right, not just the right OR the top???
I also think the above line should really be:
(x <= this->GetWidth() + this->GetLeft())

Also, depending on your actual movement conditions (i.e. velocity, etc...) the above condition could really be
(x <= this->GetWidth() + this->GetLeft() - 1)

Lets explain the minus 1:
If you have two objects, one moving directly upward, and another moving directly downward, i.e. vertically and parallel to one another, then GetWidth + GetLeft creates a "went by" each other condition not a collision condition.
Example Sprites each 4 x 4 moving VERTICALLY with respect to each other:
Sprite A @ (0, 2)          Sprite B @ (4, 2)

   0     1     2     3        0     1     2     3
-------------------------  -------------------------
|     |     |     |     |  |     |     |     |     |
-------------------------  -------------------------
|     |     |     |     |  |     |     |     |     |
-------------------------  -------------------------
|     |     |     |     |  |     |     |     |     |
-------------------------  -------------------------
|     |     |     |     |  |     |     |     |     |
-------------------------  -------------------------

Sprite A @ (0, 1)          Sprite B @ (4, 3)

   0     1     2     3
-------------------------
|     |     |     |     |
-------------------------
|     |     |     |     |     0     1     2     3
-------------------------  -------------------------
|     |     |     |     |  |     |     |     |     |
-------------------------  -------------------------
|     |     |     |     |  |     |     |     |     |
-------------------------  -------------------------
                           |     |     |     |     |
                           -------------------------
                           |     |     |     |     |
                           -------------------------

Sprite A @ (0, 0)          Sprite B @ (4, 4)

   0     1     2     3
-------------------------
|     |     |     |     |
-------------------------
|     |     |     |     |
-------------------------
|     |     |     |     |
-------------------------
|     |     |     |     |     0     1     2     3
-------------------------  -------------------------
                           |     |     |     |     |
                           -------------------------
                           |     |     |     |     |
                           -------------------------
                           |     |     |     |     |
                           -------------------------
                           |     |     |     |     |
                           -------------------------

When sprite a is at location (0, 0), then GetWidth + GetLeft = (0 + 4) which is RIGHT of the actual end of the sprite.  IF another sprite is moving completely vertically downward with x position 4, then you algorithm would flag that as a collision, when in reality they are simply moving VERY CLOSELY by one another.  This is where the - 1 comes in.
Also, you really want to make sure to be careful with your screen geometry.  What I mean by this is many screens move from top-left being pixel (0, 0) to bottom right being pixel (positive X, positive y).  Your second condition:
(y >= this->GetTop() && y <= this->GetTop() + this->GetHeight())

MIGHT need to be:
( (y + h - 1) >= this->GetTop() || y <= (this->GetTop() + this->GetHeight() - 1) )

The first portion needs to change because originally you were testing for the TOP of your input object colliding with the TOP of your object to be tested against.  What you really want is the BOTTOM of your input to be tested with the TOP of your object to be tested against.
One thing I have always found extremely useful when trying to perform this type of coding, is to actually draw out very simple sketches with actual pixel based example numerics so that I can visualize it prior to coding it.
I hope all of this helps :-)


text:
Q: Many-to-Many Relationship I have been trying to "manufacture" a many-to-many relation module between content items in Orchard. Unfortunately, with no success. But then I got an idea of how to simulate such a relationship WITH TAGS. Basically, I have to relate a "project" content type/part with a "member" type/part. Here is my idea :
Create a "project" content type, and attach a tag part to it. Create a list of project type.
Create a "member" content type, and attach a tag part to it. Create a list of member type.
Add a container widget on the projects page, in which you show the elements of the list of project type, but in the view add a filter that only shows the content items that have a "project-xx" tag(project-x being the tag on(of) the current project). The only problem I see so far is :
How can I access the tag of another content part/type on the page, so as to use it in a view(access the "project" tags from within the "member" view ) ?
Any idea on this or any other idea on modeling a many-to-many relationship between content items in Orchard 1.1 would be appreciated. I have read the docs, but have not managed the create a n-n relationship between content items.

A: I know this is a bit old, but have you seen Mechanics module (http://gallery.orchardproject.net/List/Modules/Orchard.Module.Downplay.Mechanics)?
This allows you to create connections between content items. However, it doesn't work with more recent versions of Orchard (I think >= 1.5). Worth a try if you are still using 1.1


text:
Q: Word pretends to save files, not really saving them The following oddity has just occurred: one of our users has worked for many hours on a Word document, saving continuously. The document was open all the time, and she didn't close it until it was done.
This morning when she opened it, it only had the first few changes she had made, but everything done after 17:24 was not saved.
Now... 17:24 is the file's Last Modified Time. However, we have a Word add-in that we have developed ourselves for internal purposes, and this add-in logs to the event log whenever a user saves a document (this is not the add-in's actual purpose, this is just an extra trace we use).
I can see in this log that the user had actually saved the document several times after 17:24, and each time it is saying that the current Modified timestamp is 17:24. So basically, Word is "pretending" to save the document but doesn't actually do anything.
Also, I am seeing other Word documents in the log getting saved, and those were saved successfully. File and folder permissions are set correctly.
The only error I'm getting in the event log for that evening is
License Activation Scheduler (sppuinotify.dll) failed with the following error code: 0x80070005

which I believe is a Windows activation error. Also, late at night I got the following weird error from our add-in:
Activation context generation failed for "C:\Program Files (x86)\{Our company name}\{addin folder}\{addin name}.dll.Manifest".Error in manifest or policy file "C:\Program Files (x86)\{Out company name}\{addin folder}\{addin name}.Manifest" on line 4. The element asmv2:clrClassInvocation appears as a child of element urn:schemas-microsoft-com:asm.v1^entryPoint which is not supported by this version of Windows.

This is a WinSXS error. I have not clue why this is happening, there are no multiple versions of our addin on this system or anywhere for that matter.
My questions are:

*

*Has anyone encountered something like this, when Word simply decides to pretend it is saving files while in fact it is not? How would I even go about troubleshooting this non-reproducible error?

*Can the Windows activation problem affect this?

*Can our WinSXS add-in error affect word in this way, even though the add-in works well?
Any help would be appreciated... thank you!

A: The older version of Word I have has an option on the Tools... | Save tab called "Allow fast saves". Here's what the documentation says about it:

Allow fast saves:   Speeds up saving by recording only the changes in a
  document. When you finish working on a document, clear this option and
  save the complete file with a full save. A full save may decrease the
  file size of your document.

If this option is enabled, it could be causing the problem you describe. It's been a long time since I installed the application, but I think it was enabled by default.

A: A few things I have seen that are similar:
If saving locally, check the temp files. I have seen users lock a file, or crash word and start working with the auto-recovered document and then continue to edit and save in the temp directory not realizing it.
Offline Files
If the user is working on a machine with Offline files enabled and working on files on a network share; I have seen Offline files see the share as offline and work on the file with an offline cache. Especially problematic with laptop users. The file may be in the offline file cache.
These are both not super common, but worth checking.


text:
Q: Excel set a hyperlink column to another column I have an Excel file with two columns, the first column is normal text, and another column is a hyperlink, I hope to generate a 3rd column, which shows the text in the 1st column but when click it, it will directly go to the link from the 2nd column. Any help please?
e.g.
Item   Link         Combine
abc   www.aqwe.com  abc(click this cell go to the link)
xva   www.blah.com  xva(click this cell go to the link)

many thanks

A: Use HYPERLINK() function.
=HYPERLINK(B2,A2)


text:
Q: Final and Static Final usage in Java This is from the Ex18 of Chapter "Resuing Classes" in "Thinking in Java". The code is as below:
 public class E18 {
  public static void main(String[]args)
   {
    System.out.println("First object:");
    System.out.println(new WithFinalFields());
    System.out.println("First object:");
    System.out.println(new WithFinalFields());
   }

  }

class SelfCounter{
 private static int count;
 private int id=count++;
 public String toString()
 {
    return "self counter"+id;
 }

 }

class WithFinalFields
{
  final SelfCounter selfCounter=new SelfCounter();
  static final SelfCounter scsf=new SelfCounter();

      public String toString()
      {
           return "selfCounter="+selfCounter+"\nscsf="+scsf;
      }

}

The output of the code is:
 First object:
 selfCounter=self counter1
 scsf=self counter0

 First object:
 selfCounter=self counter2
 scsf=self counter0

I could understand why in both runs the scsf instance always gets the id assigned to 0 since it is declared to be a final and static field. What confuses me is why the id of "selfCounter" objects gets assigned to be 1 and 2 respectively, I am a bit stuck on how the calculation of id is carried out based on another static instance variable--"count".
Thanks for the guidance.

A: The ids are 1 and 2 because you're making three SelfCounter objects, all of which share the same count field, which is initialized implicitly to zero.
The first one is the static SelfCounter in WithFinalFields. Its ID is zero because the count field is implicitly initialized to zero, and the value of count++ is zero.
The second ID is one, because the value of count++ is one. And the third ID is then two, because the value of count++ is two.

A: The variable private static int count; is a static variable, it will have a value of 0 when the program is launched and will not be recreated. private int id=count++; is a dynamic variable.
You have 3 cases when a new instance of the SelfCounter() class is created: 1 because of the line static final SelfCounter scsf=new SelfCounter();, 1 when the new WithFinalFields() is launched for the first time, and 1 when it is launched for the second time.
So, the values during the first and the second launch of WithFinalFields() will be 1 and 2 respectively.


text:
Q: Update Object value with String Dot Notation function filterResult(field, value){
    var result = [
        {
            "name": "Johnson",
            "age": "12",
            "interests": {
                "color": "red"
            }
        },
        {
            "name": "Calvin",
            "age": "24",
            "interests": {
                "color": "blue"
            }
        }
    ];
    var filter = $.map(result, function(n, i){
        //other stuff here...
        n[field] = value; //dot notation
        return n;
    });
    return filter;
}

filterResult("interests.color","black");

Is there a way to convert String Dot Notation "interests.color" to object "n[field]" to update the value?

*

*Please note "interests.color" just an example. sometimes level can be deeper e.g. "interests.car.make.year". Dynamic is an idea.

Got an answer from other post.
function setterDotNotation(obj, str, value){
    if (typeof str == 'string'){
        return setterDotNotation(obj,str.split('.'), value);
    }else if (str.length==1 && value!==undefined){
        return obj[str[0]] = value;
    }else if (str.length==0){
        return obj;
    }else{
        return setterDotNotation(obj[str[0]], str.slice(1), value);
    }
}

A: You're not dealing with JSON here, you're dealing with an object (more specifically, an array of objects).
Anyway, you can .split() the "interests.color" string on the "." and then use the two pieces:
var fieldNames = field.split(".");       // returns ["interests", "color"]
n[fieldNames[0]][fieldNames[1]] = value;

Expand and run the following snippet to see it work in context:

function filterResult(field, value){
    var result = [
        {
            "name": "Johnson",
            "age": "12",
            "interests": {
                "color": "red"
            }
        },
        {
            "name": "Calvin",
            "age": "24",
            "interests": {
                "color": "blue"
            }
        }
    ];
    var filter = $.map(result, function(n, i){
        //other stuff here...
            var fieldNames = field.split(".");
            n[fieldNames[0]][fieldNames[1]] = value;
            return n;
    });
    return filter;
}

console.log( filterResult("interests.color","black") );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


text:
Q: Why is header box element out of body box element? I am trying to finish home project and I am stuck with header element box not being within body box element. Can you explain to me why is that happening and how to fix it?

* {
  border: 2px solid red;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: black;
  font-size: 22px;
  color: seashell;
  opacity: 0.9;
  font-family: Helvetica, 'Times New Roman', sans-serif;
  margin: 0 auto;
  min-height: 100%;
}

header {
  height: 69px;
  width: 100%;
  border-bottom: 1px solid seashell;
  position: fixed;
  display: inline;
}

      Mission
      Featured Tea
      Locations


text:
Q: How to open XML file with EPPlus I try to open an Excel file with the XML extension with EPPlus library.
using (var p = new ExcelPackage(new System.IO.FileInfo("file.xml")))

I can open the file with Excel manually.
With the Excel Interop  library it works too, but I would like to test performance with other library.
I took a look to the source of EPPlus and I see, it try to create an ZipPackage. But Xml file can't be transform to ZIP ... It contains already all information.
Someone success to open that kind of file with EPPlus ?


text:
Q: What is the use of the line [super loadView] I just wanted to know whether i am write or not
I have been working with iPhone technology for about 4 months and the only piece of code that i write in the loadView method is to add some views like the buttons,labels etc to the current instance of the viewController class so that when i use its view property all those views are added to the window.
But the piece of line that really bugs me is

[super loadView];

what is the use of this method all i came to know from diff sites is that "if i don't use this method my app will crash" that's not a reason i am looking for, so i made a virtual concept that this line might give us a black instance of UIView and then we add all the views [self.view addSubView:btn]; to the view provided to us by this line.

So all i wanted to know is that am i right or wrong, i think the [super loadView]; line does more than that can anyone give me a detailed explanation or provide me a link from where i can refer this concept.

A: -loadView is called by your view controller when the view is actually needed. Implement it if you are creating your view manually and not in IB. You are responsible for making sure the view property has a view assigned to it by the time this method is finished. Do not call [super loadView] or [self loadView] by yourself!
Official docs: "Your custom implementation of this method should not call super."
http://developer.apple.com/library/ios/documentation/uikit/reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instm/UIViewController/loadView

A: The super keyword calls the superclass' implementation of this method. So you probably are right on the money (I don't do objective-c) and this call initializes all the stuff you need to display your app.


text:
Q: Check For CSS Differences Between OS's I have an app that runs across a few different computers and I develop on Ubuntu using Chrome.
Normally my CSS layouts look ok on PC's running Windows, but I've been noticing that a few of my layouts will break when viewing on my co-worker's computers (instead of being side-to-side with floats, will break to a new line for example).
Generally removing a couple pixels on either side will take care of the inconsistencies. This got me to thinking, is there any way to check the display differences on CSS between OS's?  Generally there are guidelines on cross-browser styling, but I don't seem to remember any places that show the differences between OS's.

A: Most likely, the problems you're seeing aren't related to the OS so much as which fonts are being used and precisely how they're rendered.  Using default fonts, "ABC" might render 16px wide on Windows but only 15px wide on your flavor of Linux.
In general, it's a good idea to add in a little extra tolerance when sizing a box based on how long (in pixels) the text inside of it is.

A: You will have to test your css in different browsers. You must install as many browsers possible in your machine and check periodically.
Also, there are tools that render your site in different browsers and you can see snapshots.
like this one: http://browsershots.org/
it has a big list of browsers/OS to check.


text:
Q: How to find particular column name in all tables in postgresql db I am using the postgresql db for openproject.
I added two custom column in front end webpage ie. Actual start date and Actual End date .
I need to record the start and end of the actual dates for a project.
I dont know which table both columns has been created and storing the records.
My database is having 110 tables and its really hard for me to search each table one by one.
Can you please help and give me a query to find the both columns.
Thanks in advance.

A: This gives you the schema name as well as the table name of a specific column.
select t.table_schema,
       t.table_name,
       c.column_name
from information_schema.tables t
inner join information_schema.columns c on c.table_name = t.table_name
                                and c.table_schema = t.table_schema
where c.column_name = 'column_name'
      and t.table_schema not in ('information_schema', 'pg_catalog')
      and t.table_type = 'BASE TABLE'
order by t.table_schema;

Where obviously 'column_name' is the name you have to pass in for a column.


text:
Q: How can I access a memory mapped device, synthesized on fpga, with a Lauterbach script? on a ZCU106 board with MPSoC Zynq Ultrascale+, I have developed a simple test application that performs reads and writes to a memory-mapped device register. The device in question is a GPIO peripheral, synthesized to fpga and accessed in memory with address (0xA0010000) configured via Vivado tool. The application does not use MMU. If I try to launch and run my application from the Vitis debugger, everything works correctly, with no problems. However, I need to launch the application from Lauterbach's Trace32. By doing the launch with a practice script (Lauterbach's scripting language), the application loads correctly, but upon reading or writing to the memory address where the synthesized device is mapped to fpga, a "debug port fail" type problem is returned. I therefore analyzed the tcl script automatically generated by Vitis to see if there are any hardware configurations that are made in tcl, but which I do not predict with the practice script (Lauterbach). My suspicion is that there are special instructions to enable the mapping of memory addresses that a processor can access. I attach the tcl script generated by Vitis, perhaps the "offending" instruction is the 'loadhw -hw'? Thanks in advance to anyone who can help me.
# In Vitis IDE create a Single Application Debug launch configuration,
# change the debug type to 'Attach to running target' and provide this
# tcl script in 'Execute Script' option.
# Path of this script: /home/daniele/vitis_workspace/interr_measurement_test_system/_ide/scripts/debugger_interr_measurement_test-default.tcl
#
#
# Usage with xsct:
# To debug using xsct, launch xsct and run below command
# source /home/daniele/vitis_workspace/interr_measurement_test_system/_ide/scripts/debugger_interr_measurement_test-default.tcl
#
connect -url tcp:127.0.0.1:3121
source /tools/Xilinx/Vitis/2021.2/scripts/vitis/util/zynqmp_utils.tcl
targets -set -nocase -filter {name =~"APU*"}
rst -system
after 3000
targets -set -filter {jtag_cable_name =~ "Xilinx HW-FTDI-TEST FT232H 49619" && level==0 && jtag_device_ctx=="jsn-HW-FTDI-TEST FT232H-49619-14730093-0"}
fpga -file /home/daniele/vitis_workspace/interr_measurement_test/_ide/bitstream/zcu106_int_meas_plat_wrapper.bit
targets -set -nocase -filter {name =~"APU*"}
loadhw -hw /home/daniele/vitis_workspace/zcu106_int_meas_plat_wrapper/export/zcu106_int_meas_pp
lat_wrapper/hw/zcu106_int_meas_plat_wrapper.xsa -mem-ranges [list {0x80000000 0xbfffffff} {0x400000000 0x5ffffffff} {0x1000000000 0x7fffffffff}] -regs
configparams force-mem-access 1
targets -set -nocase -filter {name =~"APU*"}
set mode [expr [mrd -value 0xFF5E0200] & 0xf]
targets -set -nocase -filter {name =~ "*A53*#0"}
rst -processor
dow /home/daniele/vitis_workspace/zcu106_int_meas_plat_wrapper/export/zcu106_int_meas_plat_wrapper/sw/zcu106_int_meas_plat_wrapper/boot/fsbl.elf
set bp_30_4_fsbl_bp [bpadd -addr &XFsbl_Exit]
con -block -timeout 60
bpremove $bp_30_4_fsbl_bp
targets -set -nocase -filter {name =~ "*A53*#0"}
rst -processor
dow /home/daniele/vitis_workspace/interr_measurement_test/Debug/interr_measurement_test.elf
configparams force-mem-access 0
bpadd -addr &main


text:
Q: State of Checkbox remains same $('#SaveCheckbox').attr('checked') != true

Intending to check the value of CheckBox by the above means , as found the solution , but its giving false always , either i check the checkbox or uncheck it.
Kindly help.
I am using jquery-1.10.2.min.js and jquery.mobile-1.4.0.min.js libraries.

A: Use prop() instead of attr()
$('#SaveCheckbox').prop ('checked') != true

As of jQuery 1.6, the .attr() method returns undefined for attributes
  that have not been set. To retrieve and change DOM properties such as
  the checked, selected, or disabled state of form elements, use the
  .prop() method, jQuery Docs

You can also use :checked
if($('#SaveCheckbox').is(":checked"))

OR
if($('#SaveCheckbox:checked').length)


text:
Q: How toFind the absolute max and min values of a multivariable function bounded by a circular boundary so as shown below in the image, the qustion is to find the max and min for the given function. The thing that i am not getting is why did the auther not consider the following:
1) $x =0$ or $ 2x+3y^2$ if $x=0$ here then $y= sqrt(2/3)$ and so is for the second equation when $y=0$ then $x=sqrt(1/2)$
2) how did he arrive at $8e{^4}<g(x,y)< 12e^{-4}$

A: We have
$$g_x = 2xe^{-x^2-y^2}(2 - 2x^2 - 3y^2)$$
$$g_y = 2ye^{-x^2-y^2}(3 - 2x^2 - 3y^2)$$
If $x,y$ are both zero, it's immediate that $g_x = 0$ and $g_y=0$, hence $(0,0)$ is a critical point.

Suppose $(x,y)$ is a critical point with $x \ne 0$. Then
\begin{align*}
&x \ne 0\\[4pt]
\implies\; &2 - 2x^2 - 3y^2 = 0&&\text{[since $g_x = 0$]}\\[4pt]
\implies\; &2x^2 + 3y^2 = 2\\[4pt]
\implies\; &2x^2 + 3y^2 \ne 3\\[4pt]
\implies\; &3-2x^2 - 3y^2 \ne 0\\[4pt]
\implies\; &y = 0&&\text{[since $g_y = 0$]}\\[4pt]
\implies\; &2x^2 = 2&&\text{[since $2x^2 + 3y^2 = 2$]}\\[4pt]
\implies\; &x = \pm{1}\\[4pt]
\implies\; &(x,y) = (\pm{1},0)\\[4pt]
\end{align*}
Thus, the points $(\pm 1,0)$ are candidate critical points.

One can easily verify that
$$g_x(1,0) = 0 = g_y(1,0)$$
$$g_x(-1,0) = 0 = g_y(-1,0)$$
hence the points $(\pm 1,0)$ are actual critical points.

Similarly, suppose $(x,y)$ is a critical point with $y \ne 0$. Then
\begin{align*}
&y \ne 0\\[4pt]
\implies\; &3 - 2x^2 - 3y^2 = 0&&\text{[since $g_y = 0$]}\\[4pt]
\implies\; &2x^2 + 3y^2 = 3\\[4pt]
\implies\; &2x^2 + 3y^2 \ne 2\\[4pt]
\implies\; &2-2x^2 - 3y^2 \ne 0\\[4pt]
\implies\; &x = 0&&\text{[since $g_x = 0$]}\\[4pt]
\implies\; &3y^2 = 3&&\text{[since $2x^2 + 3y^2 = 3$]}\\[4pt]
\implies\; &y = \pm{1}\\[4pt]
\implies\; &(x,y) = (0,\pm{1})\\[4pt]
\end{align*}
Thus, the points $(0,\pm 1)$ are candidate critical points.

One can easily verify that
$$g_x(0,1) = 0 = g_y(0,1)$$
$$g_x(0,-1) = 0 = g_y(0,-1)$$
hence the points $(0,\pm 1)$ are actual critical points.

So we have $5$ critical points, namely
$$(0,0),\;\;(\pm 1,0)\;\;(0,\pm 1)$$
Next, suppose $(x,y)$ is a point on the boundary of $\Delta$.

Then $x^2 + y^2 = 4$, hence
\begin{align*}
f(x,y) &= (2x^2 + 3y^2)e^{-x^2 - y^2}\\[4pt]
&=(2(x^2+y^2) + y^2)e^{-x^2 - y^2}\\[4pt]
&=(8 + y^2)e^{-4}&&\text{[since $x^2 + y^2 = 4$]}\\[4pt]
\end{align*}
But for $(x,y) \in \Delta$, we have $x^2 + y^2 \le 4$, hence $0 \le y^2 \le 4$.

Thus, for a point $(x,y)$ on the boundary of $\Delta$,
\begin{align*}
&f(x,y) = (8 + y^2)e^{-4}\\[4pt]
\implies\;&8e^{-4} \le f(x,y) \le 12e^{-4}\\[4pt]
\end{align*}
Checking the values of $f$ at the $5$ critical points,

$\;\;\;{\small\bullet}\;$The minimum value of $f$ at the critical points is $0$, which occurs at $(0,0)$.

$\;\;\;{\small\bullet}\;$The maximum value of $f$ at the critical points is $3e^{-1}$, which occurs at $(0,\pm 1)$.

Since $0 < 8e^{-4}$ and $3e^{-1} > 12e^{-4}$, none of the boundary points qualify as candidates for points where $f$ has an absolute minimum or absolute maximum.

Thus, the absolute extreme values of $f$ on $\Delta$ are the minimum and maxiumum values of $f$ at the critical points, which have already been determined.


text:
Q: Pass URL parameter from JSP to Servlet So I have a JSP with a randomly generated "key" inside the URL, which will be something like this:
url.com/reset.jsp?key=1234

And my JSP has two text inputs inside a form
<form action="ResetServlet" method="post" enctype="multipart/form-data">
<input type="text" name="firstname" size="24" value="">
<input type="text" name="lastname" size="24" value="">
</form>

And I'm trying to send the 3 parameters: Key from URL, user input of "firstname", and user input of "lastname" to my Java Servlet code. How do I read the 3 parameters from my Servlet code? Can anyone point me to a tutorial or explain how I could do that? Thanks.
EDIT:
So I wrote the following simple servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String firstname = request.getParameter("firstname");
    String lastname = request.getParameter("lastname");
    String key = request.getParameter("key");

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();
    out.println("<h1>" + "Hello: " + firstname + " " + lastname + ". key: " + key + "</h1>");
}

And it displays:

Hello: null null. key: null

No matter what I input. What am I doing wrong?

A: Just save the key parameter in the form when the page renders.
<!-- declare at top of JSP -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<form action="ResetServlet" method="post" enctype="multipart/form-data">
  <input type="text" name="firstname" size="24" value="">
  <input type="text" name="lastname" size="24" value="">

  <input type="hidden" name="key" value="<c:out value='${param.key}'/>">
</form>

A: You can use HttpServletRequest.getParameter(String) method. For example,
public class ResetServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    String firstName = request.getParameter("firstname");
    String lastName  = request.getParameter("lastname");
    String key       = request.getParameter("key");
  }
}

A: One can read parameter from query string using request.getParameter("variable_name");
in your case it will be
.....doPost(HttpServletRequest request, HttpServletResponse response) {
  String firstName = request.getParameter("firstname");
  String lastName  = request.getParameter("lastname");
  String key       = request.getParameter("key");
}

A: Just remove  enctype part in form tag.


text:
Q: Bypass "supress_filters" in WP Query Apparently, for some illogical reason, the developers decided that the only way to fetch posts in all languages, is to add supress_filters=true to the WP_Query (instead of having like say, a language_code=all option).
Anyways, I am in a situation where I need to fetch posts in all languages, but ALSO modify the WP_Query using filters. Is there a way to enforce that my filters are being added to the query, even though supress_filters is set to false?
This is the filter I need to add:
add_filter( 'posts_where', function($where, $wp_query) {
    global $wpdb;

    if($search_term = $wp_query->get( 'custom_search' )){
        $search_term = $wpdb->esc_like($search_term);
        $search_term = ' \'%' . $search_term . '%\'';
        $where .= ' AND (' . $wpdb->posts . '.post_title LIKE ' . $search_term . ' OR ' . $wpdb->posts . '.ID LIKE ' . $search_term . ' OR ' . $wpdb->posts . '.post_name LIKE ' . $search_term . ')';
    }

    return $where;
}, 10, 2 );

But it is removed after adding supress_filters=true (because I need to fetch posts in ALL languages)

A: Looking at the WP_Query Class you should be able to use pre_get_posts to modify the query before any other filters are run, which includes turning off the suppress_filters flag. An example of this could be:
/**
 * Modify WP_Queries
 * @link https://wordpress.stackexchange.com/q/356950/7355
 *
 * @param WP_Query $query
 *
 * @return void
 */
function wpse356950_query_modifications( $query ) {

    // Don't run on admin
    if( is_admin() ) {
        return;
    }

    // Some conditional to tell our query from other queries
    if( $query->get( 'suppress_filters' ) ) {
        $query->set( 'suppress_filters', false );
    }

}
add_action( 'pre_get_posts', 'wpse356950_query_modifications' );

A: One way I have found to be working is to remove the filters manually added by WPML core, like so:
global $wpml_query_filter;

/**
 * WPML fetch in all languages
 */

    remove_filter( 'posts_join', array( $wpml_query_filter, 'posts_join_filter' ), 10, 2 );
    remove_filter( 'posts_where', array( $wpml_query_filter, 'posts_where_filter' ), 10, 2 );

That's OK in my scenario, as this specific page only has one WP_Query. If you have multiple, where you need to fetch for a specific language, I recommend you readd the filters after WP_Query has run.


text:
Q: Cassandra rack concept and database structure I am new to Cassandra and I would like to learn more about Cassandra's racks and structure.
Suppose I have around 70 column families in Cassandra and two AWS2 instances.

*

*How many Data Centres will be used?

*How many nodes will each rack have?

*Is it possible to divide a column family in multiple keyspaces?

A: The intent of making Cassandra aware of logical racks and data centers is to provide additional levels of fault tolerance.  The idea (as described in this document, under the "Network Topology Strategy") is that the application should still be able to function if one rack or data center goes dark.  Essentially, Cassandra...

places replicas in the same data center by walking the ring clockwise
  until reaching the first node in another rack. NetworkTopologyStrategy
  attempts to place replicas on distinct racks because nodes in the same
  rack (or similar physical grouping) often fail at the same time due to
  power, cooling, or network issues.

In this way, you can also query your data by LOCAL_QUORUM, in which QUORUM ((replication_factor / 2) + 1) is only computed from the nodes present in the same data center as the coordinator node.  This reduces the effects of inter-data center latency.
As for your questions:

*

*How many data centers are used are entirely up to you.  If you only have two AWS instances, putting them in different logical data centers is possible, but only makes sense if you are planning to use consistency level ONE.  As-in, if one instance goes down, your application only needs to worry about finding one other replica.  But even then, the snitch can only find data on one instance, or the other.

*Again, you can define the number of nodes that you wish to have for each rack.  But as I indicated with #1, if you only have two instances, there isn't much to be gained by splitting them into different data centers or racks.

*I do not believe it is possible to divide a column family over multiple keyspaces.  But I think I know what you're getting at.  Each keyspace will be created on each instance.  As you have 2 instances, you will be able to specify a replication factor of 1 or 2.  If you had 3 instances, you could set a replication factor of 2, and then if you lost 1 instance you would still have access to all the data.  As you only have 2 instances, you need to be able to handle one going dark, so you will want to make sure both instances have a copy of every row (replication factor of 2).
Really, the logical datacenter/rack structure becomes more-useful as the number of nodes in your cluster increases.  With only two, there is little to be gained by splitting them with additional logical barriers.  For more information, read through the two docs I linked above:
Apache Cassandra 2.0: Data Replication
Apache Cassandra 2.0: Snitches