text:
Q: Kubernetes Shared Cluster We're planning our new Kubernetes cluster infrastructure and I have some questions.
Currently, we have one larger cluster where environments (dev, staging, prod) and multiple teams are working on. In the beginning, it was just a "POC", a demo - but guys you know: nothing lasts longer than temporary solutions.
On this setup, we have some general issues and on our destination architecture, we plan to fix some of those topics.
I hope that some of you can share knowledge/experience.
First of all: one cluster per application is not a solution. The applications are really small and every team has around 3-5 applications and needs about 6-20GB of ram over all nodes per environment. So a single cluster is not really an option.
We plan one cluster per environment: dev, staging (qa), prod, and maybe for operations a demo cluster.
Everything is and will be automated and IaC with terraform + ansible (kubespray).
Every team/application scope will get a single namespace - of cause.
Our questions / problems:
Monitoring
Normally we use Prometheus and Grafana to monitor pod/cluster resource usage. New should also contain central logging (we're trying out solutions right now).
This is fine for the infra-team, but infra doesn't want to monitor on application level.
Is there any working way to provide the app-teams a monitoring? Like: you (the app-team) can setup alerts on logs, cpu, ram usage whatever you need. "You just need to roll out this helm chart".
In a great world, I would provide every team (so every namespace) it's own monitoring stack so we're also able to limit storage and ram+cpu usage and every team is able to use the "ordered" resources (so if the team has a lot of logs / monitoring needs, it need to "order" more resources").
Also based on that approach, they can choose the software that suits best.
Another solution could be that infra team setups a central monitoring / log solution and limit the access. App-Team A should not be able to access logs / cpu usage / ram usage / disk usage from App-Team B. But I can't see any way to do that really good.
It can be an option that infra team installs that stack - but everything I saw is: when I install a monitoring stack on a specific namespace, the stack needs admin access to the cluster. This is not nice in my opinion.
Am I wrong?
Storage
We have a gluster storage and want to keep it. If a team needs a disk, we add a "glusterfs persistent volume" with a specific size and storageClassName like "team1-disk5".
Based on that, the team can create a PVC and use the storage. Works fine in the past.
Is this a good solution? Any other ideas?
I think that's all for the moment. Just those two questions. Any idea to move me in the correct direction?
Thanks!


text:
Q: Porting C++ OpenGL Game to iPad We have a game, developed in C++ and OpenGL for Windows and Mac.
Now we want to port the game to iPad. Is there a better way than writing the entire program in Objective-C to make our game work on iPad?
Now I am an iPhone/iPad noob, so pardon if the question is dumb.

A: You probably need to write only a small part in Obj-C that deals directly with iOS(creating a gl surface, input etc). Rest should work fine. You just need to make sure you will be using only the subset of OpenGL that is in OpenGL ES.

A: I hear DragonFire SDK lets you develop in C++ for iOS, on Windows.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tekton dashboard deployment error- Error from server (Forbidden): error when creating "config/service.yaml" I am trying to practice the steps in my local using minikube. From the teokton-dashboard in my local I am able to import the resource using git url. I followed all the steps but when creating pipeline runs I am getting error as Error from server (Forbidden): error when creating "config/service.yaml". I tried using default namespace as well as tekton-pipeline namespace. I used tekton-dashboard as serviceAccount.
[![Error from server (Forbidden): error when retrieving current configuration of:
Resource: "apps/v1, Resource=deployments", GroupVersionKind: "apps/v1, Kind=Deployment"
Name: "myapp", Namespace: "tekton-pipelines"
from server for: "config/deployment.yaml": deployments.apps "myapp" is forbidden: User "system:serviceaccount:tekton-pipelines:tekton-dashboard" cannot get resource "deployments" in API group "apps" in the namespace "tekton-pipelines"
Error from server (Forbidden): error when creating "config/service.yaml": services is forbidden: User "system:serviceaccount:tekton-pipelines:tekton-dashboard" cannot create resource "services" in API group "" in the namespace "tekton-pipelines"][1]][1]

Attaching screenshots for reference


text:
Q: Pytorch ram does not free after every epoch I am training a multi-label text classifier using PyTorch with Roberta. However after 2nd epoch ram fills and kernel crashes I checked and ram is not freed after every epoch. I have 64GB RAM, 8 CPU cores
What can be the problem?
Here is the my PyTorch implementation:
class ReaderTextDataset(Dataset):
def __init__(self,
             data: pd.DataFrame,
             tokenizer: RobertaTokenizer,
             max_token_len: int = 512):
    self.tokenizer = tokenizer
    self.data = data
    self.max_token_len = max_token_len

def __len__(self):
    return len(self.data)

def __getitem__(self, index: int):
    data_row = self.data.iloc[index]

    readerText = data_row.readerText
    labels = data_row[LABEL_COLUMNS]

    encoding = self.tokenizer.encode_plus(
        readerText,
        add_special_tokens=True,
        max_length=self.max_token_len,
        return_token_type_ids=False,
        padding="max_length",
        truncation=True,
        return_attention_mask=True,
        return_tensors='pt',
    )

    return dict(readerText=readerText,
                input_ids=encoding["input_ids"].flatten(),
                attention_mask=encoding["attention_mask"].flatten(),
                labels=torch.FloatTensor(labels))

train_dataset = ReaderTextDataset(train_df, tokenizer, max_token_len=512)

roberta_model = RobertaModel.from_pretrained(BERT_MODEL_NAME, return_dict=True)
NUM_WORKERS = 6
class ReaderTextDataModule(pl.LightningDataModule):
def __init__(self,
             train_df,
             test_df,
             tokenizer,
             batch_size=8,
             max_token_len=512):
    super().__init__()
    self.batch_size = batch_size
    self.train_df = train_df
    self.test_df = test_df
    self.tokenizer = tokenizer
    self.max_token_len = max_token_len

def setup(self, stage=None):
    self.train_dataset = ReaderTextDataset(self.train_df, self.tokenizer,
                                           self.max_token_len)

    self.test_dataset = ReaderTextDataset(self.test_df, self.tokenizer,
                                          self.max_token_len)

def train_dataloader(self):
    return DataLoader(self.train_dataset,
                      batch_size=self.batch_size,
                      shuffle=True,
                      num_workers=NUM_WORKERS)

def val_dataloader(self):
    return DataLoader(self.test_dataset,
                      batch_size=self.batch_size,
                      num_workers=NUM_WORKERS)

def test_dataloader(self):
    return DataLoader(self.test_dataset,
                      batch_size=self.batch_size,
                      num_workers=NUM_WORKERS)

class ReaderTextTagger(pl.LightningModule):

def __init__(self,
             n_classes: int,
             n_training_steps=None,
             n_warmup_steps=None):
    super().__init__()
    self.bert = RobertaModel.from_pretrained(BERT_MODEL_NAME,
                                             return_dict=True)
    self.classifier = nn.Linear(self.bert.config.hidden_size, n_classes)
    self.n_training_steps = n_training_steps
    self.n_warmup_steps = n_warmup_steps
    self.criterion = nn.BCELoss()

def forward(self, input_ids, attention_mask, labels=None):
    output = self.bert(input_ids, attention_mask=attention_mask)
    output = self.classifier(output.pooler_output)
    output = torch.sigmoid(output)
    loss = 0
    if labels is not None:
        loss = self.criterion(output, labels)
    return loss, output

def training_step(self, batch, batch_idx):
    input_ids = batch["input_ids"]
    attention_mask = batch["attention_mask"]
    labels = batch["labels"]
    loss, outputs = self(input_ids, attention_mask, labels)
    self.log("train_loss", loss, prog_bar=True, logger=True)
    return {"loss": loss, "predictions": outputs, "labels": labels}

def validation_step(self, batch, batch_idx):
    input_ids = batch["input_ids"]
    attention_mask = batch["attention_mask"]
    labels = batch["labels"]
    loss, outputs = self(input_ids, attention_mask, labels)
    self.log("val_loss", loss, prog_bar=True, logger=True)
    return loss

def test_step(self, batch, batch_idx):
    input_ids = batch["input_ids"]
    attention_mask = batch["attention_mask"]
    labels = batch["labels"]
    loss, outputs = self(input_ids, attention_mask, labels)
    self.log("test_loss", loss, prog_bar=True, logger=True)
    return loss

def training_epoch_end(self, outputs):

    labels = []
    predictions = []
    for output in outputs:
        for out_labels in output["labels"].detach().cpu():
            labels.append(out_labels)
        for out_predictions in output["predictions"].detach().cpu():
            predictions.append(out_predictions)

    labels = torch.stack(labels).int()
    predictions = torch.stack(predictions)

    for i, name in enumerate(LABEL_COLUMNS):
        class_roc_auc = auroc(predictions[:, i], labels[:, i])
        self.logger.experiment.add_scalar(f"{name}_roc_auc/Train",
                                          class_roc_auc,
                                          self.current_epoch)

def configure_optimizers(self):

    optimizer = AdamW(self.parameters(), lr=1e-5)

    scheduler = get_linear_schedule_with_warmup(
        optimizer,
        num_warmup_steps=self.n_warmup_steps,
        num_training_steps=self.n_training_steps)

    return dict(optimizer=optimizer,
                lr_scheduler=dict(scheduler=scheduler, interval='step'))

enter code here

A: You return output, which stores in the GPU, in every train_step. Try to move it to cpu if you really need to store output by
return {"loss": loss, "predictions": outputs.cpu(), "labels": labels}


text:
Q: Error while cropping image using Numpy i was try this code
import cv2
img = cv2.imread("image.jpg")
crop_img = img[100:200, 200:400] # Crop from x, y, w, h -> 100, 200, 100, 200
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)

it work for few times..but suddenly it come out with this error:
Traceback (most recent call last):
File "test5.py", line 7, in <module>
crop_img = img[100:200, 200:400] # Crop from x, y, w, h -> 100, 200, 100, 200``
TypeError: 'NoneType' object has no attribute '__getitem__'

anyone can help me..

A: If cv2.imread cannot find the file name it returns None.
If img is None, then img[100:200, 200:400] will raise
TypeError: 'NoneType' object has no attribute '__getitem__'


text:
Q: Look for ReSharper 5.0 Menu Map I have found this ReSharper 5.0 Default Key Map
http://www.jetbrains.com/resharper/docs/ReSharper50DefaultKeymap_IDEA_scheme.pdf
I would like to find a corresponding Menu Map so that I know where each command is located in the menu.

A: Unfortunately no such document exists. We've been considering writing one for some time, but there's still no tangible result.
The closest one that we have is ReSharper Feature Map but it's been a while since it was last updated.


text:
Q: E-commerce compliance when card details are processed by a third party What forms of e-commerce compliance such as PCI-DSS apply when the card details are processed by a third party such as Paypal?
Am building a bespoke shopping cart system that uses Paypal Express, so the card details never hit my server. I do however retain customer details so what compliance - both at a code and hardware level - must or should I be adhering to?

A: According to the PCI DSS, you only need to encrypt customer details if they are stored along with the PAN (aka credit card number).  Since you aren't storing or transacting the PAN, there should be nothing extra you need to do.
See page 5 on the PCI DSS:
https://www.pcisecuritystandards.org/security_standards/pci_dss_download.html

A: If credit card data never physically hits your server (including RAM due to a form post) then PCI-DSS does not apply. Outsourcing your credit card handling to a compliant third party is by far the easiest way to be compliant yourself.


text:
Q: Como saber se determinada coluna existe numa tabela no Laravel? Gostaria de saber se existe alguma maneira de saber se  uma coluna existe ou não no Laravel.
Por exemplo, quero fazer uma ordenação com dados vindos da query string. Se o valor "coluna" existir na tabela, então eu ordeno por esse campo.
 $coluna = Input::get('coluna');

 if (se_a_coluna_existe_na_tabela('usuarios', $coluna))
 {
     $query->orderBy($coluna);
 }

A: Não é tão dificil, você pode apenas usar o seguinte código
if(Schema::hasColumn('users', 'email')) ; //verifica se a tabela users tem a coluna email
{
    $query->orderBy($coluna);
}

pronto!
Caso tenha alguma dúvida, tente dar uma olhada na documentação do laravel.
https://laravel.com/docs/5.0/schema#checking-existence


text:
Q: Running Instruments on iPod touch, device restart I can't get my application running with instruments. I tried running through xcode with Product->Profile, Instruments starts, and then i select Time profile, iPod gets restart.
 I am on 10.7, xcode 4.2, iPod touch4 with iOS 5.0.1, and using 5.0 SDK. Need help!

A: iPod just running out of memory.


text:
Q: MongoDB Aggregate: Sorting by existing values first My user has this field :
interestedIn: [{
        type: String,
        enum: [
            'art',
            'sport',
            'news',
            'calture',
            ...
        ],
    }],

and my video has this field:
categories: [{
            type: String,
            enum: [
                'art',
                'sport',
                'news',
                'calture',
                ...
            ],
        }],

So I need a Video query that has the following conditions:

*

*Query to all videos and sort by values in req.user.interestedIn first.

*Rest of the videos that are not match to req.user.interestedIn get in the last.

I got this far with said query:
Video.aggregate([

        { '$match': {}},
        { '$unwind': '$categories' },
        { '$match': {categories: {$in: req.user.interestedIn}}},
        { '$group': {
            '_id': '$categories',
            'categories': { '$push': '$categories' }
        }},
        { '$sort': { 'categories': 1 } }
    ])

This is the result:
   "videos": [
        {
            "_id": "art",
            "categories": [
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art"
            ]
        },
        {
            "_id": "news",
            "categories": [
                "news",
                "news",
                "news",
                "news",
                "news",
                "news",
                "news",
                "news",
   "videos": [
        {
            "_id": "art",
            "categories": [
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art",
                "art"
            ]
        },
        {
            "_id": "news",
            "categories": [
                "news",
                "news",
                "news",
                "news",
                "news",
                "news",
                "news",
                "news",
                "news",
                "news",
                "news",
                "news",
                "news",
                "news"
            ]
        }
    ]
}

A: You can use $setIntersection to extract the matching elements followed by $size to count the matches.
$sort  descending documents on number of matches.
Something like
Video.aggregate([
  {"$addFields":{ "numofmatches":{"$size":{"$setIntersection":["$categories", req.user.interestedIn]}}}},
  {"$sort":{"numofmatches":-1}}
])


text:
Q: I have a multi dimensional array with objects and need to calculate the sum of each column using javascript I am working in angularjs. i am getting a response in json format. and the json is
"vals": [{
        "season": "SUMMER",
        "usage": [
            ["PEAK", "1.000", "2.000", "3.000", "4.000", "5.000", "6.000", "7.000", "8.000", "9.000"],
            ["NORMAL", "10.000", "11.000", "12.000", "13.000", "14.000", "25.000", "16.000", "17.000", "18.000"],
            ["OFF-PEAK", "19.000", "20.000", "21.000", "22.000", "23.000", "24.000", "25.000", "26.000", "27.000"]
        ]
    }, {
        "season": "MONSOON",
        "usage": [
            ["PEAK", "28.000", "29.000", "30.000", "31.000", "32.000", "33.000", "34.000", "35.000", "36.000"],
            ["NORMAL", "37.000", "38.000", "39.000", "40.000", "41.000", "42.000", "43.000", "44.000", "45.000"],
            ["OFF-PEAK", "46.000", "47.000", "48.000", "49.000", "50.000", "51.000", "52.000", "53.000", "54.000"]
        ]
    }, {
        "season": "WINTER",
        "usage": [
            ["PEAK", "55.000", "56.000", "57.000", "58.000", "58.000", "59.000", "60.000", "61.000", "62.000"],
            ["NORMAL", "63.000", "64.000", "65.000", "66.000", "67.000", "68.000", "69.000", "70.000", "71.000"],
            ["OFF-PEAK", "72.000", "73.000", "74.000", "75.000", "76.000", "77.000", "78.000", "79.000", "80.000"]
        ]
    }]

I have to calculate the value of each column and push that into a new array i.e
[(1.000+10.000+19.000+28.000+37.000+46.000+55.000+63.000+72.000),(2.000+11.000+20.000+29.000+38.000+47.000+56.000+64.000+73.000),(3.000+12.000+21.000+30.000+39.000+48.000+57.000+65.000+74.000),(4.000+13.000+22.000+31.000+40.000+49.000+58.000+66.000+75.000).....]

I was doing that and got the desire result but i mention the column number when i am calculating the total but column can be dynamic. I was ashamed to say that i was unable to solve it. If there is any way to make it dynamic please help. or if there is any better  way then please share. I worked for 5 columns but given json has 9 columns. My code is
$scope.ctrlFn= function(){
  var raw = angular.copy($scope.subStationsData);
var calcArray = raw.vals;
$scope.grossEnergy = raw.vals;
var k1Array = [];
var k2Array = [];
var k3Array = [];
var k4Array = [];
var k5Array = [];
$scope.totalArray = [];
function getSum(total, num) {
    return total + num;
}
for (var i=0; i<calcArray.length; i++) {
  for (var j=0; j<(calcArray[i].usage.length)-1; j++){
      for (var k = 1; k < calcArray[i].usage[j].length; k++) {
          console.log('j', j)
          console.log('k', k)
          console.log('calcArray[j].usage[k]: ',calcArray[i].usage[j][k]);
          if(k==1){
            k1Array.push(calcArray[i].usage[j][k]);
            console.log('k1Array: ',k1Array);
          }
          if(k==2){
            k2Array.push(calcArray[i].usage[j][k]);
            console.log('k1Array: ',k2Array);
          }
          if(k==3){
            k3Array.push(calcArray[i].usage[j][k]);
            console.log('k1Array: ',k3Array);
          }
          if(k==4){
            k4Array.push(calcArray[i].usage[j][k]);
            console.log('k1Array: ',k4Array);
          }
          if(k==5){
            k5Array.push(calcArray[i].usage[j][k]);
            console.log('k1Array: ',k5Array);
          }
      }
  }
}
var col1 = k1Array.map(Number).reduce(getSum);
var col2 = k2Array.map(Number).reduce(getSum);
var col3 = k3Array.map(Number).reduce(getSum);
var col4 = k4Array.map(Number).reduce(getSum);
var col5 = k5Array.map(Number).reduce(getSum);
$scope.totalArray.push(col1);
$scope.totalArray.push(col2);
$scope.totalArray.push(col3);
$scope.totalArray.push(col4);
$scope.totalArray.push(col5);
console.log('totalArray: ',$scope.totalArray);
$scope.$apply();

}

A: You can use array#reduce to hold each sum of the column and iterate each array using array#forEach.

var data = {"vals": [{ "season": "SUMMER", "usage": [ ["PEAK", "1.000", "2.000", "3.000", "4.000", "5.000", "6.000", "7.000", "8.000", "9.000"], ["NORMAL", "10.000", "11.000", "12.000", "13.000", "14.000", "25.000", "16.000", "17.000", "18.000"], ["OFF-PEAK","19.000", "20.000", "21.000", "22.000", "23.000", "24.000", "25.000", "26.000", "27.000"] ] }, { "season": "MONSOON", "usage": [ ["PEAK", "28.000", "29.000", "30.000", "31.000", "32.000", "33.000", "34.000", "35.000", "36.000"], ["NORMAL", "37.000", "38.000","39.000", "40.000", "41.000", "42.000", "43.000", "44.000", "45.000"], ["OFF-PEAK", "46.000", "47.000", "48.000", "49.000", "50.000", "51.000", "52.000", "53.000", "54.000"] ] }, { "season": "WINTER", "usage": [ ["PEAK", "55.000", "56.000", "57.000","58.000", "58.000", "59.000", "60.000", "61.000", "62.000"], ["NORMAL", "63.000", "64.000", "65.000", "66.000", "67.000", "68.000", "69.000", "70.000", "71.000"], ["OFF-PEAK", "72.000", "73.000", "74.000", "75.000", "76.000", "77.000", "78.000", "79.000","80.000"] ] }]},
  result = data.vals.reduce((r,o) => {
    o.usage.forEach((arr) => {
      arr.slice(1).forEach((v,i) => {
        r[i] = (r[i] || 0) + +v;
      });
    });
    return r;
    },[]);
console.log(result);

A:

var data = {"vals" : [{
        "season": "SUMMER",
        "usage": [
            ["PEAK", "1.000", "2.000", "3.000", "4.000", "5.000", "6.000", "7.000", "8.000", "9.000"],
            ["NORMAL", "10.000", "11.000", "12.000", "13.000", "14.000", "25.000", "16.000", "17.000", "18.000"],
            ["OFF-PEAK", "19.000", "20.000", "21.000", "22.000", "23.000", "24.000", "25.000", "26.000", "27.000"]
        ]
    }, {
        "season": "MONSOON",
        "usage": [
            ["PEAK", "28.000", "29.000", "30.000", "31.000", "32.000", "33.000", "34.000", "35.000", "36.000"],
            ["NORMAL", "37.000", "38.000", "39.000", "40.000", "41.000", "42.000", "43.000", "44.000", "45.000"],
            ["OFF-PEAK", "46.000", "47.000", "48.000", "49.000", "50.000", "51.000", "52.000", "53.000", "54.000"]
        ]
    }, {
        "season": "WINTER",
        "usage": [
            ["PEAK", "55.000", "56.000", "57.000", "58.000", "58.000", "59.000", "60.000", "61.000", "62.000"],
            ["NORMAL", "63.000", "64.000", "65.000", "66.000", "67.000", "68.000", "69.000", "70.000", "71.000"],
            ["OFF-PEAK", "72.000", "73.000", "74.000", "75.000", "76.000", "77.000", "78.000", "79.000", "80.000"]
        ]
    }]};

var result = data.vals.reduce((r,o)=>{
 o.usage.forEach((a)=>{
  a.slice(1).forEach((v,i)=>{
   r[i] = (r[i] || 0 ) + parseFloat(v);
     });
    });
 return r;
},[]);

console.log(result);


text:
Q: Issue sending emails from Sendgrid to Oulook or Hotmail users I am currently facing an issue sending emails from sendgrid to oulook or hotmail users:

550 5.7.1 Unfortunately, messages from [XX.XX.XX.XX] weren't sent.
Please contact your Internet service provider since part of their
network is on our block list (S3140). You can also refer your provider
to http://mail.live.com/mail/troubleshooting.aspx#errors.

Sengrid support keeps saying that it is my responsability to maintain dedicated IP reputation. The thing is that this IP was added to my account some weeks ago and I am not able to build any reputation since all emails are dropped by Microsoft. Other providers like Yahoo or Google are handling correctly our emails.
Also, checking IP in block lists, it is not listed in any of SPAM lists.
Can someone help me here?
Many thanks in advance.
Best regards,
Eduardo

A: From what you've shared, it sounds like you are using a dedicated IP address. The error you're seeing is due to you sending to a Microsoft owned email servers from an IP address they are unfamiliar with. Unfortunately Microsoft tends to auto-block new IPs, not just IPs with a poor sending reputation/history.

Are you sending email from new IP addresses?
IP addresses not previously used to send email typically don't have any reputation built up in our systems. As a result, emails from new IPs are more likely to experience delivery issues. Once the IP has built a reputation for not sending spam, EOP will typically allow for a better email delivery experience.
New IPs that are added for domains that are authenticated under existing SPF records typically experience the added benefit of inheriting some of the domain's sending reputation. If your domain has a good sending reputation new IPs may experience a faster ramp up time. A new IP can expect to be fully ramped within a couple of weeks or sooner depending on volume, list accuracy, and junk email complaint rates.

I recommend completing the Hotmail Blacklist Removal form. I also highly recommend this RackAid post about troubleshooting Hotmail delivery issues, which includes this gem of a pro-tip:

Usually, within 24-48 hours, you should receive notice of their decision. Typically, you receive one of two replies:
Not qualified for mitigation
We have implemented mitigation
If you receive the not qualified response, reply to the email.  Ask for clarification as to why your IP did not qualify.  You will usually receive a response in 24-48 hours.   The response comes from a real tech who will work with you to resolve the issue.
If you IP qualifies for mitigation, you should see the Hotmail email block removed in 24 hours.

You may also want to use Microsoft's delisting portal, although I have seen the most benefit for SG users coming from using the "Hotmail" support form linked above.


text:
Q: NSMutable array count not changing after removed child GMSprite *bulletMove;
int bulletCount = [bullets count];

for(int i = 0; i < bulletCount; i++)
{
    if(bulletMove.position.x > 500)
    {
        [self removeChild:[bullets objectAtIndex:i] cleanup:YES];
    }
}

How do i remove the child from the array and also the object in the array so that bulletCount goes down an integer and adjusts the array to the removed object

A: Use
[bullets removeObjectAtIndex:i];

How do i remove the child from the array and also the object in the
  array so that bulletCount goes down an integer and adjusts the array
  to the removed object

Using the above method will remove the object from index i and all following objects will shift one-up.

A: Use below code:
[bullets removeObjectAtIndex:i];

Get bullet object from bulet array and use below code.
[bullet removeFromParentAndCleanup:YES];

A: GMSprite *bulletMove;

for(int i = 0; i < [bullets count]; )
{
    if(bulletMove.position.x > 500)
    {
        [bullets removeObjectAtIndex:i];
    } else {
        i++;
    }
}

It is not exactly good style manipulating the index varialbe of a for loop within its body. You may want to re-structure this suggestions with antother type of loop (do-while or so). The basic idea is, however, that [bullest count] will always provide you with the current amount of entries in the array. And the index must only be increased if you do not remove the current object. If you remove it an your index is at 10 (example) then the next one to be checkt is at 10 again. If you remove that too then the next one to be checked against the 500 is agein at 10. So either remove it or increase the index. And as exit criteria of the loop check the index against the current amount of objects in the array.
Edit: Second part of your question: If you do your memory management right, regardless wether you ARC or not, removeObjectAtIndex should properly remove the object itself. (Unless its retain count was higher than 1 or another strong reference still exists. But even then it reduces the retain count by 1 and does exactly the right thing.)


text:
Q: Elasticserach, search datetime field only for the time i have lot of timestamps in Elasticserach, and i want to search for every document where the field "timestamp" matches those that match 11:05 UTC. The timestamp format is
yyyy-MM-dd HH:mm:ss
and its type is "date". How can i ignore the months, days, years and seconds and only serach for the time?
Thank you in advance!
I tried to simply search with a query like
 query = {
        "query": {
            "match": {
                "timestamp": "11:05"
            }
        }
    }

 RequestError(400, 'search_phase_execution_exception', 'failed to parse date field [11:05] with format [strict_date_optional_time||epoch_millis]: [failed to parse date field [11:05] with format [strict_date_optional_time||epoch_millis]]')

Thanks in advance!

A: I have seen an answer here yesterday, somehow it got removed.
I did try the following query :

query = {
        "query": {"size": 1000,
                  "range": {
                      "timestamp": {
                          "gte": "11:05:00",
                          "lte": "20:05:59",
                          "format": "HH:mm:ss"
                      }
                  }
                  }
    }

But somehow it does not return any values, even when there are a lot of timestamp that should match.
The timestamps look like this 2022-12-01T13:46:28.146663 and the type of the timestamp is "date"


text:
Q: Validating statement hard to read I need to understand what this statement means in terms of sintaxis/structure:
defaultValue: (closureData != undefined) ? (closureColl[i]) ? [closureColl[i].collaboratorGroup + "--" + closureColl[i].collaboratorArea] : (areaFixedValue) ? [areaFixedValue] : (areaDefaultValue) ? [areaDefaultValue] : [] : []

I´m used to following sintaxis     (condition) ? 'if true' : 'if false'
What does two "?" in a row mean?

A: They are nested ternary conditional operators. Nesting ternaries in that way is generally considered very bad practice, for the very reason you are running into which is that they become extremely difficult to understand. You can improve readability somewhat with proper indentation and parenthesis use, but that line does not even have that.
Consider if you had only one ternary:
const foo = isBarTrue ? trueValue : falseValue;

But then consider if trueValue were itself, a ternary expression, since you can nest expressions pretty much arbitrarily:
const foo = isBarTrue ? (isBazTrue ? truestValue : trueValue) : falseValue;

If you removed the parenthesis, it would be even more confusing to the point of unreadability:
const foo = isBarTrue ? isBazTrue ? truestValue : trueValue : falseValue;

One convention to help with readability is to indent ternaries like so (there are some handy eslint and prettier plugins that will automatically do this for you which is nice). Basically each ? causes one new level of nesting to form, indicated by an indented line, while : symbols "close" that level of nesting and moving the next line out to the level of indentation of the last unmatched ?. It's a little confusing at first, but here it is in action:
const foo = isBarTrue
  ? isBazTrue
    ? truestValue
    : trueValue
  : falseValue;

Your given expression is even worse than my example, with what looks like four nested ternary conditional operators (you can just count up the number of ?s) which is just awful. I'll come back to edit this post shortly to see if I can help you untangle it.
Edit: to untangle this, one method is to refactor and pull out each individual ternary that has the form "a ? b : c" without any weird doubles like "x : y : z". Try to pull out ternaries that seem to make sense on their own once pulled out - sometimes its helpful to start at each "end" of the expression and alternate pulling out individual expressions. Also, re-writing it with the indentation style above can be very helpful.
If we start with this:
const defaultValue = (closureData != undefined) ? (closureColl[i]) ? [closureColl[i].collaboratorGroup + "--" + closureColl[i].collaboratorArea] : (areaFixedValue) ? [areaFixedValue] : (areaDefaultValue) ? [areaDefaultValue] : [] : [];

Try rewriting it with the indentation style:
const defaultValue = (closureData != undefined)
  ? (closureColl[i])
    ? [closureColl[i].collaboratorGroup + "--" + closureColl[i].collaboratorArea]
    : (areaFixedValue)
      ? [areaFixedValue]
      : (areaDefaultValue)
        ? [areaDefaultValue]
        : []
  : [];

Now we can rewrite it as such, pulling out the last "full" ternary which kind of makes sense on its own, (areaDefaultValue) ? [areaDefaultValue] : []. Remember to replace the expression in the original ternary with the new equivalent value:
const conditionalAreaDefaultValue = (areaDefaultValue)
 ? [areaDefaultValue]
 : [];

const defaultValue = (closureData != undefined)
  ? (closureColl[i])
    ? [closureColl[i].collaboratorGroup + "--" + closureColl[i].collaboratorArea]
    : (areaFixedValue)
      ? [areaFixedValue]
      : conditionalAreaDefaultValue
  : [];

Then, pull out the first "full" ternary, which also sorta makes sense on its own, (closureColl[i]) ? [closureColl[i].collaboratorGroup + "--" + closureColl[i].collaboratorArea] : (areaFixedValue):
const conditionalAreaDefaultValue = (areaDefaultValue)
  ? [areaDefaultValue]
  : [];

const conditionalCollValue = (closureColl[i])
  ? [closureColl[i].collaboratorGroup + "--" + closureColl[i].collaboratorArea]
  : (areaFixedValue);

const defaultValue = (closureData != undefined)
  ? conditionalCollValue
    ? [areaFixedValue]
    : conditionalAreaDefaultValue
  : [];

From here the remaining nested ternaries are a bit easier to understand, and it looks like the middle part is doing a lot of work to determine the "final" value of this expression. Let's pull that part out, conditionalCollValue ? [areaFixedValue] : conditionalAreaDefaultValue:
const conditionalAreaDefaultValue = (areaDefaultValue)
  ? [areaDefaultValue]
  : [];

const conditionalCollValue = (closureColl[i])
  ? [closureColl[i].collaboratorGroup + "--" + closureColl[i].collaboratorArea]
  : (areaFixedValue);

const conditionalFinalValue = conditionalCollValue
  ? [areaFixedValue]
  : conditionalAreaDefaultValue;

const defaultValue = (closureData != undefined)
  ? conditionalFinalValue
  : [];

There is even more refactoring you could do here, especially with naming or converting things to if statements, but I will leave that to you. Hopefully this exercise sheds some light on what the heck is going on with that expression in the first place.


text:
Q: Create a dynamic page clicking on a row from a dynamically created table Im trying to open a new page, whenever i click a row in my table.
This table was generated getting data from a database. I need whenever i click a X row from the table you get redirected to a page with detailed info of this row.
I have no idea how to redirect to a non-static webpage depending on which row i clicked, also... i need help to know which row was clicked so i know which data i should get from the database again(to show in this new page). The only thing i've tried before was redirecting using the ref tag, but in this case wont work.
My plan so far:
            <tr class ="fila" id=<? echo $row["id"] ; ?>>
            <? echo $row["nombre_disfraz"]; ?>
            <? echo $nombreregion; ?>
            <? echo $nombrecomuna; ?>
            <? echo $nombrecategoria ?>
            <? echo $nombretalla; ?>
            <? echo $row["nombre_contacto"]; ?>

Thats how i generate my table right now, each id is unique for each row... my plan is to do a javascript for the class "fila", and somehow pass the variable id from the javascript using something like this.id to php, so i can have a single webpage called details.php and i can ask for the data to database again because i have an id... is this a good plan?

A: Your plan is good, and follows a very standard pattern. It's not clear exactly what stopped you from researching and attempting it, but here's the finished article anyway:
Set a "click" event listener on all elements with the "fila" class. Then inside the handler, get the ID of the clicked element, and use JavaScript to navigate to the new page, using the ID as a querystring parameter.
Demo:

var rows = document.querySelectorAll('.fila');
rows.forEach(btn => {
  btn.addEventListener('click', function() {
    var url = "details.php?id=" + this.id;
    console.log(url);
    window.location = url;
  });
});
table {
  border-collapse: collapse;
}

td {
  border-bottom: 1px solid #cccccc;
  padding: 5px;
}

.fila:hover {
  cursor: pointer;
  background-color:#cccccc;
}

      1

      23r

      fgdfg

      g4gfg

      4gw3g>

      23rgdfgd

      2

      x

      y

      z

      a

      b

      300

      x

      y

      z

      c

      d


text:
Q: If $x_n \to 0$ and $\sigma : \mathbb{N} \to \mathbb{N}$ is a bijection, then show that $x_{\sigma (n)} \to 0$ Here's the question:

Let $(x_n)$ be a sequence. Assume that $x_n \to 0$. Let $\sigma :
 \mathbb{N} \to \mathbb{N} $ be a bijection. Define a new sequence $y_n:= x_{\sigma(n)}$. Show that $y_n \to 0$.

Here's my attempted proof:
Let $\epsilon >0$ be arbitrary. Then there exists $N\in\mathbb{N}$ such that for $n\ge N$, we have $\left| x_n \right|<\epsilon$. Now, define the set $A:=\{n\in \mathbb{N}  : \sigma(n) < N \}$. Clearly, $A$ is finite set (since $\sigma$ is a bijection and there are precisely $N-1$ elements in the set). Let $M=\max A +1$. It is evident by the definition of $(y_n)$ that for $n\ge \sigma(M)$, we have $|y_n|< \epsilon$.
Is this proof correct? What are some alternative proofs?

A: Something slightly strange has happened. I think where you say $n \geq \sigma(M)$ you just want $n \geq M$. Let's see it your way first:
Your argument
You say $M = \max A + 1$.
Then you take $n \geq \sigma(M)$.
Now $y_n = x_{\sigma(n)}$ and you want $|y_n| < \epsilon$, i.e. you want $|x_{\sigma(n)}| < \epsilon$.
This would be true if $\sigma(n) \geq N$, which is equivalent to saying $n \notin A$. But why is this true?
Proposed correction
Say $M = \max A + 1$.
Then take $n \geq M$.
Now $y_n = x_{\sigma(n)}$ and we want $|y_n| < \epsilon$, i.e. we want $|x_{\sigma(n)}| < \epsilon$.
This would be true if $\sigma(n) \geq N$, which is equivalent to saying $n \notin A$. Clearly $n \notin A$ becasue $n \geq M = \max A + 1$.

A: Nitpicking. If $N=1$ then $A=\emptyset$ and $\max A$ does not exist.
You can fix this by  saying "Then there exists $N\in \Bbb N$ such that $N>1$ and such that $\forall n\geq N\,(|x_n|<\epsilon).$"
Or you can fix this by saying "Let $M\in \Bbb N$ such that $\forall n\in A\,(M>n).$"  (which is  logical whether or not $A$ is empty, because $A$ is finite).
And in the last line you want $n>M, $ because $n>M\implies \sigma(n)\geq N\implies |x_{\sigma(n)}|<\epsilon$, as explained in the Answer from T_M.
Other than that, it's fine.
BTW. If we weaken the condition on $\sigma$ to having finite fibers,  that is, if  $\{m:f(m)=n\}$ is finite for each $n$, and without $\sigma$ necessarily being surjective, then we still have $x_{\sigma(n)}\to 0 $ because $A$ is still finite. (Although $A$ may have more than $N-1$ members.)


text:
Q: SQL IF Statement using multiple ISNULL I have the below code that is returning the order that zip codes are visited. I am able to return the zip codes correctly, but in order to make the data more user friendly I have added a dash(-) between the zip codes.
The problem comes from the fact that I cannot figure out how to eliminate the dashes for rows that only have 2 or 3 zip codes.

SELECT
    [Qry_Zip Stop Sequence].[Load ID],
    [1] AS [Stop 1], [2] AS [Stop 2], [3] AS [Stop 3],
    [4] AS [Stop 4],
    TMS_Load.[Shipped Date/Time],
    CONCAT(ISNULL([1], ''), '-', ISNULL([2], ''), '-', ISNULL([3], ''), '-', ISNULL([4], '')) AS [Zip to Zip w Stops]
FROM
    (SELECT
         [Load ID], [Sequence], [Stop Zip]
     FROM
         TMS_Load_Stops) ls
PIVOT
    (MIN([Stop Zip])
        FOR [Sequence] IN ([1], [2], [3], [4])) AS [Qry_Zip Stop Sequence]
INNER JOIN
    [TMS_Load] ON [TMS_Load].[Load ID] = [Qry_Zip Stop Sequence].[Load ID];

I would like the results to show only show the dashes between valid zip codes.
78052-45050-45201 or
73350-45220 or
84009-48009-14452 or
36521-38222-87745-95123 or
73368 or
12789-35789

A: SQL Server 2017 supports CONCAT_WS which is designed for such scenario:

CONCAT_WS ignores null values during concatenation, and does not add the separator between null values. Therefore, CONCAT_WS can cleanly handle concatenation of strings that might have "blank" values - for example, a second address field

SELECT *, CONCAT_WS('-', Stop1, Stop2, Stop3, Stop4) AS r
FROM tab

db<>fiddle demo

A: Prepend every value with a dash and remove the first dash in the resulting string -- that isn't necessarily the one from the first value -- using stuff().
stuff(concat('-' + [1],
             '-' + [2],
             '-' + [3],
             '-' + [4]),
      1,
      1,
      '')

Note: I deliberately mixed + and concat() for string concatenation here. + results in NULL when a value is NULL but concat() treats NULLs like empty strings. That way we don't need to use a lot of coalesce()s or isnull()s etc..

A: The following code will insert separators only for non-NULL values. It is assumed that columns are populated from left to right.
declare @Stops as Table ( Stop1 Char(5), Stop2 Char(5), Stop3 Char(5), Stop4 Char(5) );
insert into @Stops ( Stop1, Stop2, Stop3, Stop4 ) values
  ( '00001', null, null, null ),
  ( '00001', '00002', null, null ),
  ( '00001', '00002', '00003', null ),
  ( '00001', '00002', '00003', '00004' );

select Coalesce( Stop1, '' ) + Coalesce( '>' + Stop2, '' ) + Coalesce( '>' + Stop3, '' ) +
  Coalesce( '>' + Stop4, '' )
  from @Stops;

Aside: A separator other than dash may be less confusing in lands where ZIP+4 codes are used.


text:
Q: Samba share not seen through smbtree First Edit
I changed the hostname to a 7 characters word. The errors in log.nmbd concerning the can't-be-found server disappeared

Error - cannot find server MY-FILESERVER in workgroup WORKGROUP on
  subnet 192.168.1.143

Now I see a new error showing up :

../source3/nmbd/nmbd_browsesync.c:251(domain_master_node_status_fail)
  domain_master_node_status_fail:
  Doing a node status request to the domain master browser
  for workgroup WORKGROUP at IP 192.168.1.143 failed.
  Cannot sync browser lists.

Now, when I run smbtree from the machine itself, I can see only one share folder. Also, in log.smbd I see this line :

Samba name server IDSHARE is now a local master browser for workgroup
  WORKGROUP on subnet 192.168.1.143

I guess that the problem is that the subnet is a single IP address, instead of a group of addresses.
Initial Post
I'm configuring Samba but having a lot of trouble with it. The share machine and its shares do not appear when I run smbtree. It's the first time I encounter this problem and wasn't able to figure out the origin. So I thought some of you could share some hints ;)
On a Ubuntu 16.04, I installed Samba 4.3.9. After restarting Samba,  testparm returns the following configuration :
# Global parameters
[global]
    netbios name = MY-FILESERVER
    server string = %h server (Samba, Ubuntu)
    server role = standalone server
    security = USER
    map to guest = Bad User
    obey pam restrictions = Yes
    pam password change = Yes
    passwd program = /usr/bin/passwd %u
    passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
    unix password sync = Yes
    syslog = 0
    log file = /var/log/samba/log.%m
    max log size = 1000
    dns proxy = No
    panic action = /usr/share/samba/panic-action %d
    idmap config * : backend = tdb

[samba_test_folder]
    comment = A test Samba share
    path = /home/myname
    read only = No
    guest ok = Yes

Now, once I run smbtree from another machine, I don't see the actual machine appearing. I see some Windows machines on the LAN and another Samba server, but not the one I care about.
Error log
I inspected the logs and saw in log.nmbd the following line reappearing several times:
[2016/08/29 16:08:34.969537,  0] ../source3/nmbd/nmbd_become_lmb.c:533(become_local_master_browser)
  become_local_master_browser: Error - cannot find server MY-FILESERVER in workgroup WORKGROUP on subnet 192.168.1.143

This is the main clue I found. Could it be possible that the result of  hostname must match the netbios server ? I read that netbios only uses names with 16 or less characters (source). hostname returns a name with more than 16 characters on the machine I have problems with.
Checking running processes
I thought it could be a firewall issue but iptables -L returned an empty rules table.
I checked if the processes were listening as they should. I scanned the ports with nmap -PN 192.168.1.143 (using local IP address), giving me :
PORT    STATE SERVICE
22/tcp  open  ssh
139/tcp open  netbios-ssn
445/tcp open  microsoft-ds
MAC Address: 00:13:72:D6:5A:BA (Dell ESG Pcba Test)

I double checked on the machine itself with netstat -plunt and seemed to confirm  the fact that everything is running fine :
Proto Recv-Q  Send-Q  Local Address           Foreign Address         State       PID/Program name
tcp        0       0  0.0.0.0:139             0.0.0.0:*               LISTEN      4837/smbd
tcp        0       0  0.0.0.0:22              0.0.0.0:*               LISTEN      2335/sshd
tcp        0       0  0.0.0.0:445             0.0.0.0:*               LISTEN      4837/smbd
udp        0       0  192.168.255.255:137     0.0.0.0:*                           4789/nmbd
udp        0       0  192.168.1.143:137       0.0.0.0:*                           4789/nmbd
udp        0       0  0.0.0.0:137             0.0.0.0:*                           4789/nmbd
udp        0       0  192.168.255.255:138     0.0.0.0:*                           4789/nmbd
udp        0       0  192.168.1.143:138       0.0.0.0:*                           4789/nmbd
udp        0       0  0.0.0.0:138             0.0.0.0:*                           4789/nmbd

The machine that causes trouble has a fixed IP address and matches the MAC address reported by nmap and a single machine responds to this IP when running nmap -sP 192.168.1.0/24.
I'm far from being an expert in Samba and Linux, so I may have missed something a bit obvious.

A: It seems that Samba has troubles when a static IP is defined through network interface.
https://ubuntuforums.org/archive/index.php/t-844604.html
The interface was not well defined and after adding network 192.168.1.0 it worked as expected and the share was appearing in smbtree.


text:
Q: Canonical term for "simultaneous data-latching" I have a module (in my case on an FPGA) where several input values (registers) are updated sequentially (if at all), but are all copied in parallel in a single, atomic step to guarantee coherency during the following data processing steps.
Is there a common term for this?

*

*"Double-Buffering" comes close, but usually refers to two buffers in parallel that are swapped, while I'm actually copying them "forward".

*"Simultaneous data-latching" is what I'm using at the moment, but it sounds unfamiliar...

Illustration
               store_1             store_all             do_stuff
                  |                    |                     |
                +-+-+                +-+-+                 +-+-+
   value_1 -->  |Reg| --- int_1 -->  |Reg| --> input_1 --> | M |
                +---+                +---+                 | o |
                                       |                   | d |
               store_2                 |                   | u | --> outputs
                  |                    |                   | l |
                +-+-+                +-+-+                 | e |
   value_2 -->  |Reg| --- int_2 -->  |Reg| --> input_2 --> |   |
                +---+                +---+                 +---+

                 __  ____________________
    value_1      __><____________________

    store_1      ______|_________________

                 _______  _______________
    input_1      _______><_______________

                 __________  ____________
    value_2      __________><____________

    store_2      ______________|_________

                 _______________  _______
    input_2      _______________><_______

    store_all    ____________________|___

                 _____________________  _
    out_1        _____________________><_

                 _____________________  _
    out_2        _____________________><_

    do_stuff     _______________________|

Here store_1, store_2 and store_all are write-enable signals for their registers, are synchronously clocked with the same clock.

A: Looks like basic shift-registers to me.
This type of arrangement might be called retiming registers if there presence is purely to help ease the routing pressure to 'Module'. Or perhaps pipelining registers if they are inserted to maintain some specific alignment between 'value_1/value_2' and 'outputs', say if the latency through Module changed at some point.
If control signals store_1 / store_2 /store_all are infact clocks, they may be called synchronisation stages, although the design has problems in this case.
Your question mixes words that are tangentially related to digital logic timing, without being specific.


text:
Q: Postgresql return NULL instead of right result in function I have function like this:
CREATE OR REPLACE FUNCTION public.function_geoms()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
DECLARE
  _geom_puwg1992 GEOMETRY := NEW.geom_puwg1992;
  _srid_puwg2000 INTEGER;
BEGIN
  SELECT l.srid_puwg2000 INTO _srid_puwg2000 FROM locations l, geodesies g
    WHERE
      st_contains(l.geom_wgs84, g.geom_wgs84) AND
      g.well_id = NEW.well_id AND
      l.ancestry_depth = 1;

    RAISE NOTICE '%', _srid_puwg2000;

    IF (_geom_puwg1992 IS NOT NULL) THEN
      NEW.geom_puwg2000 := ST_TRANSFORM(_geom_puwg1992, _srid_puwg2000);
      NEW.geom_wgs84 := ST_TRANSFORM(_geom_puwg1992, 4326);
    END IF;
  RETURN NEW;
END
$BODY$;

Why raise notice returns NULL, instead of right result?
If if  run query:
SELECT l.srid_puwg2000 INTO _srid_puwg2000 FROM locations l, geodesies g
  WHERE
    st_contains(l.geom_wgs84, g.geom_wgs84) AND
    g.well_id = NEW.well_id AND
    l.ancestry_depth = 1;

it returns right result.
PostgreSQL 13
Best regards.


text:
Q: What is the better way of extracting values between  tags using BeautifulSoup? I've the following HTML which I'm scrapping using BeautifulSoup.

        North America

        USA

        NYC

I want to extract and structure it like
{continent: 'North America', country: 'USA', city: 'NYC'}

I'm using the following method:
table = soup.find('table')
table.tbody.tr.td.text

And it gives me this:
u'\nNorth America\n\nUSA\n\nNYC\n'

Well this output is fine but I'm looking for some better way of solving it.

A: BeautifulSoup sits on top of lxml. Use lxml:

This code will work even if you remove those
 tags.

from lxml import html

text = """

        North America

        USA

        NYC

"""

tree = html.fromstring(text)

results = list()
for item in tree.xpath('//tr/td//text()'):
    [results.append(x.strip()) for x in item.split('\n') if x.strip() not in ""]

print results

Output:
['North America', 'USA', 'NYC']

And if you want a dictionary just:
print dict(continent=results[0], country=results[1], city=results[2])

Output:
{'city': 'NYC', 'continent': 'North America', 'country': 'USA'}

A: First of all, you should install lxml and use BeautifulSoup with it: BeautifulSoup(data, 'lxml'). See this for more information. It'll allow to fix incorrect
 tag. After that everything should work fine:
from bs4 import BeautifulSoup

data = '''

        North America

        USA

        NYC

'''

soup = BeautifulSoup(data, 'lxml')

contents = soup.table.tbody.tr.td.contents
res = {
    'continent': contents[0].strip(),
    'country': contents[2].strip(),
    'city': contents[5].text.strip()
}

print(res)
# {'country': 'USA', 'continent': 'North America', 'city': 'NYC'}


text:
Q: I am facing certain difficulties in running my smartadmin theme in angular 2 I have brought SmartAdmin Theme for development of my project,It worked great with Angularjs but when i try to run it for Angular2 it shows lot of errors.I have screen shots attached for the issue,take a look and let me know.
Thank you.

This is my package.json:
 {
  "name": "smartadmin",
  "version": "0.1.9",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "start": "ng serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "2.0.1",
    "@angular/compiler": "2.0.1",
    "@angular/core": "2.0.1",
    "@angular/forms": "2.0.1",
    "@angular/http": "2.0.1",
    "@angular/platform-browser": "2.0.1",
    "@angular/platform-browser-dynamic": "2.0.1",
    "@angular/router": "3.0.1",
    "X-editable": "github:vitalets/x-editable",
    "bootstrap": "^3.3.7",
    "bootstrap-colorpicker": "^2.3.5",
    "bootstrap-duallistbox": "github:istvan-ujjmeszaros/bootstrap-duallistbox",
    "bootstrap-markdown": "^2.10.0",
    "bootstrap-progressbar": "^0.9.0",
    "bootstrap-slider": "^9.1.3",
    "bootstrap-tagsinput": "^0.7.1",
    "bootstrap-timepicker": "^0.5.2",
    "chart.js": "2.3.0",
    "ckeditor": "^4.5.10",
    "clockpicker": "0.0.7",
    "clone": "^1.0.2",
    "core-js": "^2.4.1",
    "debounce": "^1.0.0",
    "dropzone": "^4.3.0",
    "dygraphs": "^1.1.1",
    "fuelux": "^3.15.8",
    "he": "^1.1.0",
    "highcharts": "^4.2.7",
    "ion-rangeslider": "^2.1.4",
    "jquery": "^2.2.4",
    "jquery-color": "^1.0.0",
    "jquery-jcrop": "^0.9.13",
    "jquery-knob": "^1.2.11",
    "jquery-ui-npm": "^1.12.0",
    "jquery-validation": "^1.15.1",
    "jquery.maskedinput": "^1.4.1",
    "jvectormap": "^2.0.4",
    "markdown": "^0.5.0",
    "morris.js": "^0.5.0",
    "ng2-bootstrap": "^1.1.5",
    "ng2-popover": "git+https://github.com/griga/ng2-popover.git",
    "ng2-redux": "^4.0.0-beta.0",
    "nouislider": "^8.5.1",
    "raphael": "^2.2.1",
    "redux": "^3.6.0",
    "rxjs": "5.0.0-beta.12",
    "scriptjs": "^2.5.8",
    "select2": "^4.0.3",
    "smartadmin-plugins": "^1.0.13",
    "summernote": "^0.8.1",
    "to-markdown": "^3.0.1",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.6.23"
  },
  "devDependencies": {
    "@types/jasmine": "^2.2.30",
    "angular-cli": "1.0.0-beta.15",
    "codelyzer": "~0.0.26",
    "expose-loader": "^0.7.1",
    "imports-loader": "^0.6.5",
    "jasmine-core": "2.5.1",
    "jasmine-spec-reporter": "2.7.0",
    "karma": "1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "4.0.9",
    "script-loader": "^0.7.0",
    "ts-node": "1.2.1",
    "tslint": "3.13.0",
    "typescript": "2.0.2"
  }
}

A: Update your Angular dependencies. First, change these lines in package.json:
"dependencies": {
"@angular/common": "^2.4.9",
"@angular/compiler": "^2.4.9",
"@angular/core": "^2.4.9",
"@angular/forms": "^2.4.9",
"@angular/http": "^2.4.9",
"@angular/platform-browser": "^2.4.9",
"@angular/platform-browser-dynamic": "^2.4.9",
"@angular/router": "^3.4.9",

Notice both the new version numbers and the caret (^), which roughly indicates "or later".
Then run npm install --save
I reckon you will probably get a couple of messages about unmet peer dependencies. For each of the listed packages, simply run npm install --save theListedPackage.
A handful of attempts later, all should be well.


text:
Q: browser not interpreting html template I have one function in a very small Go application that does a query to a database, retrieves some data and inserts it in the template (main.html). the data is getting inserted into the template (see image), however the html is not being interpreted by the browser (Chrome and Firefox). My browsers are otherwise working fine.  Is there something that I'm not doing correct with the template?
func Root(w http.ResponseWriter, r *http.Request) {

    t := template.Must(template.New("main").ParseFiles("main.html"))
    rows, err := db.Query("SELECT title, author, description FROM books")
    PanicIf(err)
    defer rows.Close()

    books := []Book{}

    for rows.Next() {
        b := Book{}
        err := rows.Scan(&b.Title, &b.Author, &b.Description)
        PanicIf(err)
        books = append(books, b)
    }
    t.ExecuteTemplate(w, "main.html", books)

}

main.html

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">

    Title
    Author
    Description

{{ range . }}

    {{.Title}}
    {{.Author}}
    {{.Description}}

{{ end }}

A: Most likely you are doing import "text/template" and should be doing import "html/template", but the other answer will also fix it for you.

A: You need to set the content type, although it's rather weird it didn't automatically set it for you.
w.Header().Set("Content-Type", "text/html; charset=utf-8")
t.ExecuteTemplate(w, "main.html", books)

//edit
Also for correctness sake, you should add <!DOCTYPE html> to the top of your template, not related to the problem though.


text:
Q: Under what circumstances is it a good idea to re-index tables every night? I have inherited a number of SQL Server 2005 and 2008 systems (all running in Simple recovery mode) that each currently do the following things each night from an SQL Agent task:

*

*Backup

*Shrink

*Reindex

I have stopped the shrink from happening as this is likely to be causing more problems than it is solving. (The usage of the server is to store a consistent amount of information on a rolling 5 day basis, so the space from deleted rows will be used again for fresh information without much growth).
However, I do not know whether I should also stop the nightly re-index job. It was necessary when the shrink was active because of the massive index fragmentation that shrinking causes. I cannot find much information on the internet suggesting when a nightly re-index might be sensible. Should I disable this too?

A: If the information is rolling that indicates that there is a large portion, roughly 20%, of the total DB being inserted every day.  This indicates that your stats and your indexes are 20% wrong.
That sounds like exactly the conditions you should be re-indexing for.

A: Basically, your shrink and reindex were simply undoing each other (the shrink fragments tables to recover space, then the reindex uses extra space to defragment tables).
So since you've removed the shrink, you probably can remove the nightly reindex as well.  (Still probably advisable to have a weekly full reindex, in most cases.)
But given the rolling 5-days of data, you might actually be ok with NO REINDEXES at all on those rolling tables (depending on exactly how the clustered index is configured). Here's what I mean:
Assuming you do inserts only (no updates), and the clustered index is either on the date/time, or just a perpetually increasing numeric value, the internal table arrangement might look something like:
[  Day 1  ][  Day 2  ][  Day 3  ][  Day 4  ][  Day 5  ][  Empty  ]

On day 6, you delete the data from day 1, and insert the data from day 6:
[  Empty  ][  Day 2  ][  Day 3  ][  Day 4  ][  Day 5  ][  Day 6  ]

and the same pattern continues, re-using the recently-freed space:
[  Empty  ][  Day 2  ][  Day 3  ][  Day 4  ][  Day 5  ][  Day 6  ]
[  Day 7  ][  Empty  ][  Day 3  ][  Day 4  ][  Day 5  ][  Day 6  ]
[  Day 7  ][  Day 8  ][  Empty  ][  Day 4  ][  Day 5  ][  Day 6  ]
[  Day 7  ][  Day 8  ][  Day 9  ][  Empty  ][  Day 5  ][  Day 6  ]

To know for sure if this is what is happening, I would use SQL's table fragmentation queries (dm_db_index_physical_stats) after a final reindex,then turning off the reindexes for several days. If the fragmentation numbers are very low, then this is probably what is going on. If they are high, then this probably isn't an accurate picture, and you might need to reinstate your reindexes.


text:
Q: .NET: why store Sync Block in every object? In .NET, why is lock(someObject) implemented the way it is? The way I see it, there were two options to store synchronization info:

*

*Global hashtable to map memory address -> synchronization info

*Store pointer or index to synchronization info inside every object that could possibly be locked.

In the first implementation, there is no memory overhead for objects that are not locked - they do not get any hashtable entries. However, .NET uses the second implementation, storing a Sync Block Index field in the header of every single .NET object - even those that are never locked.
What is the motivation behind this choice? What scenarios is this optimized for?

A: The CLR has one header word for the synchronization info and other things such as the object identity hash code. It's a multi-purpose field.
But still, your argument is valid: This could be implemented using a global hash table. This would decrease memory and object creation cost for most objects and increase locking and identity hash code costs. I could see this making sense but it's workload dependent.
Also, from the linked article it looks like COM and MarshalByRefObject information is stored there as well. Maybe this forces this data to be included in the object header for performance reasons. For example, each method call on a MarshalByRefObject has some overhead to check for remoted objects. Maybe someone with actual knowledge can comment/answer on this idea.
More subjectively, I think being able to lock every object is bad design in the first place. Likely, this was only kept for Java compatibility. The whole MarshalByRefObject idea is a total design failure as well. (COM interop is OK.)

A: Apart from the difficulty of getting synchronization right when doing multithreaded programming, another challenge has been the performance overhead of creating the synchronization primitives. Before the .NET framework introduced its monitors with the per-object synchronization info blocks, locking meant creating and obtaining a kernel-mode primitive (critical section or mutex).
The performance boost of each object always having a synch block outweighs the little extra memory overhead. So it's a speed vs. space tradeoff.


text:
Q: Arguments not being passed correctly to Test::MockObject method I'm working on setting up a test script in Perl. I'm using Test::MockObject to create a mock object which will hold some configuration data. The configuration in the live program comes from an INI file, i.e. it has the format
[SECTION]
KEY = VALUE

As such, I've set up the following:
use Test::MockObject;
use Data::Dumper qw(Dumper);

use constant SECTION_NAME => 'section';
use constant KEY_NAME => 'key';
use constant VALUE_NAME => 'value';

my $com_mock = Test::MockObject->new();

$com_mock->mock( 'getIniVar', sub {
   my $self = shift;
   my ( $section, $key ) = @_;
   print STDERR "\$_[0] = '" . Dumper( $_[0] ) ." '\n";
   print STDERR "\$_[1] = '" . Dumper( $_[1] ) ." '\n";
   my %iniVar = ( SECTION_NAME => { KEY_NAME => VALUE_NAME } );
   return( $iniVar{$section}->{$key} );
} );

$self->{com} = $com_mock;

Later, I actually call the mocked function:
print STDERR
      "\$self->{com}->getIniVar( 'section', 'key') = '"
    . $self->{com}->getIniVar( SECTION_NAME,KEY_NAME )
    . "'\n";

When I run the test, I see the following:
ok 1 - use Appriss::ImageExtraction3::Config;
$_[0] = '$VAR1 = 'section';
 '
$_[1] = '$VAR1 = 'key';
 '
Use of uninitialized value in concatenation (.) or string at t/config/config.pm line 159.
$self->{com}->getIniVar( 'section', 'key') = ''
$_[0] = '$VAR1 = undef;
 '
$_[1] = '$VAR1 = 'key';
 '

The first time that the mock object is called is during
use_ok 'Appriss::ImageExtraction3::Config';

This seems to have all of the arguments that I want, but I'm not explicitly calling that, so I don't know what's happening there. The second time is when I explicitly call it using
$self->{com}->getIniVar( SECTION_NAME,KEY_NAME )

(Shown above)... and at this point, the first argument is set to undef... why?

A: This line looks suspicious:
my ( $section, $key ) = @_;

As I understand, the first argument should be the mock object itself.
As for P.S., you can run t/*.t files individually:
% perl -Ilib -d t/13-unlucky.t


text:
Q: Spring Security with Spring Boot I am trying to create a Spring Boot REST application. When I deploy my application, it authentication is required and it is asking me for user name and password. How can I bypass this or how can I add a user name and password for authentication?
Do I need to remove security entry in pom?
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

A: If you don't want to use authentication at all, you should remove the dependency:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

See Spring Boot Reference Guide:

If Spring Security is on the classpath then web applications will be secure by default with 'basic' authentication on all HTTP endpoints.

A: No need of removing security from pom.xml. In your project, you can try something like below. Try to create SecurityConfig which will extend WebSecurityConfigurerAdapter and provide some user name and password and later you can customize it.
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user")
                    .password("user")
                    .roles("USER")
                    .and()
                .withUser("user2")
                    .password("secret2")
                    .roles("USER");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().fullyAuthenticated();
        http
            .httpBasic();
        http
            .csrf().disable();
    }
}

public @interface EnableWebMvcSecurity {

}

A: Apart from other two answers -  default username is 'user' and password will be printed in the console each time you start your server like below -
2019-08-31 23:58:16.417  INFO 12528 --- [  restartedMain] .s.s.UserDetailsServiceAutoConfiguration :

Using generated security password: 1ab46edf-332a-42de-ae11-70dc138c65db

Simply use these credentials to login.
Note - If you fine-tune your logging configuration, ensure that the org.springframework.boot.autoconfigure.security category is set to log INFO-level messages. Otherwise, the default password is not printed.

A: if you wish to configure a username/password of your choice then you can do so in application.properties file.
spring.security.user.name=username
spring.security.user.password=password
Now spring security will not generate a new password each time you boot the application.
Note: When using postman to send requests, go to authorization> select "basic auth"> Enter the username and password so authentication details can be sent along with each request. If using browser, there should be a login page.


text:
Q: Prove that $\lim_{h\to 0} \frac{g(a+h)-2g(a)+g(a-h)}{h^2} = g''(a)$ How do I prove that
$$\displaystyle\lim_{h\to0} \dfrac{g(a+h)-2g(a)+g(a-h)}{h^2} = g''(a),$$
where $g$ is of class $C^2$?
My attempt:
By Mean Value Theorem, there are $c_0\in (a-h, a)$ and $c_1\in(a, a+h)$ such that
$$g(a)-g(a-h) = g'(c_0)\cdot  h$$
$$g(a+h)-g(a) = g'(c_1)\cdot  h$$
Then
$\displaystyle\lim_{h\to0} \dfrac{g(a+h)-2g(a)+g(a-h)}{h^2} = \displaystyle\lim_{h\to0} \dfrac{g(a+h)-g(a)-(g(a)-g(a-h))}{h^2} = \\
\displaystyle\lim_{h\to0} \dfrac{g'(c_1)-g'(c_0)}{h}=
\displaystyle\lim_{h\to0} \dfrac{g'(c_1)-g'(c_0)}{c_1-c_0}\cdot\dfrac{c_1-c_0}{h}=\\
\displaystyle\lim_{h\to0} \dfrac{g'(c_1)-g'(c_0)}{c_1-c_0}\cdot\displaystyle\lim_{h\to0}\dfrac{c_1-c_0}
{h}
$
The first limit is equals to $g''(a)$. Then the second limit should be equals to $1$, but I can't see why.

A: If we know $g''(x)$ exists for an open interval $I$ containing $a$, $$\lim_{h\to0} \frac{g(a+h)-2g(a)+g(a-h)}{h^2}=\lim_{h\to0} \frac{g'(a+h)-g'(a-h)}{2h}
=\displaystyle\lim_{h\to0} \frac{g'(a+h)-g'(a)+g'(a)-g'(a-h)}{2h} =g''(a)
$$, by L'Hopital Rule

A: By Taylor's expansion

*

*$g(a+h)=g(a)+g'(a)h+\frac12g''(a)h^2+o(h^2)$

*$g(a-h)=g(a)-g'(a)h+\frac12g''(a)h^2+o(h^2)$

and adding up
$$g''(a)=\frac{g(a+h)-2g(a)+g(a-h)}{h^2}+\frac{o(h^2)}{h^2}$$
then take the limit.

A: \begin{align*}
g(a+h)&=g(a)+g'(a)h+\dfrac{1}{2}g''(\xi_{h})h^{2}\\
g(a-h)&=g(a)-g'(a)h+\dfrac{1}{2}g''(\eta_{h})h^{2},
\end{align*}
where $\xi_{h}$ lies in between $a$ and $a+h$, and $\eta_{h}$ lies in between $a$ and $a-h$, so
\begin{align*}
\dfrac{1}{h^{2}}[g(a+h)+g(x-h)-2g(a)]=\dfrac{1}{2}(g''(\xi_{h})+g''(\eta_{h}))\rightarrow\dfrac{1}{2}(g''(a)+g''(a))=g''(a)
\end{align*}
by the continuity of $g''$.

A: Note that
$$\dfrac{g(a+h)-2g(a)+g(a-h)}{h^2} =\dfrac{\dfrac{g(a+h)-g(a)}{h} -\dfrac{g(a)-g(a-h)}{h}}{h},$$
so that quotient is basically the slope of $g'$ at $x=a$ for $h$ very small.


text:
Q: Incorporating bash scripts into an R package? Background
I am writing an R package to support reproducible research. At this point, the workflow is mostly held together by bash scripts, and I can run an analysis by sending a single command like ./runscript.sh. I use bash for the following:

*

*file manipulation tar, rsync, 'rename'

*running bash files locally and via ssh

*running R scripts using R --vanilla that in turn call R functions

*find and replace text within files using sed

*submitting jobs via qsub
It seems to me that it would be much more efficient (cleaner and easier) to execute the entire workflow from an R function or R script. I am partial to R since I am more familiar with it and mostly work within emacs ESS.
Questions

*

*Would it be worthwhile to encapsulate all of these uses of bash within R using the system and files functions?

*Are there other R packages that I have not yet found that would be helpful for doing this?
Notes
Following Al3xa's answer, I realize that it is important to note that the speed penalty of using eg. R vs bash versions of tar and gsub on 1000-2000 files would likely be less than the current rate limiting steps in the workflow: computations by JAGS (~10-20min) and FORTRAN (>4hrs)

A: Well, there are functions like tar, gsub etc. Anyway, I guess you're willing to create a crossplatform solution. You should prefer bash for the sake of speed, and use R only for R-specific functions. I don't find it useful to wrap all system-based commands within system and/or file.*... it would be much slower... If you're using Linux, I suggest littler over Rscript interface.

A: I'm a big fan of using R as your "integrated" environment vs. bash scripts. I'm in the process of moving all of my bash and ruby scripts to Rscript as I need to make changes to them.
There are only a couple of reasons not to move everything into R that come to mind. I'm referring mainly to using Rscript to accomplish this
1) Speed, which from my testing is a moderate impact in any situation I've come across, and would be trivial relative to the times you mentioned.
2) Portability, in that paths to Rscript, etc. may be different across systems. I've had no problems writing things on OS X and moving them to a Linux server, but might break on Windows.
The advantages in my book are:
1) Much easier for me to write. I don't have to switch back and forth between the slight idiosyncrasies with things like conditional statements and for loops.
2) More forgiving. I can't describe how much time I've spent trying to get bash scripts to work because I accidentally had a space where I shouldn't have. R is much nicer in that regard (yes, of course, we should all follow conventions in R perfectly, but I'd rather that it not stall me up for hours if I don't).
3) I do better work. For tar a file it doesn't matter, but I find I do better text manipulation in R vs. awk/sed for example.
Re: packages that are helpful -- This doesn't exist, to my knowledge, but I'd love a version of make that's based on R. make's syntax is one of the most inflexible out there (tabs vs spaces? really?) - I'd love to write an R-based alternative. Some day, I will...


text:
Q: How to shift from one distro's grub to another's I installed Ubuntu 14.04(say ubuntu-1) and set it with another Ubuntu 14.04(say ubuntu-2). Now everytime I boot my PC I see the grub boot menu from Ubuntu-2 but I want it to start from Ubuntu-1's grub. I have no idea how to do it.

A: You need to boot into whichever one's grub you want to use and reinstall its GRUB. For example, boot into Ubuntu-2 and then run:
sudo grub-install /dev/sda

Note that the above assumes you want your GRUB to be on /dev/sda. You should change that to whichever drive you want to install it on.


text:
Q: Ruby on rails mysql problem I'm creating my first ROR application.
Details:
creating new app ->
rails new simple_cms -d mysql

creating a controller and a corresponding view -->
rails generate controller demo index

Then when after i started the rails server, the http://localhost:3000 page works perfectly fine. but when i try to go to the page that I just created, http://localhost:3000/demo/index, it spurts out a MYSQL error:
Access denied for user 'root'@'localhost' (using password: NO)

At first, I think it's just a database connection problem, so I've gone through the MYSQL interface and create a new database called: simple_cms_development
and I have also made a corresponding user: simple_cms
with granted privileges.
and lastly, I have configured the database.yml file to fit the details:
development:
  adapter: mysql
  encoding: utf8
  reconnect: false
  database: simple_cms_development
  pool: 5
  username: simple_cms
  password: developer
  host: localhost

But still, it spits out the same mysql problem:
Access denied for user 'root'@'localhost' (using password: NO)
Please. to anyone who knows how to use mysql as a database for rails app..A help would be really appreciated. Thank you so much!
UPDATE: This is all what's inside on the database.yml file
# MySQL.  Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
#   gem install mysql2
#
# And be sure to use new-style password hashing:
#   http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
  adapter: mysql
  encoding: utf8
  reconnect: false
  database: simple_cms_development
  pool: 5
  username: root
  password: developer
  host: localhost

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: simple_cms_test
  pool: 5
  username: root
  password:
  host: localhost

production:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: simple_cms_production
  pool: 5
  username: root
  password:
  host: localhost

A: Only reason that can cause your issue is that you are loading your server with different environment. I think that in your case you are loading your server under production mode.

A: I found that you need to add the following line to config/database.yml:
host: localhost
production:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  host: your_host # <----- normally localhost
  database: the_db_I_made
  pool: 5
  username: the_user_I_made
  password: the_password
  socket: /var/lib/mysql/mysql.sock


text:
Q: Sendgrid change href of link I am using Nodejs with Express and I am sending an email through Sendgrid, but Sendgrid is changing the href link
var emailText = '<!DOCTYPE html><meta charset="UTF-8">Here'
var from_email = new helper.Email('contact@test.com');
var to_email = new helper.Email('contact@test2.com');
var subject = 'Test';
var content = new helper.Content("text/html", emailText)
var mail = new helper.Mail(from_email, subject, to_email, content);
var request = sg.emptyRequest({
    method: 'POST',
    path: '/v3/mail/send',
    body: mail.toJSON(),
});
sg.API(request, function(error, response) {
    if (error) {
        console.log('Error response received');
    }
    console.log(response.statusCode);
    console.log(response.body);
    console.log(response.headers);
});

When the email arrives the following link appears:
https://u4006412.ct.sendgrid.net/wf/click?upn=rOQ9fjZGp5r0JyNfoC02LbL.....
Could someone help me solve this problem?

A: Similar to @israa-saifullah said, you can state clicktracking="off" directly in an html link, but if you're sending through the sg api, there is a trackingSettings property that you can set on an individual message where you can specify if you want click and open-tracking enabled. clickTracking is what re-writes your URL's, and you can specify it at the HTML or Text based level. For example this disables all tracking and therefore leaves the URL's in the email untouched.
const msg = {
 to: TO_ADDRESSS,
 from: {
   name: FROM_NAME,
   email: FROM_ADDRESSS,
 },
 subject: SUBJECT,
 text: TEXT_VERSION,
 html: HTML_VERSION,
 trackingSettings: {
  clickTracking: {
    enable: false,
    enableText: false
  },
  openTracking: {
    enable: false
  }
}

This is helpful if you don't want to override tracking at the account level (in the SG Dashboard), but just for a specific use case.
Documentation here.

A: I believe this is caused by the URL click-tracking feature of sendgrid. It will redirect to your intended resource, but does not look pretty. You can turn it off in sendgrid, but it will disable URL tracking on all emails sent by that account. If you are integrating with a 3rd-party link-tracker such as bit.ly or have your GA on lock-down, this may not bother you.
Here's more information on the feature in sendgrid: https://sendgrid.com/docs/User_Guide/Settings/tracking.html
Turn that off and see how your emails look.
UPDATE: Whitelabeling in Sendgrid
Sendgrid also has a whitelabeling feature, allowing you to serve URLs from one of your subdomains while still tracking clicks/opens through their servers. If you are concerned about the prettiness of your links or perceived security from a UX perspective, this may be the way to go.
Check out their overview of whitelabeling and
link whitelabeling doc pages. Be sure to follow sendgrid's recommendations on domain usage in emails. This ensures a high success rate on delivery.

A: You can off the Sendgrid tracking for one link specifically.
To do so, You have to add clicktracking="off" before your href tag
Do it like this
My Site

A: It is possible to change through the sendgrid settings, access the path: settingns -> tracking -> click tracking -> disabled


text:
Q: How to covert simple (flat) array to multi-dimensional (2D) arrays I have following code in the Perl language:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my $DF = "/usr/bin/df -Pk"; # HP-UX
my @temp = split /\n/, `$DF`;
shift @temp;
print Dumper \@temp;

And the output is something as below (shorter for better readability):
$VAR1 = [
          '/dev/vg00/lvol6       114224    46304    67920    41%     /home',
          '/dev/vg00/lvol7       8340704  4336752  4003952   52%     /opt',
          '/dev/vg00/lvol4       520952    35080   485872     7%     /tmp',
        ];

I want to converting the @temp array (or create a new array) to multi-dimensional (array of arrays) like this:
$VAR1 = [
          ['/dev/vg00/lvol6', 114224, 46304, 67920, '41%', '/home'],
          ['/dev/vg00/lvol7', 8340704, 4336752, 4003952, '52%', '/opt'],
          ['/dev/vg00/lvol4', 520952, 35080, 485872, '7%', '/tmp'],
        ];

Anyone help? Thanks in advance! :)

A: @temp = map [ split ], @temp ;

A: This is how I would do it
my @lines = `$DF`;
my @data  = map { [split] } @lines;
print Dumper \@data;

This is assuming that there is no unexpected whitespace in a path


text:
Q: URL image in GridView I am trying to create a gridview and load some images from URLs to this gridview but there is an issue in loading images but i can't find it, can anyone help ?
package com.images;
import java.io.InputStream;
import java.net.URL;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.coboltforge.slidemenuexample.MainActivity;
import com.coboltforge.slidemenuexample.R;

public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    // Keep all Images in array
    public Integer[] mThumbIds = new Integer [27];

    // Constructor
    public ImageAdapter(Context c) {
        mContext = c;
    }

    @Override
    public int getCount() {
        return mThumbIds.length;
    }

    @Override
    public Object getItem(int position) {
        return mThumbIds[position];
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        /*
         * ImageView imageView = new ImageView(mContext);
         * imageView.setImageResource(mThumbIds[position]);
         * imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
         * imageView.setLayoutParams(new GridView.LayoutParams(130, 130));
         * return imageView;
         */
        ImageView imageView;
        if (convertView == null) {
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
            imageView.setAdjustViewBounds(false);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }
        for (int i = 0; i < MainActivity.presentersImages.size(); i++) {
            imageView
                    .setImageDrawable(LoadImageFromWebOperations(MainActivity.presentersImages
                            .get(i) + position));

        }
        return imageView;
    }

    protected Drawable LoadImageFromWebOperations(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        } catch (Exception e) {
            System.exit(0);
            return null;
        }
    }
}

MainActivity.presentersImages is an ArrayList of strings contains the url for the images

A: check below link and download the sample application it will help You
https://github.com/nostra13/Android-Universal-Image-Loader


text:
Q: How to know current max job_id value in Oracle as a non-dba user? I have connected to oracle11g as a non-dba user. I need to create a new Oracle Job. In my job creation query I need to set a unique 'job_id' that do not conflict with existing dbms_jobs. My plan is to select job_ids from entire dbms_jobs so that from the result set i can decide my job_id is existing or not.
But as a non dba user i couldn't query dbms_jobs (from sys.job$).
What should I do?

A: Jobs are created by a user, so query USER_JOBS. This has all the jobs for this user.
Equally, as a DBA user you should not be querying JOB$, use DBA_JOBS.
In 11g, DBMS_JOB is only provided "for backwards compatability". There's now the much more powerful DBMS_SCHEDULER instead.
However, the premise of your question appears to be flawed. You've written:

In my job creation query I need to set a unique 'job_id' that do not
  conflict with existing dbms_jobs. My plan is to select job_ids from
  entire dbms_jobs so that from the result set i can decide my job_id is
  existing or not

The job ID in DMBS_JOB.SUBMIT() is an OUT parameter. You do not assign this, the package does if for you.
declare

   l_job_id number;

begin

   dbms_job.submit( l_job_id, what => ... );

end;


text:
Q: Are these two for loops the same efficient in python? d = {'a':1, 'b':2, 'c':3}

keys = list(d)

for key in keys:
    print(key)

for key in list(d):
    print(key)

My question is for the 2nd for loop, is 'list(d)' executed multiple times, or only once? If it is executed only once, it's more compact.

A: Here's a simple test:
d = {'a':1, 'b':2, 'c':3}

def _list(*args, **kwargs):
    print("Calling list!")
    return list(*args, **kwargs)

for key in _list(d):
    print(key)

And the output is
Calling list!
a
b
c

It seems that list(d) is only called once, so there's no performance difference.

A: list(d) are an Iterable. What you're doing is requesting access directly to that iterator component, and then moving the pointer that it's behind it on every loop run.
Note that the for loop is almost a syntactic sugar for iter.__next__(), which gives you a mutable shared reference to an item inside the continer on every call.
But when you're assigning it to your keys variable, you're copying the whole content on list(d) call to some memory location, so yes, assigning it could be more expensive depending on how big is the content to copy.


text:
Q: PHP Remove Everything After Character and Stop Before Character My string:
$string = '/my-picture-gallery-1000x2000.jpg';

I need to remove everything after the last occurrence of "-" (including "-") in the string and stop at the "." in the string.
So the output should read as:

/my-picture-gallery.jpg

but I need it to stop and keep everything after the "."

A: Should be able to use PHP's strstr in-built function in combination with str_replace to get the result you're after
$string = '/my-picture-gallery-1000x2000.jpg';
echo str_replace(strrchr($string, '-'), '', $string) . strstr($string, '.');

That would leave you with:

/my-picture-gallery.jpg

Slightly more readable version
$string = '/my-picture-gallery-1000x2000.jpg';

$dimensions = strrchr($string, '-');
$extension = strrchr($string, '.');

$image = str_replace($dimensions, '', $string) . $extension;

A: $string = '/my-picture-gallery-1000x2000.jpg';
echo substr($string,0,strrpos($string,'-')) . substr($string,strrpos($string,'.'));

A: you can use explode() function. It returns array of strings. Just choose part or parts of string and combine them in one string.
More about explode() function at: http://php.net/manual/en/function.explode.php

A: Try this :
$string = '/my-picture-gallery-1000x2000.jpg';

$ext= strstr($string, '.');
$dash=strrpos($string,'-');

$filename= substr($string, 0 ,$dash);

echo $filename.$ext;

In a short form , you can use :
$filename = substr($string, 0 ,strrpos($string,'-')).strstr($string, '.');

A: if(false !== $pos = strrpos($string, '-'))
  $s = substr($string, 0, $pos);

First check if the needle is in the heystack using the reverse search. Then get the string from start up to the found position.
According to your edit a regular expression would be appropriate. This has also the advantage that it can handle UTF8 file pathes.
$new_name = preg_match('~^(.*)-[^-.]*(\..*)$~u', $string, $matches)
  ? $matches[1].$matches[2]
  : $string
;


text:
Q: Can we add attribute(i.e. id/class) on any div which is inside the
A: A script element contains CDATA, it cannot have child elements (< does not mean "start of tag" inside it (except when that tag is </script>)).
If you want to perform DOM manipulation of the contents of your template, then you must first parse the template into a DOM.
var template = $('#template').text();
var $template = $(template);
$template.addClass('hello');
alert($template.wrap('

').parent().html());

A: Why don't you render the template to the dom and then add the class.
Edit:
Please note that your code doesn't work even if the div is inside a normal html tag.
Please refer this fiddle:
http://jsfiddle.net/shyamchandranmec/R7g3S/
$('#foo').contents().find('#bar').addClass('fb');
$("#foo").find("#bar").addClass('foobar');

foo bar

The class fb wont be added to the div #bar.


text:
Q: LINQ on indexed result of previous query gives error "could not be translated" I was trying to add an index on the result set that LINQ was giving me and I was successful in doing so. I'll not go in deep about why indexing I'm doing as the major reason being the nature of data that I'm dealing with is having redundancy and I need to work with it.
Not much into the LINQ but i have managed to get through the problem statement that i have. Now i'm having following doubts.

*

*Whether im putting index on the record properly ?

*Do i need to align query ? i mean the sequence of predicates that i have used in query ?

*It seems to be neat query then why still it is giving error as :
could not be translated. Either rewrite the query in a form that can be translated, or
switch to client evaluation explicitly by inserting a call to 'AsEnumerable',
'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?
linkid=2101038 for more information.
Heres my query :
dbEmployees = await _dbContext.Employees
                                        .AsNoTracking()
                                        .OrderBy(x => x.EmployeeName)
                                        .ThenBy(x => x.EmployeeCode)
                                        .ThenBy(x => x.BadgeNumber)
                                        .ThenBy(x => x.StartDate)
                                        .ThenBy(x => x.SignOnTime)
                                        .Where(x => x.UnitCode == "BU" && x.DepartmentId == 1)
                                        .Select((item, employeeIndex) => new
                                        {
                                            EmployeeIndex = employeeIndex + 1,
                                            item
                                        })
                                        .Where(x => x.EmployeeIndex >= employeeIndexPointer)
                                        .Select(x => x.item)
                                        .Take(10)
                                        .ToListAsync();

Any help or pointers are welcomed.

A: You will need to use LINQ to Object (instead of LINQ to SQL) if operating on IEnumerable<T>
Notice the .AsEnumerable() right before our .Where() statement, this will transform the result set from IQueryable<T> to IEnumerable<T>
var dbEmployees = await _dbContext.Employees
    .AsNoTracking()
    .OrderBy(x => x.EmployeeName)
    .ThenBy(x => x.EmployeeCode)
    .ThenBy(x => x.BadgeNumber)
    .ThenBy(x => x.StartDate)
    .ThenBy(x => x.SignOnTime)
    .AsEnumerable()
    .Where(x => x.UnitCode == "BU" && x.DepartmentId == 1)
    .Select((item, employeeIndex) => new
    {
        EmployeeIndex = employeeIndex + 1,
        item
        })
    .Where(x => x.EmployeeIndex >= employeeIndexPointer)
    .Select(x => x.item)
    .Take(10)
    .ToListAsync();

Read a bit more here: Are Linq to SQL and Linq to Objects queries the same?


text:
Q: issues with DATETIME in database I have devised the following code; to calculate the waiting time and expected time for a patient. The code should also echo a warning if the patient has been waiting too long.
Please note: Waiting_time is DATETIME in the database.
Here is the code;
<?php

$conn = mysqli_connect("localhost","root","") or die ("No connection");
mysqli_select_db($conn, "a&e") or die('Could not select database.');

$query = "SELECT PatientID, Forename, Surname, Gender, Illness, Priority, Arrival_time,NOW() as now,ABS(TIMEDIFF(NOW(), Arrival_time)) as Waiting_Time FROM Patient";
$result = mysqli_query($conn, $query) or die("Invalid query");

echo "

PatientID
Forename
Surname
Gender
Illness
Priority
Waiting Time

";

while ($row = $result->fetch_object()){

//Select the  expected and discharge time for this patient.
  $query2 = "SELECT Abs(TIMEDIFF(Expected_Time,'00:00:00')) as Expected,Abs(TIMEDIFF(Discharge_Time,'00:00:00')) as Discharge ".
                "FROM priority_time ".
                "WHERE Illness = '".$row->Illness."'".
                    " AND Priority = '".$row->Priority."'".
                ";";

    $result2 = mysqli_query($conn, $query2) or die("Invalid statement: ".$query2);

    $row2 = $result2->fetch_object();
    $expected =  $row2->Expected;

    $discharge  = $row2->Discharge;
    echo "expected-> ".$expected." discharge-> ".$discharge;

    if($expected > $discharge){
        echo "There is a problem with the database consistency, expectedTime must be less than dischargeTime!";
    }
    //Set the patient color.
    if($row->Waiting_Time <  $expected && $row->Waiting_Time <  $discharge){
        echo "
";
    }
    if($row->Waiting_Time >=  $expected && $row->Waiting_Time <  $discharge){
        echo '
';
    }
    if($row->Waiting_Time >  $expected && $row->Waiting_Time >  $discharge){
        echo '
';
    }

    //Print patient info
     echo
      "" . $row->PatientID . "
      " . $row->Forename . "
      " . $row->Surname . "
      " . $row->Gender . "
      " . $row->Illness . "
      " . $row->Priority . "
      " . $row->Waiting_Time . "(".$expected."-".$discharge.") 	";

    //Close row
    echo "
";

}

echo "
";
mysqli_close($conn);
?>

EDIT:
On each row, in the column Waiting Time it is showing the waiting time in seconds, and in brackets the currentTime a minus and the arrival time, just for checking. How do I convert the waiting time to the format hh:mm:ss to have a better representation for the user?
Showing;
Waiting time
01:15:42(10500.000000-10500.000000)

Why is it displaying (10500.000000-10500.000000)?

A: Try this:
gmdate("H:i:s", $seconds)

If that doesn't work, have a look at How to convert seconds to time format?
Update:
To do this in the SQL statement try something like this:
SELECT TIME_TO_SEC(TIMEDIFF('2013-03-27 12:00:00', '2013-03-27 10:00:00')) diff;

So something like this:
SELECT PatientID
, Forename
, Surname
, Gender
, Illness
, Priority
, Arrival_time
, NOW() as now
, TIME_TO_SEC(TIMEDIFF(NOW(), Arrival_time)) as Waiting_Time
FROM Patient;

Then you would change this line:
" . $row->Waiting_Time . "(".$expected."-".$discharge.")

to this:
" . gmdate("H:i:s", $row->Waiting_Time) . "(".$expected."-".$discharge.")

A: When dealing with dates and times in php strtotime() is your biggest friend. Lucky the date() function is all you need for this. Something that is going to convert seconds to a readable format could be the following.
$time = strtotime('now');
echo $time . '
';
$var =  date('H:i:s',$time);
echo $var;


text:
Q: Unable to install Yellowbrick or Pipenv on Conda on Windows: infinite package conflicts I have recently installed Anaconda3 on my Windows machine. I need to install Yellowbrick and followed their instructions on the quickstart page. Conda is not on my system's PATH, according to installation instructions.
From the anaconda prompt, I tried to install yellowbrick but it never goes beyond the 'solving environment' part. I ran the installer command with the --debug flag and it seems to be pointing conflicts on every single of the 408 dependencies associated with it. I set the channel priority as strict according to this answer and nothing changed.
When I try to install yellowbrick (through pip) on my Linux machine, it works without a problem.
I have tried to install plotly the same way and it worked. However, pipenv has the same problems, and it never goes past the 'solving environment` step either.
I tried it on two different machines and the result is the same. One runs Windows 10, the other Windows 11. Please help as I'm clueless what to do next.
EDIT: Error output below.
Collecting package metadata (current_repodata.json): done Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source. Collecting package metadata (repodata.json): done Solving environment: / Found conflicts! Looking for incompatible packages. This can take several minutes.  Press CTRL-C to abort.
The "several minutes" mentioned turned into a whole night and counting.

A: My guess is that you are trying to install Yellowbrick in the base Anaconda installation.  That almost never goes well because of the huge number of packages already in the base environment.  You should create a new environment using Conda and install Yellowbrick in there.
First open the Anaconda Prompt from the Windows Start Menu.  Then use the following commands:
First we create a new environment with the packages we want.  The environment is name "myenv".  You can change that to whatever you want.  Here we are asking for pandas, yellowbrick, and umap-learn.  All of the dependencies (python, numpy, ect) will be solved by Conda.
conda create -n myenv pandas conda-forge::yellowbrick conda-forge::umap-learn -y

After that finishes, we activate the environment and run all your code from within it.
conda activate myenv

If you want additional packages, such as Jupyter notebooks, you can install them using Conda.
conda install -n myenv jupyter