text:
Q: disabling individual items in knockout-sortable In knockout-sortable, I know that you can disable a sortable list using isEnabled in the sortable binding.  I also know you can disable moving items using cancelDrop in a beforeMove function.  The problem is, isEnabled disables the whole list, and cancelDrop can only be called after the item is already dragged and dropped onto another sortable.
Is there a way to disable sortable's click/drag behavior on certain contained items?

A: You can use the jQuery UI sortable options items or cancel for this purpose. Docs here: http://jqueryui.com/sortable/#items.
You would add them in a binding like:
<div class="container" data-bind="sortable: { data: tasks, options: { cancel: '.prevent' } }">

or globally like:
ko.bindingHandlers.sortable.options.cancel = ".prevent";

Sample here: http://jsfiddle.net/rniemeyer/2wEX3/


text:
Q: netsh causes syntax error in Win8 I create a .bat file for change network using netsh:
netsh interface ip set address name=Wireless source=static addr=192.168.43.100 mask=255.255.255.0 gateway=192.168.43.1

In Windows-7 work fine, but in Windows-8+ not work and return this error:

The syntax of the command is incorrect

How use netsh command for change IP address in Windows-8?

Note: I run the BAT file as Admin

redpajama_set_name: RedPajamaStackExchange


text:
Q: AWK Unexpected token error I came up with the below script to list out calls which take longer than  10000000 microseconds (ServiceDuration in our logs has value logged in microseconds) from the server log file which stores all calls coming to the service.
servicedurationlimit.awk
#!/bin/sh
dir1=$1/*.log

# for each log file in the input dir
for file1 in $dir1
do
        echo $file1":"
        awk  '/#BeginLogEntry|ServiceDuration/ {
                #get slow running service's information
                if ($1 == "#BeginLogEntry")
                {
                        split($0, a, "\t");
                        servinfo=a[3]" ServiceAt:"a[2];
                } else {
                        getline;
                        if ($0 > 10000000)
                        {
                                print servinfo", ServDur:"$0
                        }
                }
        }' $file1
done

On running the script I get below error:
./servicedurationlimit.awk /path/to/server/logs/
./servicedurationlimit.awk: line 12: syntax error near unexpected token `$0,'
./servicedurationlimit.awk: line 12: `                  split($0, a, "\t"); '

Can you please help me understand what could be causing this?
Below is the sample log file (which has 2 log entries):
#BeginLogEntry  04.13 20:11:11.671  BROWSE_ALL
@Properties LocalData
IsJson=1
UserTimeZone=utc
@end
@IdcRSet AuditProps
2
auditPropertyKey
auditPropertyValue
ServiceDuration
62818
ServiceStartTime
{ts '2015-04-13 20:11:11.671'}
@end
#EndLogEntry    04.13 20:11:11.671  BROWSE_ALL
#BeginLogEntry  04.13 21:12:11.671  BROWSE_SOME
@Properties LocalData
IsJson=1
UserTimeZone=utc
@end
@IdcRSet AuditProps
2
auditPropertyKey
auditPropertyValue
ServiceDuration
162818123
ServiceStartTime
{ts '2015-04-13 21:12:11.671'}
@end
#EndLogEntry    04.13 21:12:11.671  BROWSE_SOME

Below is the output I am expecting after running the script on log file containing above log entries.
BROWSE_SOME ServiceAt:04.13 21:12:11.671, ServDur: 162818123

awk Version information
$ awk --version
GNU Awk 3.1.5

A: I am running GNU Awk 4.0.2 and your code gives this error on my box:
awk: cmd. line:2:       #get slow running services
awk: cmd. line:2:       ^ syntax error
./test.sh: line 11: syntax error near unexpected token `$0,'
./test.sh: line 11: `        split($0, a, "\t");'

However I believe you just need to remove the ' single quote from your comment:
#get slow running service's


text:
Q: Check if two values are either in a dictionary as a key or in a list I am not sure how to write a logic in the most pythonic way.
I have 2 data types:
d: Dict[str, Any] = {} l: List[str]: []
Now I want to write a condition where I check if at least one of the strings is in either the dictionary(as a key) or in list. I am not sure how to do that in the most pythonic way.
I could obviously write:
if 'str_1' in d.keys() or 'str_2' id d.keys():
     return True
elif 'str_1' in l or 'str_2' id l:
    return True

I am struggling to come up with a way to write this elegantly in a Pythonic way, preferably to have it in one line.

A: Perhaps something like this:
any(item in coll_ for coll_ in (l, d) for item in ('str_1','str_2'))

A: use a ternary expression like this:

l=["a","c"]
d={'b':'yes'}

key = 'b'
result = True if key in d or key in l else False

Clarification
The above is the equivalent of:
result = key in d or key in l

In a ternary expression you are not forced to return boolean.


text:
Q: How do I cast on an update? The data field is set to vchar(4) and I would like to cast it as an int This is what I have come up with so far but I am getting a syntax error
   update t_Provider set(CAST(f_Postnr as int)) = '66886' where f_Name= 'Test1'

A: By your question, I assume column f_Postnr is a NVARCHAR(4).
You cannot insert data into this column with a greater character length then 4.
Any solution would require you to edit the column length.

A: Please look at the syntax for an update in MSDN..
The left hand side of the assignment has to be a known memory location (variable or column/field).  What you are doing is trying to set and expression (unknown location) to a constant and filter by a where clause.
Use this code to do what you want.
-- Code from user
update t_Provider
set f_Postnr = 66886
where f_Name= 'Test1'

Why not pass the constant in the update without stating it as a string ''?  That's what the above snippet does.  This assumes f_Postnr is a INT which can easily handle a 66K number (domain constraint).
If you use '66886', SQL Server will implicit cast the string to an integer if there are no errors.
Here is a huge chart for MSDN on implicit casting matrix.
I hope this helps with your future TSQL endeavors!

A: What about using...
UPDATE t_Provider
SET f_Postnr = CAST('66886' AS INT)
WHERE f_Name = 'Test1'


text:
Q: Me el siguiente error saleWarning: move_uploaded_file(): Unable to move Estoy creando una interfaz en el que pueda subir los datos de un producto dentro de una base de datos en xampp, también estoy intentando añadir la dirección de la imagen, sin embargo me sale error cuando intento enviar los datos, se guardan bien, incluso la dirección de la imagen a la que debería de ser guardada, sin embargo me sale el error y la avisa de que la imagen no se ha movido.
aqui el codigo
<?php
require 'conexionproduct.php';

$producto=$_POST['nombreproduct'];
$categ=$_POST['categoria'];
$subcateg=$_POST['subcategoria'];
$prec=$_POST['precio'];
$stoc=$_POST['stock'];
$descrip=$_POST['descripcion'];
$imagen='';
if(isset($_FILES["imagenproduct"])){
    $file=$_FILES["imagenproduct"];
    $nombre=$file["name"];
    $tipo=$file["type"];
    $ruta_provisional=$file["tmp_name"];
    $size=$file["size"];
    $dimensiones=getimagesize($ruta_provisional);
    $witdh = $dimensiones[0];
    $height = $dimensiones[1];
    $carpeta = "images/";
    if($tipo != 'image/jpg' && $tipo != 'image/JPG' && $tipo != 'image/jpeg'
    && $tipo != 'image/png' && $tipo != 'image/gif'){
        echo "El archivo no es una imagen";
    }else if ($size > 3*1024*1024){
        echo "Error: Imagen muy grande";
    }else{
        $src = $carpeta.$nombre;
        move_uploaded_file($ruta_provisional, $src);
        $imagen="images/".$nombre;
    }
}

$query=mysqli_query($conexion, "INSERT INTO producto (id_categoria,nom_produc,precio,stock,descripcion,id_subcategoria,foto) VALUES ('$categ','$producto','$prec','$stoc','$descrip','$subcateg','$imagen')");

?>


text:
Q: How to combine or merge multiple values inside the single array? I have an array values. Inside the array some multiple data but how to combine or merge these multiple records.
some values inside the single array are  multiples . How to merge these ?
    Array
    (
    [0] => plxliupp
    [1] => plxliupp
    [2] => dg_w12
    [3] => col4312
    [4] => Iphone6s
    [5] => Ndry_milk
    [6] => smj7
    [7] => ovn 02 o3
    [8] => allwin6406f
    )

After remove multiples values. array like this
    Array
    (
    [0] => plxliupp
    [1] => dg_w12
    [2] => col4312
    [3] => Iphone6s
    [4] => Ndry_milk
    [5] => smj7
    [6] => ovn 02 o3
    [7] => allwin6406f
    )

thanks for answering

A: $array = array("a" => "moon", "star", "b" => "moon", "star", "sky");

// Deleting the duplicate items
$result = array_unique($array);
print_r($result);


text:
Q: plugin.media erro Estou tentando utilizar o Media Plugin for Xamarin and Windows com o Visual Studio Community 2017. Um aplicativo android que deverá ter a capacidade de tirar algumas fotos.
Segui as seguintes orientações:
Em Resources, adicionou uma pasta chamada 'xml' e dentro dela criei um arquivo por nome file_paths.xml com o seguinte código:
 <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
      <files-path name="my_images" path="images/"/>
      <files-path name="my_docs" path="docs/"/>
    </paths>

Em seguida, abri o arquivo AndroidManifest.xml e adicionei o seguinte código:
<application android:label="ReporOnLine.Android">
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
      <meta-data
          android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/file_paths" />
    </provider>
    </application>

No arquivo AssemblyInfo.cs adicionei:
[assembly: UsesFeature("android.hardware.camera", Required = false)]
[assembly: UsesFeature("android.hardware.camera.autofocus", Required = false)]

Quando tento depurar o aplicativo usando o Genymotion com Google Nexus 4 - 5.0.0 API 21, ou meno no meu smartphone, gera o erro conforme imagem em anexo.
Agradeço se alguém puder me ajudar.

A: Substitui a seguinte linha:
android:authorities="${applicationId}.fileprovider"

por
android:authorities="com.companyname.ReporOnLine.fileprovider"

Limpei a solução e recompilei, tudo funcionou perfeitamente.


text:
Q: php loop through json, differing property names I'm not to comfortable with json, and there has to be an easier way of doing what I am doing.
Here is a sample of the json feed I'm working with.
"goalie": [
    {
        "position": "Goalie",
        "id": 8476945,
        "weight": 207,
        "height": "6' 4\"",
        "imageUrl": "http://3.cdn.nhle.com/photos/mugs/8476945.jpg",
        "birthplace": "Commerce, MI, USA",
        "age": 22,
        "name": "Connor Hellebuyck",
        "birthdate": "May 19, 1993",
        "number": 30
    }
],
"defensemen": [
    {
        "position": "Defenseman",
        "id": 8470834,
        "weight": 260,
        "height": "6' 5\"",
        "imageUrl": "http://2.cdn.nhle.com/photos/mugs/8470834.jpg",
        "birthplace": "Roseau, MN, USA",
        "age": 30,
        "name": "Dustin Byfuglien",
        "birthdate": "March 27, 1985",
        "number": 33
    }
]

There is a lot more data than shown above, multiple goalies, defensemen and forwards. Currently I'm using a for loop to loop through goalies, then another one to loop through defensemen and so on. Is there a way to loop through every player regardless of the property name, not sure if that's the right term... if not please correct me.
Thanks

A: Yes there is! In PHP, looping over objects ( or associative arrays, or dictionaries ) is done in the same way as looping over arrays ( indexed arrays, or lists ). So nested looping is your friend. Let's say your huge data structure was saved to a variable called $everyone
<?php
    foreach ($everyone as $playergroup => $players) {
        foreach ($players as $player) {
            // now you can operate on each player
        }
    }
?>


text:
Q: How to evaluate limits Let $f$ be a continuously differentiable function on $\mathbb R$. Suppose that $L=\lim\limits_{x\to \infty}(f(x)+f^{'}(x))$ exists. If $0<L<\infty$, and if $\lim\limits_{x\to \infty} f^{'}(x)$ exists then, can it be proved that $\lim\limits_{x\to \infty} f^{'}(x)=0$?
Let $(x_n)$ be a sequence diverges to $\infty$. Then $f(x_n)+f^{'}(x_n)\to L$.  After that I could not proceed. Please help!

A: In broad strokes, the ideas are:
Since $\lim_{x\to\infty}f'(x)$ and $\lim_{x\to\infty}(f(x)+f'(x))$ exist and are finite, then
$\lim_{x\to\infty}f(x)$ exists and is finite. This implies $\lim_{x\to\infty}f'(x)=0$.

A: If $\lim_{x\to \infty} f'(x) = C \neq 0$ then there is a point $x_0$ for which $$|f'(x) - C| < C/4$$ for all $x > x_0$. Without loss of generality assume that $C>0$. Hence $$f(x) = f(x_0) + \int_{x_0}^x f'(x) dx > f(x_0) + \int_{x_0}^x \frac34 C dx = f(x_0) + \frac34 C (x-x_0).$$
Since $\lim_{x\to\infty} ( f(x) + f'(x) ) = L$ exists and $\lim_{x\to\infty} f'(x)$ also exists, this means that $\lim_{x\to\infty} f(x)$ exists. Also since the limits are both finite, so is the limit of $f(x)$.
However, from our above inequality we have $\lim_{x\to\infty} f(x) = \infty$. This is a contradiction.


text:
Q: Change view with AlertAction I would like to change of ViewController when I click on "OK" button of my AlertAction but I have an error

Thread 1: signal SIGABRT "Receiver () has no segue with identifier 'NextQuestion'

Here is my code : Code on error
Can you help me please ? If you want more codes, don't hesitate. :)
Thanks !

A: You need to create a segue from your current vc to the destination one and name it NextQuestion


text:
Q: How to get parent object based upon key from child map in MongoRepository JAVA SpringBoot This is how my object looks.
@Document("parent")
public class Parent {
    @Id
    private String id;
    private String field-1;
    private Map<String,Long> someMap;
}

{
    "_id" : "parent-id",
    "field-1" : "some value",
    "someMap" : {
        "category-5" : 123,
        "category-4" : 456
    }
}

I want to get this entire object when i search with "category-5" or "category-4". I am using MongoRepository and SpringBoot.

I tried following approach but its not working for me
public interface ParentRepo extends MongoRepository<Parent, String> {

    @Query("{someMap :{$in: [?0]}}")
    List<Parent> findBySomeMap(String id);
}

or if anyone can help me to convert this into MongoRepository/@Query method that would be great and much appreciated
Goal here is to pass CategoryId as a parameter to query
db.getCollection('parentCollection').find({"someMap.category-4" : {$exists:true}})

This method returns expected results

A: package com.somepackage.services;

import org.springframework.stereotype.Service;
import java.util.List;
import com.yourpackagestructure.Parent;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

@Service
public class Service{

   private MongoTemplate mongoTemplate;

   public Service(MongoTemplate mongoTemplate){
    this.mongoTemplate = mongoTemplate;
   }

   public List<Parent> getParentList(String mapKey){
    Query query = new Query();
    query.addCriteria(Criteria.where("someMap." + mapKey).exists(true));
    List<Parent> parents = mongoTemplate.find(query,Parent.class);
   }
}


text:
Q: Бесконечная загрузка callback (inline) кнопок в vk_api При нажатии на кнопку идёт бесконечная загрузка и не появляется show_snackbar сообщение.
Пробовал на пк и телефоне.

kb.py
from vk_api.keyboard import VkKeyboard, VkKeyboardColor

inln = VkKeyboard(one_time=False, inline=True)

inln.add_callback_button(label='Покажи pop-up сообщение',
                               color=VkKeyboardColor.SECONDARY,
                               payload={"type": "show_snackbar", "text": "привет"})

main.py
import vk_api
from vk_api.longpoll import VkEventType, VkLongPoll

def send(pk, text = None, keyboard = None, sticker_id = None):
    vk.method('messages.send',
             {'user_id': pk[0],
             'message': text,
             'keyboard': keyboard,
             'random_id': 0,
             'sticker_id': sticker_id})

def main():
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW and event.to_me and event.from_user:
            msg = event.text.lower()
            id = event.user_id
            domain = vk.method('users.get',
                              {'user_ids': id,
                               'fields': 'domain'})[0]["domain"]
            pk = [id, domain, msg]
            if msg == "inline":
                send(pk, "тест", kb.inln.get_keyboard())

Long Poll API - 5.131 | Python - 3.9.2

Как я понял, не я один столкнулся с такой проблемой. В поисках решения нашёл много людей с таким
же казусом, но разным кодом


text:
Q: Free products of two or copies of a group Could someone describes the elements of the free product of two (or three...) copies of the finite cyclic group $\mathbb{Z}/N\mathbb{Z}$.
Are they words over $\mathbb{Z}/N\mathbb{Z}$ ? Do you allow $0$ (I mean the neutral element of $\mathbb{Z}/N\mathbb{Z}$) in these words?
What is the difference from the free product of two and the free product of three copies then?
You may see I'm lost...
Thank you...

A: Let $a$ be a generator of the first copy of $\mathbb{Z}/N\mathbb{Z}$ and $b$ be a generator of the second copy.
An element in the free product of the two groups is then a word of the form $a^{i_1}b^{k_1}a^{i_2}b^{k_2}\cdots a^{i_m}b^{k_m}$ for some $m$ and with the $i_j$ and $k_j$ between $0$ and $N-1$. If we further only allow $i_1$ and $k_m$ to be $0$, any element has a unique representation of this form.
The important thing to note is that we need to distinguish the generators coming from the two groups, so if we included a third copy, we would have to introduce a third generator as well.

A: They are words over the disjoint union of two (or three) copies of the set of nonzero elements of $\mathbb Z/n\mathbb Z$, with the additional restriction that two neighboring symbols must not come from the same of the two (or three) copies.
In the case of two factors, once we know whether the first symbol is from one factor or the other, the additional restriction makes it unambiguous which one each of the following symbols come from, so in that case the elements of the group are almost just words of nonzero elements of the original group (but plus information about whether it is first-factor-first or second-factor-first). With more than two factors this becomes unworkable and you need to fall back on the "neighboring symbols must not come from the same copy" rule.


text:
Q: AngularJs : triggering an event to simulate user action when unit testing a directive I have seen that in order to simulate user action on the DOM generated by a directive, there are two approaches, both trigering an event:
How to trigger ng-change in directive test in AngularJS
The first approach uses jquery and the second one a function called browserTrigger defined in angular-scenario.js. The second one is supposed to be better as jquery would have a bug on event triggering (which I believe, I am not arguing :) ).
Using the angular-scenario means e2e testing for me. but I have seen egghead video  and he seems to do unit testing. How is this possible ?
I guess he just copied the function ?
I think I am going to test directives as e2e tests, it makes more sense as unit test is more fore pure functions.

Well, I just found that browserTrigger is something internal not supposed to be used directly : https://github.com/angular/angular.js/issues/5178

Thanks!

A: As of 1.3.15 you can use triggerHandler to trigger a event as shown below,
it('should click the element',function(){
    element.triggerHandler('click') ;
    expect($scope.clicked).toBe(true);
});

A: simple and it works, example, in  unit test env:
spyOn(self, 'updateTransactionPrice');

var el = compile('<form name="form" latest novalidate json-schema="main.schema_discount" json-schema-model="main._data"><input type="text" ng-model="main._data.reverse_discount" ng-class="{ \'form-invalid\': form.reverse_discount.$invalid }" ng-change="main.transactionPrice(form);" name="reverse_discount" class="form-control-basic" placeholder="" ng-disabled="!main.selectedProduct.total_price"></form>')(scope);
el.find('input').triggerHandler('change');

expect(self.updateTransactionPrice).toHaveBeenCalled();


text:
Q: WebCryptoAPI - Does it support signing with cryptographic tokens? I would like to be able to sign data on the browser using 100% JavaScript and cryptographic token based keys.
From what I have seen so far, all old implementations of this functionality are being discontinued (e.g. even new ActiveXObject("CAPICOM.Store"); doesn't seem to work in IE11 any more since it throws an error! - I don't know if I am missing something... Perhaps because I run it in the Console window...).
I have looked into the specs of the WebCryptoAPI (that is supposed to be the be the new supported way):
http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-sign
...and then at this (which is more clear, organized and helpful):
http://msdn.microsoft.com/en-us/library/ie/dn302332(v=vs.85).aspx
...and I saw that it allows you to create new keys (generateKey), but I am not sure if it supports using keys from tokens. There is an importKey but from the description it seems that is not what I need in order to sign with an existing key that the OS can see.
Does this web-standard aim at allowing that kind of functionality? Can I use it as it is now and achieve my goal?
Can I do anything better at least in Firefox that has a device manager (Options->Certifivates->Security Devices)?
Related questions:
Accessing signing/encryption in a browser's Keystore using JavaScript - sample code? (WebCryptoAPI)
js signature on chrome with OS keystore
UPDATE:
I have also found this PDF:
http://webpki.org/papers/PKI/x509-webcrypto-extension-scheme.pdf
From what I have seen, there is no window.crypto.subtle.KeyStore in any of the browsers, so I guess this is wild dreams that people have for the distant future...
UPDATE2:
This was the reason I couldn't load the ActiveX in IE11: https://stackoverflow.com/a/5157766/2173353
So, at least, there is one old way still working...

A: No, currently not. Hardware or software tokens of the user are still unavailable. See the comment for Eugene (on the question) for slightly more information.


text:
Q: Difference between Ctrl K + D and Ctrl E + D What is the difference between the Visual Studio 2010 shortcuts Ctrl E + D and Ctrl K + D?

A: Visual Studio WITH C# KEY BINDINGS
To answer the specific question, in C# you are likely to be using the C# keyboard mapping scheme, which will use these hotkeys by default:
Ctrl+E, Ctrl+D to format the entire document.
Ctrl+E, Ctrl+F to format the selection.
You can change these in Tools > Options > Environment -> Keyboard (either by selecting a different "keyboard mapping scheme", or binding individual keys to the commands "Edit.FormatDocument" and "Edit.FormatSelection").
If you have not chosen to use the C# keyboard mapping scheme, then you may find the key shortcuts are different. For example, if you are not using the C# bindings, the keys are likely to be:
Ctrl + K + D (Entire document)
Ctrl + K + F (Selection only)
To find out which key bindings apply in YOUR copy of Visual Studio, look in the Edit > Advanced menu - the keys are displayed to the right of the menu items, so it's easy to discover what they are on your system.


text:
Q: What happens if a Python object is unbound? import queue, threading

def getFromQueue(myQueue):
    while True:
        print(myQueue.get())

def putInQueue(myQueue):
    while True:
        putString=... #code that provides values
        myQueue.put(putString)

for msg in msgList:
    myQueue=queue.Queue()
    threading.Thread( target=getFromQueue, args=(myQueue, ) ).start()
    threading.Thread( target=putInQueue, args=(myQueue, ) ).start()

My goal is to have each pair of (getFromQueue and putInQueue) threads in a loop to share one unique queue.  When I reassign myQueue to a new Queue Object, what happens to the old Queue object?  Does each thread still use the original queue object that was passed when I spawned the thread or do all the existing threads get updated to point the new/latest one and all share a single Queue Object?

A: Each instance of Queue gets two more references to it before the global myQueue is assigned a new value: the myQueue parameter to getFromQueue and the myQueue parameter to putInQueue. An object is only destroyed once the last reference to an object is unbound.
The only effect on the previous instance of Queue as the result of the new assignment myQueue = queue.Queue() is that its reference count will decrease from 3 to 2.
Once both threads executing the functions for a given instance of Queue have exited, then that instance can be collected. The first thread that exits will result in the reference count decreasing from 2 to 1 when the local myQueue goes out of scope; the second will result in the reference count decreasing from 1 to 0.


text:
Q: kong needs to start after cassandra, but cassandra is slow to actually accept connections so kong fails to start I am setting up kong as an API gateway.  It requires cassandra.
I am using Centos 7, and I created systemd unit file for each with kong starting after cassandra, and requiring cassandra.
Here are my unit files.
Kong:
[Unit]
Description=Kong API Gateway
After=network.target
After=cassandra.service
Requires=cassandra.service

[Service]
ExecStart=/usr/local/bin/kong start
ExecStop=/usr/local/bin/kong stop
ExecReload=/usr/local/bin/kong reload
Type=forking
PIDFile=/usr/local/kong/kong.pid

[Install]
WantedBy=default.target

Cassandra:
[Unit]
Description=Cassandra DB
After=network.target

[Service]
ExecStart=/opt/apache-cassandra-2.1.11/bin/cassandra -p /run/cassandra.pid
ExecStop=/usr/bin/kill $(cat /run/cassandra.pid)
Type=forking
PIDFile=/run/cassandra.pid

[Install]
WantedBy=default.target

Kong always fails due to cassandra not accepting connections yet.  Cassandra creates it's pid file, which appears to be what systemd uses to know that it's up, but it doesn't start listening for connections for several seconds.
Is there a good systemd way to make this work?
One of my ideas was to create a separate script for kong that would wait for the cassandra TCP port to be listening before starting.
If cassandra would either not fork until it's actually ready, or not create the pid file until it's actually ready, I think that would fix it.

A: You can use an ExecStartPost= directive in the cassandra.service that will wait until Cassandra is allowing connections.  This will delay the Cassandra "start" event and therefore delay Kong starting.
@Gregory came up with:
ExecStartPost=/bin/bash -c 'for i in `seq 1 100`; do \
        if lsof -Pi :5671 -sTCP:LISTEN &>/dev/null; then \
            exit 0; \
        fi; \
        sleep 0.1; \
    done; \
    exit 1'


text:
Q: Delete lines in a txt file using VBScript in Indusoft Web Studio I am a student and working on a project using Indusoft Web Studio.
I have been using IWS for about 6 mouths but I have only used VBScript for about 2 weeks.
I need to Delete all Lines that contains the word "DELETE" in a txt file.
I have found this method and fixed it to do what I want but I can not get it to work.
The file I am trying to edit in are also used by IWS, I am trying to get IWS to let go of the file by giving IWS another file instead, but I do not know if this works. This is what I do in the first and last line of the code.
Is my VBScript wrong or do I need to look elsewhere for my error source?.
Side note the code with $ in front is IWS function or variables.
$TextGridName = "PlayListTemp.txt"

Dim strFileTemp, strFileRecipe , objFS , objTextFile , objFS1 , objTextFile2 , DeleteWord

strFileTemp = $GetAppPath() & "temp.txt"
strFileRecipe = $GetAppPath() & "PlayList.txt"

DeleteWord = "DELETE"

Set objFS = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFS.OpenTextFile(strFileRecipe)
Set objFS1 = objFS.CreateTextFile(strFileTemp,True)
objFS1.close
Set objTextFile2 = objFS.OpenTextFile(strFileTemp,8)

Do Until objTextFile.AtEndOfStream
    strLine = objTextFile.ReadLine
    If InStr(strLine,DeleteWord)> 0 Then
        strLine = Replace(strLine,DeleteWord,1)
      Else
    objTextFile2.writeline strLine
    End If

Loop

Set objTextFile = Nothing
Set objTextFile2 = Nothing

objFS.copyFile strFileTemp , strFileRecipe , True
objfs.DeleteFile strFileTemp

Set objfs = Nothing
Set objfs1 = Nothing

$TextGridName = "PlayList.txt"

I have tried to not Delete the Temp file, to see if it creates one, but it looks like I do not do that neither.
Can you Help me?
Thanks to Bond this is my new code (i mean Thanks :) )
$TextGridName = "PlayListTemp.txt"

Dim strFileTemp, strFileRecipe , objFS , objTextFile , objFS1 , objTextFile2 , DeleteWord , strLine

strFileTemp = $GetAppPath() & "temp.txt"
strFileRecipe = $GetAppPath() & "PlayList.txt"

DeleteWord = "DELETE"

Set objFS = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFS.OpenTextFile(strFileRecipe)
Set objTextFile2 = objFS.CreateTextFile(strFileTemp, True)

Do Until objTextFile.AtEndOfStream
    strLine = objTextFile.ReadLine
    If InStr(strLine, DeleteWord) = 0 Then
       objTextFile2.WriteLine strLine
    End If
Loop

objTextFile2.Close
objTextFile.Close

Set objTextFile = Nothing
Set objTextFile2 = Nothing

objFS.copyFile strFileTemp , strFileRecipe , True
objfs.DeleteFile strFileTemp

Set objfs = Nothing
Set objfs1 = Nothing

$TextGridName = "PlayList.txt"

the output file looks like this
਍਍吀䔀匀吀㄀Ⰰ㘀 ഀഀ
਍吀䔀匀吀㄀Ⰰ㘀 ഀ
഍ഀ
DELETE,60
਍ഀ

all this is written in one line in the txt file
each time it runs it on an empty txt file it adds a ਍
how can I fix this?

A: Looks like we've got a few issues here...
1. Set objFS = CreateObject("Scripting.FileSystemObject")
2. Set objTextFile = objFS.OpenTextFile(strFileRecipe)
3. Set objFS1 = objFS.CreateTextFile(strFileTemp,True)
4. objFS1.close
5. Set objTextFile2 = objFS.OpenTextFile(strFileTemp,8)

Line 1: Looks good.
Line 2: Open the file in "read" mode by passing 1 as the 2nd param.
Line 3 - 5: It looks like you're trying to create a new output file? Just use:
Set objTextFile2 = objFS.CreateTextFile(strFileTemp, True) and remove lines 3-5.
Then, in your loop, you can say:
If InStr(strLine, DeleteWord) = 0 Then
    ' Word not found on this line. Write line to new temp file.
    objTextFile2.WriteLine strLine
End If

Don't forget to close both files:
objTextFile2.Close
objTextFile.Close


text:
Q: Retirar dois valores de um arquivo de texto Preciso retirar dois números de um arquivo de texto, e adicioná-los a duas variáveis (X e Y).
Estou tentando usar o CSV mas não estou conseguindo.
with open('circulo.plt','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=' ')

Aqui está um exemplo da tabela:
PW0.350,5;
PW0.350,6;
PW0.350,7;
PW0.350,8;
LT;
SP1;
PU-2158 393;
PD-1358 393;
PD-1358 1193;
PD-2158 1193;
PD-2158 393;
SP0;

Os únicos valores que me interessam são os que começam com "PU-" e "PD-".

A: O método csv.reader retorna um reader que você deve usar para iterar pelas linhas do arquivo. Para cada linha, é retornada uma lista contendo os respectivos campos. Como você usou o delimiter=' ', os campos serão separados por espaços. Então basta ver se o primeiro elemento da lista começa com "PU-" ou "PD-", usando o método startswith:
import csv
with open('circulo.plt','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=' ')
    for linha in plots:
        if linha[0].startswith('PU-') or linha[0].startswith('PD-'):
            print(linha)

No caso, estou imprimindo a linha inteira. Como cada linha é retornada como uma lista, a saída é:
['PU-2158', '393;']
['PD-1358', '393;']
['PD-1358', '1193;']
['PD-2158', '1193;']
['PD-2158', '393;']

Aí você decide se vai usar lista[0] para pegar somente o primeiro elemento (as strings que começam com "PU-" ou "PD-"), ou lista[1] para pegar o respectivo valor ("393;", "1193;", etc).

Mas talvez você nem precise usar o módulo csv, pois dá para ler as linhas do arquivo assim:
with open('/tmp/arq.txt','r') as arquivo:
    for linha in arquivo:
        if linha.startswith('PU-') or linha.startswith('PD-'):
            print(linha.split())

A diferença é que agora cada linha é uma string contendo a linha inteira, então eu uso split para separar a string por espaços e retornar uma lista. A saída é a mesma do exemplo anterior.
Da mesma forma que a solução anterior, você pode escolher se pega o primeiro ou segundo elemento da lista retornada por split.

Se quiser, também pode usar expressões regulares, através do módulo re:
import re

r = re.compile(r'^P[UD]-')
with open('/tmp/arq.txt','r') as arquivo:
    for linha in arquivo:
        if r.match(linha):
            print(linha.split())

Para cada linha do arquivo, é verificado se ela corresponde à regex ^P[UD]-.
O marcador ^ significa "início da string", assim eu garanto que vou testar somente se a string começa com determinado padrão.
Em seguida temos a letra P maiúscula e logo depois uma classe de caracteres (os colchetes). No caso, [UD] significa "a letra U ou a letra D". Em seguida, temos o hífen.
Portanto, a regex testa se a linha começa com PU- ou PD-.

Outra opção, para testar a regex e ao mesmo tempo pegar os valores é:
import re

r = re.compile(r'^(P[UD]-\S+) (\S+)')
with open('/tmp/arq.txt','r') as arquivo:
    for linha in arquivo:
        m = r.match(linha)
        if m:
            print(m.group(1), m.group(2))

Agora estou usando parênteses para formar grupos de captura - isso permite que eu pegue os valores que a regex encontrou. Também uso o atalho \S, que significa "qualquer caractere que não seja espaço" (veja a documentação para saber todos os caracteres que são considerados "espaços" - isso inclui o TAB e quebras de linha, por exemplo).
Em seguida eu uso group(1) e group(2) para obter os valores obtidos por cada par de parênteses. O primeiro grupo é a string que começa com "PD-" ou "PU-", e o segundo grupo é a string que vem logo em seguida no arquivo. A saída, neste caso, são duas strings diferentes, em vez de uma lista:
PU-2158 393;
PD-1358 393;
PD-1358 1193;
PD-2158 1193;
PD-2158 393;


text:
Q: How to change status bar color with Flutter? Good evening guys.
I have a problem. I've been on flutter for quite some time. Here I have two AScreen and BScreen screens. For AScreen I would like a white color status bar with black icons. And for BScreen a red status bar with the icons in white. How to achieve this ??
I use flutter_statusbarcolo when I am on screen A the status bar is red I navigate to screen B the status bar is white but when I return to screen A the status bar keeps the color white (color of the screen B)

A: Since you want to change this on per-screen basis, do this on your appBar off the your screen's Scaffold.
Use
appBar: AppBar(
  backgroundColor: Colors.red, // status bar color
  brightness: Brightness.light, // status bar brightness
)

A: AnnotatedRegion<SystemUiOverlayStyle>(value: SystemUiOverlayStyle(statusBarColor:Colors.white,),child: Scaffold(),)

Applies its effect only for the widget that you wrap.


text:
Q: How to match one term (word or sentence) from comma separated list using regex and js? I have a simple list such as:
Health, Health Care, Health Options
My search term is the word "Health". When searching for "Health" I do not want to match "Health Care" and "Health Options" because technically those are different items on the list.
After reading Regex documentation I figured I was supposed to use a lookbehind to check for preceding text. But from what I understand those options are not present in the JS regex.
In summary I need to match a specific value in a group, where the group is a term before/after a comma.

A: If you really need to use regex, the following would work:
var str = "Cat Health, Health, Health Care, Health Options",
    reg = /(?:[^,], )*(Health)(?:, [^,])*/;

alert(str.match(reg)[1]);
// -> Health

Regex Explanation:

*

*Non-comma stuff followed by a comma and a space -- repeated 0-n times.

*"Health"

*Comma, space, non-comma stuff -- repeated 0-n times

Note that there is no lookbehind in Javascript Regex, see:
Positive look behind in JavaScript regular expression
To do it programmatically as suggested in comments (assuming the list items are always separated by a comma then a space):
var str = "Cat Health, Health, Health Care, Health Options"
var list = str.split(/, /);
var a = list.indexOf("Health");
// a = -1 if not found, otherwise contains the index of "Health" in the list


text:
Q: Google Javascript Client library OAUTH asks for Offline Access permission, though it was never requested My application interacts with Google with Javascript only. It asks for user profile access, email access and contacts management permissions.
Upon loading a page, the application checks if the user has already granted those permissions and obtains an access token if he had.
Here is some sample code:
var GoogleContacts = {
...
    checkAuth: function(){
        gapi.auth.authorize({
            client_id: googleKeys.clientId,
            scope: googleKeys.scopes,
            immediate: true
          },
          jQuery.proxy(this.handleAuthResult, this)
        );
    },
    askAuth: function(){
        gapi.auth.authorize({
            client_id: googleKeys.clientId,
            scope: googleKeys.scopes,
            immediate: false
          },
          jQuery.proxy(this.handleAuthResult, this)
        );
    }
...
}

....
function handleGoogleApiLoad(){
    gapi.client.setApiKey(googleKeys.apiKey);
    gapi.auth.init(function(){console.info('popup api ready')});
    setTimeout(function(){GoogleContacts.checkAuth();}, 300);
}

....
$('#emailButton').click(function() {
    if(!accessToken)
       GoogleContacts.askAuth();
    ...
});

Now, if user comes for the first time, he is asked the correct permissions when he pressed the "Send email" button. When user reloads a page, the seamless permissions check returns failure and when user hits a "send email" button, we open the Google authorization popup again, and it now asks for Offline Access permission.
  This seems incorrect as the JS api has no actual use for offline access.
  Looks like this problem started after Google released the incremental auth feature: http://googleplusplatform.blogspot.co.il/2013/12/google-sign-in-improvements11.html
  Is this a bug that will soon be fixed, or should we change the code somehow to not confuse our users with weird permission requests?
Update:
I have tried to use the plus api and gapi.auth.signIn() method but with the same result.
Apparently, this problem is scope-dependant, as when I use only the login scope, everything works as expected, but adding the Google Contacts access scope https:||www.google.com/m8/feeds/ always leads to the Offline Access request when entering page second time. Here is a fiddle to confirm this: http://jsfiddle.net/hjLM6/6/
This must be a bug and I really would like Google to deal with it soon, as it scares users away.

A: The immediate:false parameter in your askAuth method is the cause. The post that Abraham mentions explains the background.
The gapi.auth.authorize() method should generally be avoided in most cases now that the gapi.auth.signIn() method is available to handle programatic initiation of the authorization flow and also you should make use of the dynamic callbacks. The information on monitoring a user's session state explains how and when to get your sign-in callback function to fire and how you can use the values within the auth result object to determine if they've previously authorized your app, signed in (or out) of your app, or signed in (or out) of google.
Your checkAuth and askAuth functions would effectively be combined to check the status of the auth result object and act accordingly. Your email button click event would trigger instead gapi.auth.signIn() with the necessary parameters and scopes for your app.

A: I just had exactly the same issue with drive.readonly scope, for what it's worth the way I worked around it is by always calling authorize with immediate = false. This isn't that bad because when you do this for an already authorized user, Google will open the popup for a fraction of a second but then will immediately close it (apparently making use of the chance to open the popup in the browser event handler in case the user does need to authorize).
Curiously, for localhost server where I previously used immediate = true, I continue to see requests for offline access - but on the production server I haven't seen seen them so far, fingers crossed.


text:
Q: Generate fields instead of properties with CodeDOM I created some code from an XSD-schema-file using CodeDOM:
XmlSchemaImporter importer = new XmlSchemaImporter(schemas);
CodeNamespace code = new CodeNamespace(targetNamespace);
XmlCodeExporter exporter = new XmlCodeExporter(code);

foreach (XmlSchemaElement element in schema.Elements.Values)
{
    XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName);
    exporter.ExportTypeMapping(mapping);
}

Now within my post-processing I realized that this code will generate properties like this:
bool prop1Field;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=0)]
public bool Prop1
{
    get
    {
        return prop1Field;
    }
    set
    {
        prop1Field = value;
    }
}

But I want the generator to simply produce fields instead. Is there a way to achieve this? I know xsd.exe also produces fields when using the /f-argument.
EDIT: Afterwards I want to replace those by auto-properties. To do so with the current approach I´d have to delete the backing-field from the property and all its occurences within the generated code. If CodeDOM however generates a public field in the first place all I had to do is to delete this field, create a new property with the same name using CodeSnippedTypeMember as shown in this answer. Thus I won´t need to search the codes for occurences of the private backing-field and replace them by calls to the property.

A: No, there´s no option to be set to allow this as it shouldn´t matter for consuming code if your attribute is a field or a property (assuming we don´t use reflection) and public fields are considered bad practice.
Anyway I found a way to achieve this by copying all the comments and attributes of the property to the private backing-field and make the field public. However remember that doing so is mostly a bad design-idea.
    public void Process(CodeNamespace code, XmlSchema schema)
    {
        foreach (var type in code.Types.Cast<CodeTypeDeclaration>().Where(x => !x.IsEnum))
        {
            var result = new List<CodeMemberField>();
            var properties = type.Members.OfType<CodeMemberProperty>().ToList();
            foreach (var property in properties)
            {
                ReplacePropertyByField(type, property);
            }
        }
    }

    private static void ReplacePropertyByField(CodeTypeDeclaration type, CodeMemberProperty property)
    {
        var backingField = GetBackingField(property, type);
        backingField.Comments.AddRange(property.Comments);
        backingField.Attributes = property.Attributes;
        backingField.CustomAttributes = property.CustomAttributes;
        backingField.Name = property.Name;
        type.Members.Remove(property);
    }

    private static CodeMemberField GetBackingField(CodeMemberProperty property, CodeTypeDeclaration type)
    {
        var getterExpression = ((CodeMethodReturnStatement)property.GetStatements[0]).Expression;
        var backingFieldName = ((CodeFieldReferenceExpression)getterExpression).FieldName;
        return type.Members.OfType<CodeMemberField>().Single(x => x.Name == backingFieldName);
    }


text:
Q: PHP Accessing cookie value in html page using jquery+ajax I'm trying to access cookie value into html using jquery or ajax ,I'm new to ajax so I don't know how to access json values. I tried with $.getJSON() but it not working. When I execute same code into localhost, it showing john.
test.php
<?php
    $cookie_name = "user";
    $cookie_value = "john";
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
    echo json_encode($_COOKIE[$cookie_name]);
?>

A: Not sure how you are planning on using the value on the client side, but the issue as to why you are not getting output is the fourth parameter option you have in setcookie() function. I'm not sure why you have this as the documentation I found does not list a fourth option. The function accepts the name, value, and time to live.
Also, if all you want to do is return the name of the user value, you don't need to use json_encode(). You can simply echo the name as the response:
<?php

     $cookie_name = "user";
     $cookie_value = "john";
     setcookie($cookie_name, $cookie_value, time() + (86400 * 30));

     echo $_COOKIE[$cookie_name];

?>


text:
Q: iPhone 12 compression of video making videos blue colored I'm trying to compress videos selected from the photo library of the iPhone device and uploading them to the server. Its working for all devices except iPhone 12. On iPhone 12 videos are showing all blue and same to server. Following is the code I'm using to compress videos.
func convertVideo(phAsset : PHAsset, handler:@escaping (_ compressedData: Data?)-> Void){

        var compressedData: Data? = nil
       PHImageManager.default().requestAVAsset(forVideo: phAsset, options: PHVideoRequestOptions(), resultHandler: { (asset, audioMix, info) -> Void in
           if let asset = asset as? AVURLAsset {
               do {
                   let videoData = try  Data.init(contentsOf: asset.url)
                   print(asset.url)
                   //self.orginalVideo = asset.url
                   print("File size before compression: \(Double(videoData.count / 1048576)) mb")
               let compressedURL = NSURL.fileURL(withPath: NSTemporaryDirectory() + NSUUID().uuidString + ".MP4")
                   print(compressedURL)
                   self.compressVideo(inputURL: asset.url , outputURL: compressedURL) { (exportSession) in
                       guard let session = exportSession else {
                           return
                       }
                       switch session.status {
                       case .unknown:
                           print("unknown")
                        handler(compressedData)
                           break
                       case .waiting:
                           print("waiting")
                        handler(compressedData)
                           break
                       case .exporting:
                           print("exporting")
                        handler(compressedData)
                           break
                       case .completed:
                           do {
                           compressedData = try  Data.init(contentsOf: compressedURL)
                               //self.compressVideo = compressedURL
                            print("File size AFTER compression: \(Double(compressedData!.count / 1048576)) mb")
                            handler(compressedData)
                           }
                           catch{
                              print(error)
                            handler(compressedData)
                           }

                       case .failed:
                           print("failed")
                        handler(compressedData)
                           break
                       case .cancelled:
                           print("cancelled")
                        handler(compressedData)
                           break
                       @unknown default:
                        break
                       }
                   }
               } catch {
                   print(error)
                handler(compressedData)
                   //return
               }
           }
       })

   }

   func compressVideo(inputURL: URL, outputURL: URL, handler:@escaping (_ exportSession: AVAssetExportSession?)-> Void) {
       let urlAsset = AVURLAsset(url: inputURL, options: nil)
       guard let exportSession = AVAssetExportSession(asset: urlAsset, presetName: AVAssetExportPresetMediumQuality) else {
           handler(nil)

           return
       }
       exportSession.outputURL = outputURL
       exportSession.outputFileType = AVFileType.mp4
       exportSession.shouldOptimizeForNetworkUse = true
       exportSession.exportAsynchronously { () -> Void in
           handler(exportSession)
       }
   }

Please help. Thanks in advance!

A: Resolved it by using LightCompressor_ios lib
https://github.com/AbedElazizShe/LightCompressor_iOS


text: Q: What is the situation with Intel Poulsbo drivers on Ubuntu (e.g. X11 windows) now? I know about the GMA500 driver, but I can't compile the source code. Is there any chance to find working Poulsbo GPUs driver for the latest Ubuntu distro? I just need GLX so I can watch movies on this laptop sometimes.. Thanks..


text:
Q: T4 Toolbox problems I downloaded and installed the latest  version of the T4 Toolbox for VIsual Studio 2010, in an attempt to create LINQ business objects, but I'm having some troubles with it. First, I was getting errors saying it couldn't find T4Toolbox.tt and T4Toolbox\LinqtoSql.tt in my project directory, but that's not where they are installed. Am I to provide the absolute path to them in my template?
In trying to get this to work, I removed the files I added via the instructions, and added them again. This time the error changed to "File doesn't exist: "\XML\SCHEMAS\DBMLSCHEMA.XSD". I have populated the dbml file using the server explorer.
Both errors reference the same file, the "ServerBiz.tt" file that I created from a Linq to SQL Model template in the Code Generation section in Visual Studio. They've also both generated the warning "The C# 2.0 and C# 3.5 compilers are no longer supported. Templates will always be compiled with the version 4 compiler instead of 'v3.5' as specified.", though switching the language attribute in the .tt file to "C#" cleared that up (and has had no effect on the errors I'm receiving). I've also got no color highlighting in the editor, though something tells me I just need to install a tool or something to get that to work. But I thought I'd mention these things in case they were relevant.
Update:
I was mistaken, the search did find T4Toolbox.tt in C:\Program Files\T4 Toolbox. I've updated the post to reflect this.

A: I reported this and the issue was fixed in the latest version. See my post here for details.


text:
Q: Uncaught exception 'Doctrine\ORM\ORMException' with message 'The EntityManager is closed How to pass doctrine entity manager to some class constructor?
For example, i set-up and create entity manager $em in file _someAction.php.
In the same file i instantiate the class, and pass entity manager to the constructor, but em does not work in the class. I am getting
Fatal error: Uncaught exception 'Doctrine\ORM\ORMException' with message 'The EntityManager is closed.'
class dealErrCl
use Doctrine\ORM\EntityManager;
use someNamespace\LogErr;

class dealErrCl {
 private $em; //entity manager to save error to the entity

public function __construct( \Doctrine\ORM\EntityManager $em ) {
        $this->em = $em;
}

public function flush($errArr) {

    $this->le = new LogErr();

    if( isset($errArr['title']) ) {
        $this->le->setTitle($errArr['title']);
    }
/*...*/

    $this->em->persist($this->le);
    $this->em->flush();

}
_someAction.php
include DbCon.php; // configures doctrine and creates $em. If i use this em in this file, it works, but if i tryt to pass it to some class constructor, it gives Fatal error.

use LogBundle\Components\ErrC\dealErrCl;
$dealErrIn = new dealErrCl($em);

If i use this $em in  _someAction.php file, it works, but if i tryt to pass it to some dealErrCl constructor, it gives Fatal error.

A: It means that there is an error during the flush, which closes the entity manager.
There maybe many possible errors:
1) setting null on non-null field
2) using reserved keywords for field name
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#quoting-reserved-words
POSTGRE reserved words :
https://www.postgresql.org/docs/7.3/static/sql-keywords-appendix.html
MYSQL reserved words:
https://dev.mysql.com/doc/refman/5.7/en/keywords.html
Thus better always enclose all flush, inside a try-catch block.


text:
Q: How to post JSON data from asp.net mvc 3 to web service
Possible Duplicate:
Consuming REST based web services in .Net

I have the project of asp.net MVC, and my partner works on RESTFUL web service. Then I'm the one who post the JSON data to the web service. But I never work with posting data to web service. Could anyone give me any idea of how to posting JSON data to Restful using asp.net mvc 3.0.
Thanks for any help anyone can give me!


text:
Q: Terraform Throwing Error while doing Init with Azure DevOps I am trying to run Terraform with Azure DevOps
Below is my pipeline YML file
variables:
  - group: infra-variables

trigger:
  branches:
    include:
    - master
  paths:
    include:
    - Terraform-Test
    exclude:
    - README.md

stages:
- stage: Validate
  displayName: Validate
  jobs:
  - job: validate
    pool:
      vmImage: ubuntu-latest
    steps:
    - checkout : self
    - task: AzureCLI@2
      displayName :
      inputs:
        azureSubscription: 'PalTest'
        scriptType: 'bash'
        scriptLocation: 'inlineScript'
        inlineScript: |
          az account set --subscription $AZURE_SUBSCRIPTION_ID
          az login --service-principal -u $AZURE_CLIENT_ID -p $AZURE_CLIENT_SECRET --tenant $AZURE_TENANT_ID
          STORAGE_ACCOUNT_KEY=$(az storage account keys list -g $(Terraform_Backend_RG) -n $(TF_STATE_BLOB_ACCOUNT_NAME) | jq ".[0].value" -r)
          echo "setting storage account key variable"
          echo "##vso[task.setvariable variable=ARM_ACCESS_KEY;issecret=true]$ARM_ACCESS_KEY"

    - task: ms-devlabs.custom-terraform-tasks.custom-terraform-installer-task.TerraformInstaller@0
      displayName: Install Terraform
      inputs:
        terraformVersion: 'latest'

  # Init
    - task: TerraformTaskV1@0
      displayName: "Terraform Init"
      inputs:
        provider : 'azurerm'
        command: 'init'
        workingDirectory: '$(System.DefaultWorkingDirectory)/Terraform-Test'
        backendServiceArm: 'PalTest'
        backendAzureRmResourceGroupName: $(Terraform_Backend_RG)
        backendAzureRmStorageAccountName: $(TF_STATE_BLOB_ACCOUNT_NAME)
        backendAzureRmContainerName: '$(TF_STATE_BLOB_CONTAINER_NAME)'
        backendAzureRmKey: 'infrastructure/terraform.tfstate'

  # Validate
    - task: TerraformCLI@0
      displayName: Validate Config
      inputs:
        command: 'validate'
        workingDirectory: '$(System.DefaultWorkingDirectory)/Terraform-Test'

- stage: Plan
  displayName: Plan
  jobs:
  - job: plan
    pool:
      vmImage: ubuntu-latest
    steps:
    - task: ms-devlabs.custom-terraform-tasks.custom-terraform-installer-task.TerraformInstaller@0
      displayName: Install Terraform
      inputs:
        terraformVersion: 'latest'

  # Init
    - task: TerraformCLI@0
      displayName: Initialize Terraform
      env:
        ARM_SAS_TOKEN: $(ARM_ACCESS_KEY)
      inputs:
        command: 'init'
        workingDirectory: '$(System.DefaultWorkingDirectory)/Terraform-Test'
        commandOptions: '-backend-config=storage_account_name=$(TF_STATE_BLOB_ACCOUNT_NAME) -backend-config=container_name=$(TF_STATE_BLOB_CONTAINER_NAME) -backend-config=key=$(ARM_ACCESS_KEY)'
        backendType: 'selfConfigured'

  # Plan
    - task: TerraformCLI@0
      displayName: Plan Terraform Deployment
      env:
        ARM_SAS_TOKEN: $(ARM_ACCESS_KEY)
        ARM_CLIENT_ID: $(AZURE_CLIENT_ID)
        ARM_CLIENT_SECRET: $(AZURE_CLIENT_SECRET)
        ARM_SUBSCRIPTION_ID: $(AZURE_SUBSCRIPTION_ID)
        ARM_TENANT_ID: $(AZURE_TENANT_ID)
      inputs:
        command: 'plan'
        commandOptions: '-input=false'
        workingDirectory: '$(System.DefaultWorkingDirectory)/Terraform-Test'

# Approve
- stage: Approve
  displayName: Approve
  jobs:
  - job: approve
    displayName: Wait for approval
    pool: server
    steps:
    - task: ManualValidation@0
      timeoutInMinutes: 60
      inputs:
        notifyUsers: 'pallabcd@hotmail.com'
        instructions: 'Review the plan in the next hour'

- stage: Apply
  displayName: Apply
  jobs:
  - job: apply
    pool:
      vmImage: ubuntu-latest
    steps:
      - task: ms-devlabs.custom-terraform-tasks.custom-terraform-installer-task.TerraformInstaller@0
        displayName: Install Terraform
        inputs:
          terraformVersion: 'latest'

      # Init
      - task: TerraformCLI@0
        displayName: TF Init
        env:
          ARM_SAS_TOKEN: $(ARM_ACCESS_KEY)
        inputs:
          command: 'init'
          workingDirectory: '$(System.DefaultWorkingDirectory)/Terraform-Test'
          commandOptions: '-backend-config=storage_account_name=$(TF_STATE_BLOB_ACCOUNT_NAME) -backend-config=container_name=$(TF_STATE_BLOB_CONTAINER_NAME) -backend-config=key=$(ARM_ACCESS_KEY)'
          backendType: 'selfConfigured'

      # Apply
      - task: TerraformCLI@0
        displayName: TF Apply
        env:
          ARM_SAS_TOKEN: $(ARM_ACCESS_KEY)
          ARM_CLIENT_ID: $(AZURE_CLIENT_ID)
          ARM_CLIENT_SECRET: $(AZURE_CLIENT_SECRET)
          ARM_SUBSCRIPTION_ID: $(AZURE_SUBSCRIPTION_ID)
          ARM_TENANT_ID: $(AZURE_TENANT_ID)
        inputs:
          command: 'apply'
          workingDirectory: '$(System.DefaultWorkingDirectory)/Terraform-Test'
          commandOptions: '-auto-approve'

My main.tf file is shown below :
terraform {
  required_version = "~> 1.0"

  backend "azurerm" {
  storage_account_name = "glstor2020"
  container_name = "glstor2050"
  key = "terraform.tfstate"
  access_key = "=="
}

  required_providers {
    azuread = "~> 1.0"
    azurerm = "~> 2.0"
  }
}

provider "azurerm" {
  features {}
}

data "azurerm_resource_group" "az-rg-wu" {
  name = "Great-Learning"
}

data "azurerm_client_config" "current" {}

data "azurerm_key_vault" "my-kv" {
  name                = "testhalvault"
  resource_group_name = "PallabDev"
}

All my variables are in variable group and below is my tfvar file which takes variable from the variable group
subscription_id      = "#{AZURE_SUBSCRIPTION_ID}#"
client_id            = "#{AZURE_CLIENT_ID}#"
client_secret        = "#{AZURE_CLIENT_SECRET}#"
tenant_id            = "#{AZURE_TENANT_ID}#"
storage_account_name = "#{TF_STATE_BLOB_ACCOUNT_NAME}#"
container_name       = "#{TF_STATE_BLOB_CONTAINER_NAME}#"
access_key           = "#{ARM_ACCESS_KEY}#"
admin_password       = "#{VM_PWD}#"

I get the below error in the init stage

A: https://developer.hashicorp.com/terraform/language/settings/backends/azurerm
In your example it seems that you use 3 approaches, maybe terraform chooses one of these(deciding by which argument was provided first), and after you provide other properties it is a problem for Terraform
You use access_key

When authenticating using the Storage Account's Access Key - the following fields are also supported: access_key

You also use sas_token

When authenticating using a SAS Token associated with the Storage Account - the following fields are also supported:

You also use client_secret and other which can be found in section

When authenticating using a Service Principal with a Client Secret - the following fields are also supported:

I am not sure if Azure can handle all these 3 directions at once


text:
Q: Windows Server 2008 R2 missing a drive I have a production server (Dell T110 Windows 2008 R2) that was up and running just fine. It has 4 drives 2 256GB drives a spare, and the OS, a 512 that is setup for MSSQL2008R2 Server Data drive just responsible for holding the the MDF files, and an old style TB disk drive for archiving data to.
This server has been in production for a few months and has not had any issues. Suddenly the OS quits finding the data drive. This was very intermittent starting Friday night and by Saturday afternoon it was dead. I know SSD's have a shorter life expectancy and configured settings to preserve the SSD's as long as possible, but the way this drive failed was more like windows issue than a hard drive issue.
The first sign was windows explore/disk manager couldn't find the drive, yet for a little while we were able to run queries and still use the device  in MSSQL.
I also have no entry in Disk Management for it. If the hard drive had simply failed I think it would show up as a bad or unusable drive. Is this a sign of a IO controller failure?
Has anyone seen anything like this before? Is there any way to get windows to try and see the drive again besides the re-scan drives? My servers are out of town so I don't have any physical access until I make a trip to the co-location.
Any help would be appreciated.

A: Get the service tag of the server and download Server Administrator and DSET from the Dell homepage. Install Server Administrator. If you happen to have a controller failure, it should be able to provide you with some more details.
Do you have a support contract with Dell? If so, contact their hotline and open a case. They'll probably ask you to create a system report with the DSET utility, so make sure you have the tool ready.


text:
Q: Fitness based ranking If 3 variables $x[0]$, $x[1]$, $x[2]$ and their sum give the probability of the variable being selected as follows
$$\begin{align}
p[0] &= \frac{\text{sum}-x[0]}{2\times\text{sum}}\\
p[1] &= \frac{\text{sum}-x[1]}{2\times\text{sum}}\\
p[2] &= \frac{\text{sum}-x[2]}{2\times\text{sum}}
\end{align}$$
then, it is not a very good fitness based probability. because for the numbers $0.426, 0.036, 0.325$ the corresponding probabilities are $0.23, 0.48, 0.29$, although the second number is 10 times smaller than the other two, it only receives half the share.
Can someone suggest a better approach?

A: [assuming I understood what you meant] use Exponential ranking: $p_j = \frac{e^{- \alpha x_j}}{\sum_j e^{- \alpha x_j}}$
Where $\alpha$ is a coefficient $>1$ if you need to increase the 'weight' of the individual with the lower value


text:
Q: VB.NET : Use System.Type in value binding I am trying to use reflections in VB.NET to handle types.
    Public Function reflective(Of T)() As System.Type
        Dim t_ As T = Nothing
        Return t_.GetType()
    End Function

    Sub Main()
        Dim nbr_type As Type = reflective(Of Int32)() 'Works fine
        Console.Writeline("Number type is: " & nbr_type.Name) 'Works fine
        Dim nbr As nbr_type = Nothing 'Fails 'nbr_type' is not declared. It may be inac...
        'VB compiler completely fails to understand what I am trying to do
    End Sub

How do I initialize a variable using System.Type?


text:
Q: How to configure ClamAV autoupdate I am using ClamAV for scanning our files in our Django application. I am running freshclam manually to update the antivirus database. My question is how to automate it?

A: From the ClamAV documentation, I created a Cron job with the following code:-
N * * * *   /usr/local/bin/freshclam --quiet


text:
Q: Wrong behaviour of set I have a set of Vec3b to hold posible RGB pixel values.
std::set<cv::Vec3b> used_colors;

But behaves weird:
used_colors.insert(cv::Vec3b(100, 255, 255));

// this returns 1 although (100, 0, 0) is NOT in the set
used_colors.count(cv::Vec3b(100, 0, 0));

The value (100, 0, 0) is found because other value starting with 100 is already inserted in the set. Other values like (80, 0, 0) can not be found. This is obviously the wrong weird behaviour.

I implemented the < comparision operator like this:
bool operator <(const cv::Vec3b &a, const cv::Vec3b &b) {
    if(a[0] < b[0])
        return true;

    if(a[0] > b[0]);
        return false;

    if(a[1] < b[1])
        return true;

    if(a[1] > b[1]);
        return false;

    if(a[2] < b[2])
        return true;

    if(a[2] > b[2]);
        return false;

    return false;
}

A: Your operator< is broken due to errant semicolons after several of the if statements.
Consider the inputs a = Vec3b(100, 255, 255) and b = Vec3b(100, 0, 0). Because the R value of both is 100 the test makes it to
if(a[0] > b[0]);  // <-- notice the semicolon?

Because of that trailing semicolon the function unconditionally returns false. Due to the same reason, the comparison b < a also returns false; and set::count thinks the element already exists.
Get rid of the trailing semicolons and your comparison operator works as expected.

Instead of manually writing all those comparisons to do lexographical ordering, an easier, less error prone way is to use std::tie
bool operator<(const cv::Vec3b &a, const cv::Vec3b &b)
{
  return std::tie(a[0], a[1], a[2]) < std::tie(b[0], b[1], b[2]);
}

A: Your comparison function is stuffed, probably because you have ; after a number of your if statements.
Even then, this is far more complex than it needs to be. std::tie makes this into a one-liner:
bool operator <(const cv::Vec3b &a, const cv::Vec3b &b)
{
    return std::tie(a[0], a[1], a[2]) < std::tie(b[0], b[1], b[2]);
}


text:
Q: Is it possible to remotely run scripts in a guest OS using VCLI? Using VMware OVF Tool 4.0, I'm deploying/powering on some VMs and would like to execute some scripts inside them. However, I was unable to assign injection properties to a VM, I.e: DNS, Gateway, etc. See OVF Tool documentation page 22 for more information: https://www.vmware.com/support/developer/ovf/ovf400/ovftool-400-userguide.pdf
This below link was helpful but the associated properties were not assigned, when I tred this:
http://www.virtuallyghetto.com/2014/06/an-alternate-way-to-inject-ovf-properties-when-deploying-virtual-appliances-directly-onto-esxi.html
As an alternative, I would like to remotely run a setup script that resides in the VM.
I'm seeing from articles online that Power CLI cmdlet Invoke-VMScript is a common choice. Link shown below:
https://www.vmware.com/support/developer/PowerCLI/PowerCLI51/html/Invoke-VMScript.html
Is there an alternative method to this cmdlet? Is there a similar command that VCLI has to offer? Any assistance would be great. Thanks in advance.
Regards,Gabriel

A: I researched VIX API using Perl, and I'm now able to run  remote scripts from a VM.Link: https://www.vmware.com/support/developer/vix-api/Regards,Gabriel


text:
Q: Vectorization of self-dependant MATLAB loop I am pretty new to matlab and am trying to understand vectorization. I am usually able to find a way to vectorize my code, but this time is different. Note that e() and f() aren't function calls but arrays, a(i,j) is a matrix. The problem here is that the value of e(i) depends on the value of e(i-1). Same thing also happens for f(i). Is there a way to vectorize this loop in order to gain speed?
The function takes A a tridiagonal symmetric matrix, b the solution to the Ax=b linear system and outputs sol: the solution to the system. The code works as is, i just want to make it quicker where possible. Hope the additional details help.
function [sol] = MySolTridiagDirect(A,b)
   %Adds 2 slack variables
   a = [zeros(size(A,1),1),A,zeros(size(A,1),1)];
   %Adds solutions to slack variables
   b = [zeros(1,size(b,2));b;zeros(1,size(b,2))];

   e = NaN(size(A,1)+1,1);
   f = NaN(size(A,1)+1,1);
   x = NaN(size(A,1)+1,1);

   e(1) = 0;
   f(1) = 0;
   x(1) = 0;

   for i=2:size(f,1)
       e(i) = (-a(i-1,i+1)) / (a(i-1,i-1)*e(i-1,1) + a(i-1,i));
       f(i) = (b(i) - a(i-1,i-1)*f(i-1)) / (a(i-1,i-1)*e(i-1,1) + a(i-1,i));
   end
   %% Solver for variable 'x' (solution)
   x(end) = f(end);
   for i=size(f,1)-1:-1:2
      x(i) = e(i)*x(i+1) + f(i);
   end
   sol = x(2:end,:);
end

A: I think this problem can not be vectorized in a traditional way, I did not find any possibility to simplify the code and doing so increase the performance by a factor of ~2
a2=diag(a,2);
a0=diag(a,0);
a1=diag(a,1);

for i=2:size(f,1)
    e(i) = (-a2(i-1)) / (a0(i-1)*e(i-1) + a1(i-1));
    f(i) = (b(i) - a0(i-1)*f(i-1)) / (a0(i-1)*e(i-1) + a1(i-1));
end

To find a vectorisation, I used the symbolic toolbox to display the full formula to calculate e(i) only using e(1), but I failed to see any possibilities to implement these calculations in a vectorized manner. If you look at the formulas, there are more and more nested brackets involved:
n=4;
f=sym('f',[n,1]);
e=sym('e',[n,1]);
a1=sym('a1',[n,1]);
a0=sym('a0',[n,1]);
a2=sym('a2',[n,1]);
b=sym('b',[n,1]);

for i=2:size(f,1)
    e(i) = simplify((-a2(i-1)) / (a0(i-1)*e(i-1) + a1(i-1)));
    f(i) = simplify((b(i) - a0(i-1)*f(i-1)) / (a0(i-1)*e(i-1) + a1(i-1)));
end

The only possibilities I know to evaluate such formulas are recursion and for-loops. As for-loops are much faster than recursion in matlab, there is probably no better way.


text:
Q: Eigenvalues of shape operator and of curvature on second exterior power Terminology note
In the following, a scalar product will be a symmetric bilinear form, and a euclidean scalar product will be a positive definite scalar product. This is the terminology used by my Differential Geometry teacher.
Background
Let me sum up the operators coming in play in the question. To start right from the start, we have, in as general a context as possible, a Riemannian manifold $(M,g)$. The metric induces a single Levi-Civita connection, which I will denote $\nabla_XY$, where $X,Y$ are fields and $\nabla_XY$ is the covariant derivative of $Y$ along $X$, as it is also called. The curvature tensor is then defined as:
$$R(X,Y)Z=\nabla_X\nabla_YZ-\nabla_Y\nabla_XZ-\nabla_{[X,Y]}Z=[\nabla_X,\nabla_Y]Z-\nabla_{[X,Y]}Z.$$
This is the type $(1,3)$ curvature tensor, whereas the type $(0,4)$ tensor is:
$$R(X,Y,Z,W)=g(R(X,Y)Z,W).$$
This can be proven to be antisimmetric in the first two and second two entries, and symmetric w.r.t. swapping the two couples (i.e. $R(X,Y,Z,W)=R(Z,W,X,Y)$). This means it induces a scalar product on the second exterior power, which we define as:
$$\mathcal{R}(X\wedge Y,Z\wedge W)=R(X,Y,W,Z).$$
$g$ also induces a scalar product on the second exterior power:
$$g'(v\wedge w,u\wedge t)=g(v,u)g(w,t)-g(v,t)g(w,u).$$
This can be shown to be positive definite -- in fact, if $\{v_j\}$ is orthonormal w.r.t $g$< $\{v_i\wedge v_j\}_{i<j}$ is orthonormal w.r.t. $g'$. Fixing this scalar product as a "reference", since $\mathcal{R}$ is also a scalar product, we get a self-adjoint operator, which we still denote $\mathcal{R}$, by setting:
$$g'(\mathcal{R}(v\wedge w),u\wedge t)=\mathcal{R}(v\wedge w,u\wedge t).$$
Oh I'm writing all of this with decomposable vectors but this is extended by additivity to non-decomposable ones of course.
The last operator we need is the shape operator. So we consider a hypersurface $N\subseteq M$. Locally, we can always find a normal unitary vector field $\mathcal{N}$ for $N$. Modulo a sign, this induces an operator, called shape operator, which is defined by:
$$S(v)=\nabla_X\mathcal{N},$$
where $X$ is any field which evalues to $v$ at the tangency point $p$ of $v$ to $M$. It can be shown that this is a $g$-self-adjoint endomorphism of $T_pN$, and that $S(\mathcal{N}(p))=0$.
Question
So here comes, at last, the question. I have been given the following exercise.

Let $M$ be a hypersurface of $\mathbb{R}^n$. Suppose $M$ is compact, connected, orientable (i.e. has a global unitary normal field). Assume $\{v_j\}$ is an orthonormal basis for the tangent space $T_pM$ consisting of eigenvalues of the shape operator $S$. Prove that $\{v_i\wedge v_j\}$ is an o.n.b. of $\Lambda^2T_pM$ composed of eigenvalues of $\mathcal{R}$, and more precisely $\mathcal{R}(v_i\wedge v_j)=\lambda_i\lambda_jv_i\wedge v_j$, where $S(v_i)=\lambda_iv_i$.

Now the fact that those wedges provide an orthonormal basis is easy, since we know (by earlier proof in the course) that it is a basis, and orthonormality follows from a simple computation:
$$g'(v_i\wedge v_j,v_k\wedge v_\ell)=g(v_i,v_k)g(v_j,v_\ell)-g(v_i,v_\ell)g(v_j,v_k)=\delta_{ik}\delta_{j\ell}-\delta_{i\ell}\delta_{jk},$$
we need $i<j$ and $k<\ell$ by definition of the basis, if the two are equal the first term is $1\cdot1$ and the second one $0\cdot0$, so it is a normal basis, and if they are distinct then the first term is 0, and if $i\neq k$ it could be that $i=\ell$ but the $j\neq k$ since $j>i=\ell>k$, so the second term is also zero, whereas if $j\neq\ell$ it could be $j=k$, but $i\neq\ell$ by a similar argument, giving again that both terms are zero. As for the fact those vectors are eigenvalues of $\mathcal{R}$, I am pretty much at a loss: what is the link between $\mathcal{R}$ and $S$? I must be missing something fundamental, but I just don't see a way to link them.
PS
I also know that the hypotheses given imply $S$ is everywhere positive definite or everywhere negative definite, and that $M$ is diffeomorphic to $S^d$. That is (or should be) called Hadamard's theorem. "or should be" because the statement was given after the proof of the theorem and along the lines of «This set of considerations are called Hadamard's theorem». At this point in the course we have not yet covered geodesics, and we never saw anything involving both geodesics and $S$. I remark this because I have seen this question. Also, principal curvature is an unknown term for me. Seeing this question makes me remember the Theorema Egregium, which we proved, and seems to be potentially useful here. However, T.E. works in $\mathbb{R}^3$, not $\mathbb{R}^{d+1}$, so it would need a generalization. Obviously, $d=2$ is solved by T.E., because if the sectional curvature (which equates to $\mathcal{R}(v_i\wedge v_j,v_i\wedge v_j)$ since the denominator is 1) is the determinant of the shape operator, then it is the product of the eigenvalues, which are precisely the $\lambda_i$.

A: By the Gauss (or is it Codazzi-Mainardi?) equation (which I had completely forgotten about), we have:
$$R(X,Y)Z=A(S(X),S(Y))Z=\lambda_i\lambda_jA(X,Y)Z=\lambda_i\lambda_j\langle Y,Z\rangle X-\langle X,Z\rangle Y,$$
so: $\newcommand{\ang}[1]{\langle #1 \rangle}$
\begin{align*}
\mathcal{R}(X\wedge Y,Z\wedge T)={}&R(X,Y,T,Z)=\ang{R(X,Y)T,Z}=\lambda_i\lambda_j\ang{\ang{Y,T}X-\ang{X,T}Y,Z}={} \\
{}={}&\lambda_i\lambda_j\ang{X,Z}\ang{Y,T}-\lambda_i\lambda_j\ang{X,T}\ang{Z,Y}.
\end{align*}
By definition of the operator $\mathcal{R}$:
$$\ang{\mathcal{R}(X\wedge Y),Z\wedge T}=\mathcal{R}(X\wedge Y,Z\wedge T)=\lambda_i\lambda_j\ang{X,Z}\ang{Y,T}-\lambda_i\lambda_j\ang{X,T}\ang{Z,Y},$$
but $X,Y,Z,T$ are part of an orthonormal system (the one chosen on $N$), so if $X\neq Z$ or $Y\neq T$ this is 0, and otherwise this is $\lambda_i\lambda_j$, proving this is indeed an eigenvalue.


text:
Q: A method that dismisses a `modalViewController` and presents another The thing is: I have a modalViewController presented with a button that triggers an IBAction like this:
-(IBAction)myMethod
{
    [self dismissModalViewControllerAnimated:YES];

    if([delegate respondsToSelector:@selector(presentOtherModalView)])
    {
        [delegate presentOtherModalView];
    }
}

in the root view that is the delegate for that modalViewControllerI've implemented the presentOtherModalView delegate method and it looks like this:
    -(void)presentOtherModalView
{

     AnotherViewController *viewInstance = [[AnotherViewController alloc]initWithNibName:@"AnotherViewController" bundle:nil];

     viewInstance.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

     [self presentModalViewController:viewInstance animated:YES];

    [viewInstance release];
}

The problem is this second modalViewController is not being presented. It gives me the message wait_fences: failed to receive reply: 10004003... How should this be done?

A: It is because the dismissModalViewControllerAnimated takes some time to dismiss with animation and you are calling another view to present as modal view before dismissing the 1st modal view so the presenting modal view call was rejected. You should not perform animations when you are not on the view after completely dismissing only you can call another view. To solve this problem call the present modal view after 2 or 3 seconds using time interval or use completion block for dismissModalViewControllerAnimated
You can achieve it by using this
[delegate performSelector:@selector(presentOtherModalView) withObject:nil afterDelay:3];

A: Because they are executed exactly after each other (they don't wait for the view to disappear/appear), it doesn't get executed. Because there can only be one ModalViewController on the screen at a time, you have to first wait for the other ModalViewController to disappear before the next one is put on screen.
You can do this creatively how you want, but the way I did it was something like:
[self dismissModalViewControllerAnimated:YES];
self.isModalViewControllerNeeded = YES;

And then in the underlying ViewController, in the viewDidAppear method, I do this:
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.isModalViewControllerNeeded) {
        [self presentModalViewController:viewInstance animated:YES];
        self.isModalViewControllerNeeded = NO;
    }
}

Hope it helps!


text:
Q: github actions - Private Composite action POST fail Issue:
Pulling a private repo that contains several actions will fail in the POST phase with error message:
 Error: Can't find 'action.yml', 'action.yaml' or 'Dockerfile' under '/home/runner/work/testjerome/testjerome/.github/actions/package_and_push_to_ECR'. Did you forget to run actions/checkout before running your local action?

Example to reproduce it:
- name: Check out main repository
  uses: actions/checkout@v2

- name: Get composite run steps repository
  uses: actions/checkout@v2
  with:
    repository: myorg/myaction
    # Select revision
    ref: v1.0.0
    # Personal access token to check out private repository
    token: ${{ secrets.PAT_TOKEN }}
    # Indicate where to check action out to
    path: .github/actions

- name: Run action from private repo
  uses: ./.github/actions/myAction

This example assumes that "myorg/myaction" is a private github repo with 1 folder having 1 file like this: myAction/action.yml
Question:
Would any one know how to avoid that issue, while still having several actions in a repo ? (yes, I could create 1 repo per action ... but this is going to be messy)
References:
This is a follow up from the comments from How do you use a composite action that exists in a private repository?
As well as this github issue (can't find the issue itself in github):
https://githubmemory.com/repo/actions/runner/issues/1300
Someone did setup a reproducible example:
https://github.com/rethab/composite-action-user

A: Ignore the question - found the github issue link:
https://github.com/actions/runner/issues/1300
I'll wait until someone helps there
Also, as the issue is "because we do a checkout action in the remote action", the workaround I'm now using is:

*

*remove that checkout

*upload the files I need from the caller job, and download them from the callee ... silly workaround for a silly issue


text:
Q: How to pass json object to code behind in ASP.Net using VB Can you help me to solve this..?
Actually I developed a simple application to pass a JSON object to ASP.Net code behind. I am Using VB in Code behind.
I am just using the below code in jquery ajax.
$(document).ready(function () {
      $.ajax({
            type: "POST",
            url: "form1.aspx/getStringReverse",
            data: "{'Name':'Vinoth'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) { alert(msg.d); }
            , failure: function (msg) { alert(msg.d); }
        });
});

Below is the code in VB

'This code is not working
<WebMethod>

Public Shared Function getStringReverse(ByVal name As String) As String

    Return StrReverse(name )

End Function

'This code is not working

When I am Calling this function, Control is not passed to the function.
But When I am changing this function as below, It works.

'This code is working'
<WebMethod>

 Public Shared Function getStringReverse() As String

    Return "String Reverse"

 End Function

'This code is working

Kindly help me to solve this.

A: You need to mark the method you want to call as WebMethod and also as static method.
 <WebMethod()>
    Public Shared Function getStringReverse(name as string) As String
        ***
    End Function


text:
Q: SimpleXml_load_file to two dimensional array Sorry about this question, maybe somwhere here in StackOverflow is answer for my question, but there is a way, to convert my xml file to two dimensional php array and keep xml node attributes in second dimension (Something like this : $colors['2']['en'] i mean $colors[colorid][lang])?
P.S Sorry for my bad english, this isn`t my native language.
Here is my xml file:
    <?xml version="1.0" encoding="UTF-8"?>
<Colors>
    <Color id="1">
        <Name lang="lv" default="true">Sudraba</Name>
        <Name lang="en">Silver</Name>
        <Name lang="ru">Серебро</Name>
    </Color>
    <Color id="2">
        <Name lang="lv" default="true">Sarkans</Name>
        <Name lang="en">Red</Name>
    </Color>
    <Color id="3">
        <Name lang="lv" default="true">Melns</Name>
    </Color>
</Colors>

A: This is working example. If you are choosing $sxml->Color[0], this method is selecting first Color element in xml document, but if you select like this $sxml->Color["0"], it is selecting by element's attribute. Sorry for my english, this is not my native language too:).
<?php

    $sxml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?>
    <Colors>
        <Color id="1">
            <Name lang="lv" default="true">Sudraba</Name>
            <Name lang="en">Silver</Name>
            <Name lang="ru">Серебро</Name>
        </Color>
        <Color id="2">
            <Name lang="lv" default="true">Sarkans</Name>
            <Name lang="en">Red</Name>
        </Color>
        <Color id="3">
            <Name lang="lv" default="true">Melns</Name>
        </Color>
    </Colors>');

    echo $sxml->Color["1"]->Name[0];

    ?>


text:
Q: Extending Array in Typescript doesn't allow me to modify array I created a class, that extends Array:
export class Collection<T> extends Array<T> {
    constructor(items?: Array<T>) {
        super(...items);

        Object.setPrototypeOf(this, Object.create(Collection.prototype));
    }

    whereKey(key: string, value: any): T {
        for(let i = 0; i < this.length; i++) {
            if(this[i][key] === value) {
                return this[i];
            }
        }
    }

    removeAt(index: number) {
        this.splice(index, 1);
    }
}

However, using anything standard array method, like splice(), or even filter(), doesn't work. I get ImportsHomeComponent.html:15 ERROR TypeError: CreateListFromArrayLike called on non-object as an error. Literally the only method I can use is push.
I have created the collection like so:
getImportTests(): Observable<Collection<ImportTest>> {
    return this.http.get<Collection<IImportTest>>(route('imports/import-tests')).map((importTests: Collection<IImportTest>) => {
        return new Collection<ImportTest>(importTests.map((importTest: IImportTest) => {
            return new ImportTest(importTest);
        }));
    });
}

And then tried to remove an element like so:
this.importTests.removeAt(this.importTests.indexOf(importTest));

I only really need to use a collection but of the whereKey method, but I'm open to anything as this is driving me crazy.

A: The Collection constructor does not call the super Array constructor properly. Notice the structure is different:
new Collection(["a", "b"]) =>
    Array(2)0: "a"1: "b"length: 2__proto__: Collection

new Array(["a", "b"]) =>
    Array(1)0: (2) ["a", "b"]length: 1__proto__: Array(0)

Try this:
constructor(...items) {
        super(...items);

        Object.setPrototypeOf(this, Object.create(Collection.prototype));
    }


text:
Q: Double integral problem Evaluate the double integral
$$
I = \iint_D x y \ dx dy
$$
where $D$ is the closed triangular region with vertices $(0, 0)$, $(4, 0)$, $(0, 3)$.
Appreciate any and all help!

A: $x$ ranges from $0$ to $4$, and for each value of $x$, $y$ ranges from $0$ to $-3x/4  + 3$, so
$$
I = \int_0^4 dx \ x \int_0^{-3x/4 + 3} dy \ y.
$$
I'll let you evaluate.

A: You can solve this question with Stokes' theorem. If you have the vector field $\mathbf{F} (x,y)$, you know that
$$\int_{D} (\mathbf{\nabla}\times \mathbf{F})_z\,dx\,dy =\int_{\partial D} \mathbf{F}\cdot d\mathbf{r}. $$
With $\mathbf{F}=- \tfrac12 x y^2 \mathbf{e}_x$, you find that
$$\begin{align}
\int_{D} xy\,dx\,dy& = \int_{\partial D} \mathbf{F}\cdot d\mathbf{r}
= \underbrace{\int_0^4 F_x(x,0)\,dx}_{=0}
+ \underbrace{\int_0^3 F_y(4,y)\,dy}_{=0}
- \int_0^1 [4 F_x(\mathbf{r}) + \underbrace{3 F_y(\mathbf{r})}_{=0}]\,dt\\
&=\int_0^1 2 [4(1-t)][3(1-t)]^2\,dt = 72 \int_0^1(1-t)^3\,dt
\end{align}$$
where we parameterized the last segment via $\mathbf{r}(t) = \begin{pmatrix}4(1-t)\\ 3(1-t)\end{pmatrix}$, $t\in[0,1]$.


text:
Q: Gtk Type Error thrown after cx freeze compile, (working fine in python interactive shell) I'm running python 3.4 on Ubuntu 14.04. I am using gtk to code my app indicator (little icon near the clock etc). It works fine in the interactive shell. However running it after compile (with cx-freeze), the gtk app indicator is throwing an error, everything else works fine. I won't post the whole log as it's rather long. I suspected it was something with threading but even taking the code out of the thread for testing yielded the same result.
This is the line causing the error
(process:11923): Gtk-CRITICAL **: gtk_icon_theme_get_for_screen: assertion 'GDK_IS_SCREEN (screen)' failed

(process:11923): Gtk-CRITICAL **: _gtk_style_cascade_get_for_screen: assertion 'GDK_IS_SCREEN (screen)' failed

(process:11923): Gtk-CRITICAL **: _gtk_style_provider_private_lookup: assertion 'GTK_IS_STYLE_PROVIDER_PRIVATE (provider)' failed

...more code omitted

ci = gtk.MenuItem('Currently Opened')
TypeError: GObject.__init__() takes exactly 0 arguments (1 given)

and the gtk related code:
from gi.repository import Gtk as gtk
from gi.repository import AppIndicator3 as appindicator

def mer():
            a = appindicator.Indicator.new('tim',self.imgdir+'firebird.gif', appindicator.IndicatorCategory.APPLICATION_STATUS)
            a.set_status (appindicator.IndicatorStatus.ACTIVE)
            m = gtk.Menu()
            oi = gtk.MenuItem( 'Open Smart Overlay' )
            ci = gtk.MenuItem('Currently Opened')
            ri = gtk.MenuItem('Recently Opened')
            qi = gtk.MenuItem( 'Quit' )
            m.append(oi)
            m.append(ci)
            m.append(ri)
            m.append(qi)
            a.set_menu(m)
            oi.show()
            ci.show()
            ri.show()
            qi.show()
            oi.connect('activate', lambda e: self.trayQueue.put(self.root.deiconify))
            ci.connect('activate', lambda: 0)
            ri.connect('activate', lambda: 0)
            def quit(item):
                gtk.main_quit()
                self.trayQueue.put(lambda :gui_base.quitter(self))
            qi.connect('activate', quit)
            while 1:
                gtk.main()
        thread.start_new_thread(mer,())


text:
Q: Non-orthogonal bases a set of functions $$ u_{n}=x^n, n=0,1,2....$$ is linearly independent, but it isn't orthonormal. I need to find the first four polynomials that are orthonormal and the interval $$-1\leqslant x \leqslant 1$$
(these polynomials are proportional to the Legendre polynomials)
Is there a method to find those polynomials?

A: The method you want is Gram-Schmidt orthogonalization.
The inner product used here is $$<P_m(x), P_n(x)> = \int_{-1}^{1}P_m(x)P_n(x)dx$$, which you want to be zero when you combine two of your final functions.
Let the first function $P_0 = v_1 = 1$.
Then the second function will be $$ v_2 = x - \frac{<x,1>}{<1,1>} \cdot 1$$
The third function will be
$$v_3 = x^2 - \frac{<x^2,1>}{<1,1>} \cdot v_1-\frac{<x^2,v_2>}{<v_2,v_2>} \cdot v_2$$. and so on.
If you need orthonormal, not just orthogonal, divide each vector by its length, $\sqrt{<v,v>}$ as you find them.


text:
Q: Dependence in probabilistic machine learning From this slide: slides page 39, it says:
In probabilistic machine learning prediction time: compute the likelihood given parameters, each parameter configuration of which is weighted by the posterior:
$$
p(y|x, D)=\int p(y|\theta, x) p(\theta|D) d\theta
$$
where $x, y, \theta, D$ is input, output prediction, network parameters, dataset, respectively. I am trying to derive this formula in this way:
$$
p(y|x, D)=\int p(y, \theta| x,D) d\theta = \int p(y|\theta, x, D) p(\theta|x, D) d\theta=\int p(y|\theta, x) p(\theta|D) d\theta
$$
However, it depends on such assumption: $y$ is independent of $D$, so $p(y|\theta, x, D)=p(y|\theta, x)$. Since $y$ depends on $\theta$, $\theta$ depends on $D$, it seems that $y$ should also depends on $D$. What's wrong here?
In addition, we need $p(\theta|x, D)=p(\theta|D)$, that is $x$ is independent of $\theta$. Is it still correct in training time? It seems that $\theta$ depends on $D$, so should also depend on $x$?

A: The form with $p(y|\theta,x,D)$ is the correct version according to Bayes Rule. But, in the literature around these, typically we assume $p(y|\theta,x,D)=p(y|\theta,x)$ because $D$ is data useful in estimating the parameters of the model, which is $\theta$. However, if you already know the parameters of the model, you only need the input and the model parameters to calculate $y$'s distribution.
For the second term, same logic applies. We estimate $\theta$ from data, not the current value of $x$ at prediction time.


text:
Q: In Android CameraBridgeViewBase class, How to set opencv camera for Portrait orientation in Full screen mode I was using opencv cameraBridgeViewBase Class, in Normal portrait mode camera angle is rotated. so i use to traspose and flip, camera angle rotated to normal portrait mode.
Core.transpose(mRgba, mRgbaT);
Imgproc.resize(mRgbaT, mRgbaF, mRgbaF.size(), 0,0, 0);
Core.flip(mRgbaF, mRgba, 0);

But camera view is center of the screen , not able to get full screen mode. Is anything possible to change full screen mode or without transpose and flip to change full screen mode for portrait please justify me thank you..

A: I'm not sure if I understood your problem. But if you want to keep your OpenCV application full screen no matter if you tilt/rotate your phone, one easy thing to do in order to overcome this problem would be:
Go to your Android manifest and add android:screenOrientation="landscape" before the line: android:label="@string/app_name"
Keep us updated if it worked for you


text:
Q: Laravel 4 file upload error I have an file upload form, and I want to use validator.
$roles = array(
    'title' => 'required|max:128',
    'description' => 'required|max:2800',
    'picture' => 'mimes:jpeg,bmp,png'
);

My problem is, if I try to upload a picture, I get this error: finfo::finfo(): Failed to load magic database at ''. The $_SERVER['MAGIC'] is set to /usr/share/misc/magic... So I don't know why throw  this error. But if I comment out the picture validation line, and I select a photo is the form, I also get an error: Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed.Can anybody tell me what should I do?
UPDATE
$finfo = new finfo(FILEINFO_MIME_TYPE);
$filename = public_path() . '/images/test.png';
var_dump($finfo->file($filename));

It works good string(9) "image/png". But in the validation still bad.

A: Laravel uses finfo for file validation and finfo needs magic_file name of a magic database file, usually something like /path/to/magic.mime. In your php.ini make sure you have something like this available and it points qo the right resource
[mime_magic]
mime_magic.magicfile = "D:\xampp\php\extras\magic.mime"

This is the path for the file in my xampp installation. It may varies depending on your OS and If not specified, the MAGIC environment variable is used, for more information, visit fileinfo. Also, this may help you. It's not related to Laravel but your php installation.


text:
Q: Como calcular um FOR para de 6 em 6 incrementos ele dar um echo? Tenho um FOR simples que preciso que a cada 6 incrementos ele mande um echo com uma mensagem, segue código:
$carros = array("Volvo", "BMW", "Toyota", "Alfa Romeu", "WV", "Teste", "test2", "Teste4", "Teste3", "Teste5", "Volkswagem", "Ferrari");

for ($i=0; $i < count($carros); $i++) {
    echo "Carro ".$carros[$i];

    //quando chegar a 6, 12, 18, 24, 30... ele manda esse echo
    echo "Página: ".$i;

}

A: coloque um IF com uma condição verificando se o seu contador é um múltiplo de 6.
$carros = array("Volvo", "BMW", "Toyota", "Alfa Romeu", "WV", "Teste", "test2", "Teste4", "Teste3", "Teste5", "Volkswagem", "Ferrari");

for ($i=0; $i < count($carros); $i++) {
    echo "Carro ".$carros[$i];

    if ($i%6 === 0){
      echo "Página: ".$i;
    }
}

A: Pode verificar se o $i é mod (que verifica se a divisão não tem resto) de 6 então imprimir o número de página.
if($i % 6 === 0) echo $i;

Outro exemplo simples:
foreach(range(1, 60 ) as $item){
    if($item % 6 === 0) echo 'Página '. $item .PHP_EOL;
}

Saída:
Página 6
Página 12
Página 18
Página 24
Página 30
Página 36
Página 42
Página 48
Página 54
Página 60

Exemplo - ideone

A: $carros = array("Volvo", "BMW", "Toyota", "Alfa Romeu", "WV", "Teste", "test2", "Teste4", "Teste3", "Teste5", "Volkswagem", "Ferrari");

for ($i=0; $i < count($carros); $i++) {
echo "Carro ".$carros[$i];

$number = 0;
if($i === (6 + number)){
    number = number + 6;
    echo "Página: ".$i;
 }
}


text:
Q: Unity3d Instantiate a child prefab from the parent source I originally posted this question on answers.unity3d but got no answers
Unity3d Instantiate a child prefab from the parent source
I have a Prefab called GreyPiece, When clicked on it, This GreyPiece is supposed to create children of the same type
currently my GreyPiece class has a public Transform object called GreyPieceTransform
public Transform greyPieceTransform;

This Transform is the same as the main GreyPiece Prefab [dragged and dropped in the Unity3d Editor]
And when clicking on the object, I Instantiate multiple children for this object [as needed] and setting the transform as it's parent
Transform greyPiece = Instantiate(greyPieceTransform, transform.position, transform.rotation) as Transform;
greyPiece.parent = transform;
Debug.Log("this id "+transform.GetInstanceID()+"\tprefab id "+greyPieceTransform.GetInstanceID()+"\tchild id "+greyPiece.GetInstanceID());

so far so good, if I create one object and click on it , I'd have 1 child

*

*parent

*

*child

now if I create 2 I'll get this

*

*parent

*

*child

*child

*

*child

if I create 3

*

*parent

*

*child

*child

*

*child

*child

*

*child

*child

*

*child

basically what's happening is that the original GreyPieceTransform seems to be changing, and when I try to instantiate another object it's taking the modified [the current parent] and instantiates from it
this issue doesn't happen if I didn't set the parent of the new instantiated object
EDIT: I also added a debug output
The debug.Log output is this

this id -185148   prefab id -185148   child id -185236
this id -185148   prefab id -185148   child id -185318
this id -185148   prefab id -185148   child id -185418

As you can see , the parent transform and the prefab transform  have the same ids, but they shouldn't
To make this even clearer I decided to name the transforms as "grey "+greyPiece.getInstanceID();
and this is how it looks in the hierarchy view

so now, how can I have the grePieceTransform actually reference the prefab [instantiate from the prefab] instead of it having the same reference as the parent

A: I guess the problem is the following. At the first instantiation transform and greyPieceTransform point to the same object.
You can check it comparing instance ids.
If this is the case the behavior you see is reasonable. The first time you instantiate a new GameObject the source object has no parent and no children so you get just one child. The second time you are instantiating the parent with 1 child and attaching it as a child (fig.2).
And so on.
Here's a simple snippet that may help:
public class Test : MonoBehaviour {

    public Transform prefab;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        if (Input.GetKeyDown(KeyCode.A))
        {
            Debug.Log("prefab id " + prefab.GetInstanceID() + " this id " + transform.GetInstanceID());
        }
    }
}

It will print different combinations of ids depending on how the object references are set up.
Case 1
If Test is attached to a object in the hierarchy and prefab is a reference to a prefab in the project, ids will be different.
Case 2
If Test is attached to a object in the hierarchy (which is a prefab instance)and prefab is a reference to the linked prefab in the project id will still be different.
(prefab is a link from a instanced object to a prefab. it should be a prefab property override in this case and you should see the bold font in the inspector).Ids will be different.
Case 3
If Test is attached to a prefab and the field prefab points to itself, when it is instantiated the first time(or dragged into the hierarchy), transform and prefab fields will point to the same object (the transform of the prefab instance).
Ids will be equal.

apparently what's happening is that the when instantiating an object
  from a that prefab Transform [greyPieceTransform], it's using it as
  the current object and modifies the original one [so greyPiece and
  greyPieceTransform would be the same]

No. If greyPieceTransform and transform of the object are different the "original" won't be modified. But probably they aren't.