text:
Q: Postgres xml data type in a frequently updating data set I'm working on an RSS reader that will store information from an RSS feed into a feed table. I would like to re-fetch the RSS feeds every 15 minutes (respecting ETags and other HTTP cache headers) to detect any updates. I'm expecting about 30,000 RSS feeds each with about 100 items.
Is it reasonable to use the Postgres xml data type for this large and frequently updating data set? Or should I parse out relevant fields in my code that fetches the feeds and store them in individual columns in the Postgres table?
In SQL:
create table channel (
  id serial primary key,
  xml xml
);

vs.
create table channel (
  id serial primary key,
  title text,
  link text,
  description text,
  -- etc.
);

The RSS feed won't be changing every 15 minutes, I just want to check frequently to be sure to catch any updates. Because of this suppress_redundant_updates_trigger seems like a good choice, but I am not sure if it will work with the xml data type because there is no way to check equality between xml types in Postgres. Would it make sense to convert the xml to text and check equality that way?
I would prefer to use the xml type because it means I don't have to predict the contents of the RSS feed. I can get everything and dynamically derive the information I need using xpath. Would it be a bad idea to use the xml type in a frequently updating large data set?


text:
Q: Meteor: Can't update fields with $set I'm learning Meteor. So far, I've been able to initialize properties on User.profile with the following:
Meteor.users.update(Meteor.userId(),{$set:cardObject});

I'd like to update those properties but when I use the same technique I get this:
errorClass {error: 403, reason: "Access denied", details: undefined, message: "Access denied [403]", errorType: "Meteor.Error"…}

It will let me $unset the properties though:
Meteor.users.update(Meteor.userId(),{$unset: cardObject});

This is strange to me. I can delete properties but not modify them.
Any ideas?

A: I don't have the full codebase, so I'm guessing, but based on your code snippet, it might be because cardObject doesn't complete the $set commmand properly.  a typical $set command looks like this:
 ...{"$set" : {"key": "value"}}...

so, it may depend on what is in your cardObject.
Whereas your $unset will work just fine because you only need the key to perform an unset.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How To Uniquely Identify An Android Device? even after change the system or factory reset. I wonder maybe there are some ways to get some hardware info, and then make an unique id for this phone based on these info.
Is that possible?

A: You can use device IMEI number. Most of case it's unique.
check this post -> How to get the device's IMEI/ESN programmatically in android?

A: As you read there isn't a 100% safe method to get a unique id. Another approach that you can use (if you want a unique identifier for your app) is to generate a random UUID at your first install and save it locally;
UUID uuid = UUID.randomUUID();
preferences.setAppId(uuid.toString());


text:
Q: Нет права на чтение файла, хотя я состою в группе владельца файла Есть например файл 1.png.
Он принадлежит владельцу и группе www-data:www-data.
На файле стоят права -rw-rw----
Как я понимаю, просматривать файл может владелец и все кто состоит в группе владельца, т.е. в группе www-data.
Мой пользователь andrey.
Я добавил его в группу www-data командой $ sudo usermod -a -G www-data andrey.
Если просмотреть командой $ groups andrey, то в списке группа www-data есть.
Но почему-то права на просмотр этого файла всё равно нет. Т.е. я не могу открыть эту картинку в Ubuntu 16.04 в обычном проводнике.
Почему так происходит? Или я не правильно понимаю механизм прав доступа? Подскажите пожалуйста.

A: Чтобы изменения вступили в силу необходимо перелогиниться.


text:
Q: Android live update? I'm creating a android game which communicates with a web server using JSON.
When someone starts a new game versus another user I want that user to get a
immediate notification. So far I've made the notifications and they work,
but it only checks when I log in to the game, how do I create a live update
that checks with a, perhaps, one minute interval even if the game is closed?

c2dm.php
<?

function googleAuthenticate($username, $password, $source="Company-AppName-Version", $service="ac2dm") {

    session_start();
    if( isset($_SESSION['google_auth_id']) && $_SESSION['google_auth_id'] != null)
        return $_SESSION['google_auth_id'];

    // get an authorization token
    $ch = curl_init();
    if(!ch){
        return false;
    }

    curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
    $post_fields = "accountType=" . urlencode('HOSTED_OR_GOOGLE')
        . "&Email=" . urlencode($username)
        . "&Passwd=" . urlencode($password)
        . "&source=" . urlencode($source)
        . "&service=" . urlencode($service);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    // for debugging the request
    //curl_setopt($ch, CURLINFO_HEADER_OUT, true); // for debugging the request

    $response = curl_exec($ch);

    //var_dump(curl_getinfo($ch)); //for debugging the request
    //var_dump($response);

    curl_close($ch);

    if (strpos($response, '200 OK') === false) {
        return false;
    }

    // find the auth code
    preg_match("/(Auth=)([\w|-]+)/", $response, $matches);

    if (!$matches[2]) {
        return false;
    }

    $_SESSION['google_auth_id'] = $matches[2];
}

function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText) {

    $headers = array('Authorization: GoogleLogin auth=' . $authCode);
    $data = array(
        'registration_id' => $deviceRegistrationId,
        'collapse_key' => $msgType,
        'data.message' => $messageText //TODO Add more params with just simple data instead
    );

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");
    if ($headers)
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    $response = curl_exec($ch);

    curl_close($ch);

    return $response;
}
?>

C2DMRegistrationReceiver
public class C2DMRegistrationReceiver extends BroadcastReceiver
{

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Log.w("C2DM", "Registration Receiver called");
    if ("com.google.android.c2dm.intent.REGISTRATION".equals(action)) {
        Log.w("C2DM", "Received registration ID");
        final String registrationId = intent
                .getStringExtra("registration_id");
        String error = intent.getStringExtra("error");

        Log.d("C2DM", "dmControl: registrationId = " + registrationId
                + ", error = " + error);
        // TODO Send this to my application server
    }
}

public void sendRegistrationIdToServer(String deviceId, String registrationId) {

    Log.d("C2DM", "Sending registration ID to my application server");
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("myserverpage");
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        // Get the deviceID
        nameValuePairs.add(new BasicNameValuePair("deviceid", deviceId));
        nameValuePairs.add(new BasicNameValuePair("registrationid", registrationId));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);
        BufferedReader rd =
            new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {
            Log.e("HttpResponse", line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

C2DMMessageReceiver
public class C2DMMessageReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Log.w("C2DM", "Message Receiver called");
    if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
        Log.w("C2DM", "Received message");
        final String payload = intent.getStringExtra("payload");
        Log.d("C2DM", "dmControl: payload = " + payload);
        // Send this to my application server
    }
}
}

public void register(View view) {
    Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
    intent.putExtra("app",PendingIntent.getBroadcast(this, 0, new Intent(), 0));
    intent.putExtra("sender", "app-name@gmail.com");
    startService(intent);
}

Now if I start a game against someone, I have a class that sends the information to the server. Then how do I proceed?

A: You could accomplish what you want by implementing a Service.  However, making an HTTP request to get the status every minute will be a drain on the battery.  I would suggest looking into C2DM in order to send a push notification to the client.


text:
Q: Como converter JSON em Objeto e encontrar um id - JAVA Preciso converter um JSON em objeto e navegar até um ID e capturar apenas ele.
JSON Exemplo:
"{"_status":"sucesso","_dados":{"_sucesso":[{"idintegracao":"BkmRboZmaaa","situacao":"SALVO","TituloNumeroDocumento":"01012020","TituloNossoNumero":"501","CedenteContaCodigoBanco":"748","CedenteContaNumero":"9999","CedenteConvenioNumero":"9999"}],"_falha":[]}}

Preciso capturar o idIntegração que fica em _dados._sucesso[0].idintegracao, e salvar em uma string.
O que fiz até agora:
 String jsonString = response.body().string();

        JSONObject jsonObjectBoleto = new JSONObject("{" + jsonString + "}");

        Iterator<String> iteratorBoletos = jsonObjectBoleto.keys();
        System.out.println("TO AQUI");

        System.out.println("TO AQUI NO WHILE " + iteratorBoletos.toString());
        JSONObject dadosBoleto = jsonObjectBoleto.getJSONObject(iteratorBoletos.toString());
        System.out.println("TO AQUI NO WHILE 2 " + iteratorBoletos.toString());
        Boleto boleto = new Boleto();
        System.out.println("DADOS DO BOLETO: " + dadosBoleto.getString("idintegracao"));

Tentei também fazer isso mas sem sucesso:
      String jsonString = response.body().string();

        String json = ("{" + jsonString + "}");

        JSONObject obj1 = new JSONObject(json);

        String idIntegracao = obj1.getString("idintegracao");

        System.out.println("idIntegracao : " + idIntegracao);

A: Você pode utilizar utilizar a API de processamento de Json disponível apartir do java 1.8
Dependencias maven:
<dependency>
    <groupId>javax.json</groupId>
    <artifactId>javax.json-api</artifactId>
    <version>1.1</version>
 </dependency>
 <dependency>
     <groupId>org.glassfish</groupId>
     <artifactId>javax.json</artifactId>
     <version>1.1</version>
</dependency>

Após adicionar as bibliotecas recupere o Json em uma String e crie um JsonReader para ler a String:
String jsonString = response.readEntity(String.class);
JsonReader jsonReader = Json.createReader(new StringReader(jsonString));

Recupere o JsonObject apartir do jsonReader:
 JsonObject jsonObject = jsonReader.readObject();

Recupere o JsonObject para o atributo "_dados"
 JsonObject attributeDados = jsonObject.getJsonObject("_dados");

Recupere o JsonArray para o atributo "_sucesso"
 JsonArray jsonArray = attributeDados.getJsonArray("_sucesso");

Recupere enfim o id
String idIntegracao = jsonArray.getJsonObject(0).getString("idintegracao");


text:
Q: My macro is not being able to perform vlookup I have a complex that is doing alot of copy pasting to different files, however, I am getting an error on the following line and error is object doesn't support this property or method
.Range("Q" & i).Value="if(P" & i & "=" & Chr(34) & "Y" & Chr(34) & ",vlookup(A" & i & "," & OutShVar & "!$A:$BP,68,0)," & Chr(34) & "Not Available" & Chr(34) & ")"

(I am copy pasting parts that are relevant to the question.)
  Set OutShVar=ThisWorkbook.Worksheets("MasterReport")
  Set RngConcat=OutShVar.Range("A:A")

  Set wMain=Workbooks.open(ForePath & sfn)
  Call OpenLink 'Performs tasks on another report after opening it

  'After doing a bunch of things on the OpenLink report,
    'i want to do a vlookup on that report that will take things from the excel
    'workbook where the macro is i.e., OutShVar and RngCon'

   'On Master list/Refresh
   if .Range("P" & i).Value = "N" Then
   .Range("Q" & i).Value="Not inscope"
  Else
   If not IsError(Application.Match(.Range("A" & i).Value,RngConcat,0) Then
    .Range("Q" & i).Value="if(P" & i & "=" & Chr(34) & "Y" & Chr(34) & ",vlookup(A" & i & "," & OutShVar & "!$A:$BP,68,0)," & Chr(34) & "Not Available" & Chr(34) & ")"
    'This is where the problem is, not sure if this is right way to do the vlookup?

A: To assign a formula, use the Formula property of Range Object. Also, use the Worksheet Name property to use it rather than worksheet object in the formula.
The code below should work fine for you.
.Range("Q" & i).Formula = "= IF(P" & i & "=" & Chr(34) & "Y" & Chr(34) & ",VLOOKUP(A" & i & ",'" & OutShVar.Name & "'!$A:$BP,68,0)," & Chr(34) & "Not Available" & Chr(34) & ")"

Below is the difference between key properties of range for future reference:
.Text gives a string representing what is displayed on the screen for the cell. Using .Text is usually a bad idea because you could get ####
.Value2 gives you the underlying value of the cell (could be empty, string, error, number (double) or boolean)
.Value gives you the same as .Value2 except if the cell was formatted as currency or date it gives you a VBA currency (which may truncate decimal places) or VBA date.
Source: Another StackOverflow answer


text:
Q: internal error while starting android studio I am trying to start android studio. I have already installed jdk7 in my computer but when i start android studio, it shows below error message:

Internal error. Please report to
  https://code.google.com/p/android/issues
java.lang.RuntimeException: java.lang.IllegalArgumentException:
  Argument for @NotNull parameter 'name' of
  com/android/tools/idea/welcome/Platform. must not be null
      at com.intellij.idea.IdeaApplication.run(IdeaApplication.java:178)
      at com.intellij.idea.MainImpl$1$1$1.run(MainImpl.java:52)
      at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:312)
      at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:745)
      at java.awt.EventQueue.access$300(EventQueue.java:103)
      at java.awt.EventQueue$3.run(EventQueue.java:706)
      at java.awt.EventQueue$3.run(EventQueue.java:704)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
      at java.awt.EventQueue.dispatchEvent(EventQueue.java:715)
      at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:362)
      at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
      at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
      at java.awt.EventDispatchThread.run(EventDispatchThread.java:91) Caused by: java.lang.IllegalArgumentException: Argument for @NotNull
  parameter 'name' of com/android/tools/idea/welcome/Platform.
  must not be null
      at com.android.tools.idea.welcome.Platform.(Platform.java)
      at com.android.tools.idea.welcome.Platform.getLatestPlatform(Platform.java:72)
      at com.android.tools.idea.welcome.Platform.createSubtree(Platform.java:89)
      at com.android.tools.idea.welcome.InstallComponentsPath.createComponentTree(InstallComponentsPath.java:81)
      at com.android.tools.idea.welcome.InstallComponentsPath.init(InstallComponentsPath.java:215)
      at com.android.tools.idea.wizard.DynamicWizardPath.attachToWizard(DynamicWizardPath.java:97)
      at com.android.tools.idea.wizard.DynamicWizard.addPath(DynamicWizard.java:233)
      at com.android.tools.idea.welcome.FirstRunWizard.init(FirstRunWizard.java:75)
      at com.android.tools.idea.welcome.FirstRunWizardHost.setupWizard(FirstRunWizardHost.java:100)
      at com.android.tools.idea.welcome.FirstRunWizardHost.getWelcomePanel(FirstRunWizardHost.java:92)
      at com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame.(WelcomeFrame.java:68)
      at com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame.showNow(WelcomeFrame.java:173)
      at com.intellij.idea.IdeaApplication$IdeStarter.main(IdeaApplication.java:302)
      at com.intellij.idea.IdeaApplication.run(IdeaApplication.java:172)

A: Try this:

*

*Open the folder bin under the directory where you installed your Android Studio.

*Find the file idea.properties and open it with Notepad++ / UltraEdit / other plain text editing software.

*Add disable.android.first.run=true as the final line and save the file.

*Restart Android Studio.


text:
Q: Invalid or unexpected token when loading into the client side I'm trying to run an extremely simple socket.io/express webserver just to test things out. I'm using express to serve the following index.html

Hello Websocket

The HTML loads fine but for some reason, I'm getting an error Uncaught SyntaxError: Invalid or unexpected token for socket.io.js 1.  When I look at it on chrome there are a bunch of weird characters 摯‽湥潣敤਻敹獡⹴敤潣敤㴠搠捥摯㭥洊摯汵⹥硥潰瑲⁳‽敹獡㭴ਊ⨯⨪ ⥽ਊ⨯
However, when I simply request localhost:5000/socket.io/socket.io.js I get the socket.io code I would expect.
This is my index.js:
const app = require("express")();
const httpServer = require("http").createServer(app);
const options = { /* ... */ };
const io = require("socket.io")(httpServer, options);
const path = require('path');

app.get('/', (req, res) =>{
    console.log("Getting a request to /")
    res.sendFile(path.join(__dirname, 'public' , "index.html"));
})

io.on("connection", socket => {
    console.log("We are connected");
    console.log(socket.handshake.adress);
 });

httpServer.listen(5000, () => {
    console.log("Listening on port 5000");
});

How to fix this?


text:
Q: Marshmallow permission popup hides fragment UI beneath My app asks for permissions in Parent activity while fragment is shown to user already
when app asks for permission the background becomes complete white I want to show permission dialog on top of fragment but not covering full screen
Any ideas?
adding code below
int finePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        List<String> listPermissionsNeeded = new ArrayList<>();
        if (finePermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
            listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), PERMISSION_CODE);

        }

A: add this line to your dialog
 dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));


text:
Q: Best place to parse big input text data in rails I have two related to each other questions. I need some best practices.
First part..
Im searching best place to put data parser from text area. I do not want to insert that data to database, just read from text area after that compare that with some data and do some action (no any data from database). Where would u place that parsers? I should use helper (for now I use helpers just in view), concerns or just model methods?
Second part..
For example, lets input data looks like:
A B H 0 2
C D R 1 3
E F E 4 9
R H T 1 0

I parse that data from text area, split by column, check regex, if there is 5 cols etc. I need to create list of objects, and where could i create that 'helper' class with fields like first_col, sec_col, third_col, that data will be not saved to database..?

A: I think it's the job of a service object. You will pass the text to your service, it will work with your param and return the result, anywhere in your app.


text:
Q: Как реализовать универсальную функцию поиска и сортировки по таблице в Django с помощью api queryset? Делаю страницу с табличкой, которая содержит поля с информацией из базы данных. Хочу над каждым столбцом сделать формочку поиска по параметрам, но не могу придумать никакого универсального решения кроме как через if-else проверять наличие кучи параметров в request.GET. Я уверен, что решение моей проблемы уже известно и существует уже довольно давно, но я никак не могу сформулировать вопрос чтобы найти это в гугле.
В общем, сейчас проверка и фильтрация выглядит следующим, мягко говоря, не самым красивым способом:
#   поиск
    if 'name' in request.GET:
        list = list.filter(name__icontains=request.GET.get('name'))
        cache.name = request.GET.get('name')
        cache.save()
    elif cache.name is not '':
        list = list.filter(name__icontains=cache.name)

    if 'number' in request.GET:
        list = list.filter(number__icontains=request.GET.get('number'))
        cache.number = request.GET.get('number')
        cache.save()
    elif cache.number is not '':
        list = list.filter(number__icontains=cache.number)

# и далее, далее, далее...

При чем такая конструкция находится в каждом представлении, отвечающем за отображение таблицы, а таблиц много. Поэтому такое решение совершенно не подходит.
Я хочу сделать что-то вроде универсальной функции поиска, которая бы вызывалась в каждом view и возвращала бы отфильтрованный и отсортированный список объектов, которые потом будут отображаться в таблице.
Я это вижу примерно таким образом:
def search_and_sort(request, list, cache_instanse):
    for search_seting in request.GET:
        if cache_instanse.search_seting is not '':
            list = list.filter(search_seting__icontains=cache_instanse.search_seting)
        else:
            list = list.filter(search_seting__icontains=request.GET.get(search_seting))
            cache_instanse.search_seting = request.GET.get(search_seting)
            cache_instanse.save()
    return list

cache_instance - это объект кэша для каждой отдельной таблички, он хранит значения полей при предыдущих поисковых запросах, по факту копирует объект таблицы, только все его поля класса CharField.
Вариант с кодом выше не работает, так как я не могу передать в качестве строки имя переменной (это решало бы всю проблему) и просто проитерироваться по строкам, представленным в request.GET не представляется возможным.
Уважаемые мидлы, сеньеры и джуны-переростки, если кто-то может чем-то помочь, сказать куда я думаю не так или показать готовое решение, прошу, помогите пожалуйста.
Спасибо!
UPD:
Я справился с сортировкой. Не могу понять как сделать поиск.
Сортировка выглядит следующим образом:
def search_and_sort(request, list, instance, cache_instance):
    #   перебор всех параметров, переданных в request.GET
    for setting in request.GET:
        #   проверка на ключ сортировки
        if setting is 'sorted' or setting is 'resort':
            #   если нужно отсортировать от большего к меньшему
            if setting == 'sorted' and request.GET.get(setting) is not '':
                list = list.order_by('-'+request.GET.get(setting))
            #   если нужно отсортировать от меньшего к большему
            else:
                list = list.order_by(request.GET.get(setting))
    return list

Чтобы провернуть такое же решение с поиском типа Object.objects.filter(field__icontains=request.GET.get(setting)) нужно чтобы вместо fields подставлялось имя переменной. Как получить имя переменной я знаю, не знаю только как передать.
Я планировал сделать это следующим способом:
def search_and_sort(request, list, instance, cache_instance):
    #   перебор всех параметров, переданных в request.GET
    for setting in request.GET:
        #   проверка на ключ сортировки
        if setting is 'sorted' or setting is 'resort':
            #   если нужно отсортировать от большего к меньшему
            if setting == 'sorted' and request.GET.get(setting) is not '':
                list = list.order_by('-'+request.GET.get(setting))
            #   если нужно отсортировать от меньшего к большему
            else:
                list = list.order_by(request.GET.get(setting))
        #   если это ключ поиска
        else:
            fields = instance._meta.get_fields()
            for field in fields:
                if field.name == setting:
                    list = list.filter(field__icontains=request.GET.get(setting))
    return list

Кто знает как мне помочь или знает решение лучше, прошу не проходить мимо.

A:
Object.objects.filter(field__icontains=request.GET.get(setting)) нужно чтобы вместо fields подставлялось имя переменной

Делайте так:
filters = {
    '{}_icontains'.format(setting): request.GET.get(settings)
}
Object.objects.filter(**filters)

** разворачивает dict в список именованных параметров функции. Как раз то, что нужно, если имена параметров динамические.


text:
Q: Share localstorage with another systems I have a login system (x.x.x.x: 8000) that generates a localstorage. When a user clicks a certain button it goes to another system (x.x.x.x: 8001) and needs the information stored in the previous system's localstorage (x.x.x.x: 8000). Is it possible to share the localstorage generated in the login system (x.x.x.x: 8000) with other systems?
Thank you very much

A: It might be worth looking into this library as a solution to your problem: Cross Storage
This library enables multiple domains to share the same localStorage. Hope this helps!

A: Web storage ( local storage & session storage ) only allowed to store data per origin ( per domain & protocol ). That means you the browser can't share data between different origin.Local storage across different domains The attached link have a good explanation about the cross storage.

A: There is a complete thread about sharing localStorage between subdomains here:
use localStorage across subdomains
You could use the recommended IFRAME technique. You can call a page on x.x.x.x:8001 from x.x.x.x:8000 info an IFRAME, before the user click, to store the data needed on x.x.x.x:8001. By doing so, you would be able to retrieve the data needed after the user click.


text:
Q: Saving all Windows 10 cmd window content I have a fairly lengthy batch process that runs a number of other batch files and programs.  Some of the programs log to the window, but have already hooked the console streams so simple output redirection does not work. A lot of files are created during processing, but one file I cannot capture is the overall console log for the process.  The only way I see to do this is the cmd Window Title bar menu shown in the image below.  I know I could use some type of windows automation tool, but before resorting to that, I want to ask all of you if there is a way to automate the Cmd windows Title menu operations that is intrinsic to the Windows environment.

A: I found a short article with examples here:
https://levelup.gitconnected.com/how-to-access-the-system-clipboard-copy-paste-from-the-command-line-c8615d510ae2
Using Windows intrinsic clip command to get the output, and using powershell get-clipboard to save that in a file.
>call _thFullMonty.cmd | clip
>PowerShell get-clipboard > _theFullMonty.log


text:
Q: CSS layout with multiple 3x3 grids, one in each corner I'm working on a single screen JavaScript web application. It has several screens and the users can perform some timing tests to get a overall score. I'll admit I'm no expert in GUI design, although I'm perfectly comfortable working with Visual Studio xaml and Android Studio layouts.
At the moment I'm trying to add a new screen, which should have the following layout. It should have a  rectangle in the center, with 4 grids of 3x3 squares, one grid in each corner of the center rectangle, and one smaller square in the middle. (The "plus" in the middle can just be a square with an image I guess).

Then there's some JavaScript code which should change the colors of the blocks in several patterns, repeat a couple of times, and ask for certain user input, but that is the easy part.
My problem is getting the screen layout as required on screen, which is much harder than I initially thought. I've found this question but couldn't get it to work properly.
After trying some things I'm stumped, see my code below. Btw, I've just created a separate HTML and CSS file and started experimenting, but if someone can suggest a more effective approach, I'm all ears.

.container {
}

body {
 font-family: Arial;
 background: #080;
 overflow: "hidden";
}

/* color for blocks */
.red    {background: #f00;}
.orange {background: #f80;}
.yellow {background: #ff0;}
.green  {background: #0f0;}
.cyan   {background: #0ff;}
.blue   {background: #00f;}
.purple {background: #f0f;}

/* containing area for the four 3x3 grids */
.block3_area {
 width: 50%;
 position: absolute;
 top: 50%;
 left: 50%;
 margin-right: -50%;
 transform: translate(-50%, -50%);
 background: #0cf;
}

/* one 3x3 grid */
.block3_grid {
 display: grid;
 grid-gap: 1px;
 grid-template-columns: repeat(3, 1fr);

 width: 30%;
 height: 30%;
}

.grid_tl {float: top left;}
.grid_tr {float: top right;}
.grid_bl {float: bottom-left;}
.grid_br {float: bottom-right;}

/* the inner blocks of the grid */
.game3block {
 width: 50px;
 height: 50px;
}

.game3block > .game3block {
  padding: 10px;
  background-color: #ccc;
}
<!DOCTYPE HTML>

  <title>3x3 grid css test</title>

 <link rel="stylesheet" type="text/css" href="grid.css">

TL-1

TL-2

TL-3

TL-4

TL-5

TL-6

TL-7

TL-8

TL-9

TR-1

TR-2

TR-3

TR-4

TR-5

TR-6

TR-7

TR-8

TR-9

BL-1

BL-2

BL-3

BL-4

BL-5

BL-6

BL-7

BL-8

BL-9

BR-1

BR-2

BR-3

BR-4

BR-5

BR-6

BR-7

BR-8

BR-9

Does anybody know how to get this layout? Any help is appreciated.

A: https://codepen.io/ud-kazi/pen/poJdGLL

body{
  background:green;
}

.wrapper{
  width:300px;
  height:300px;
  background:pink;
  margin:0 auto;
}

.blue{
  float:left;
  margin-bottom:10px;
}

.blue-box{

  margin-right:52px;
}

.blue-box div{
  height:40px;
  width:40px;
  background:blue;
  border:0.5px solid yellow;
  float:left;
}

.red{
  float:left;
   margin-bottom:10px;
}

.red-box{

}

.red-box div{
  height:40px;
  width:40px;
  background:red;
  border:0.5px solid yellow;
  float:left;
}

.orange{
  float:left;
}

.orange-box{

  margin-right:52px;
}

.orange-box div{
  height:40px;
  width:40px;
  background:red;
  border:0.5px solid orange;
  float:left;
}

.black{
  float:left;
}

.black-box div{
  height:40px;
  width:40px;
  background:black;
  border:0.5px solid yellow;
  float:left;
}

.plus{
  text-align:center;
  font-size:30px;
  color:white;
}

+

A: Flex and grid, if you are okay to use them , can help you .
example with an extra tag for the + sign if it is one :

/* color for blocks */

.red {
  background: #f00;
}

.orange {
  background: #f80;
}

.yellow {
  background: #ff0;
}

.green {
  background: #0f0;
}

.cyan {
  background: #0ff;
}

.blue {
  background: #00f;
}

.purple {
  background: #f0f;
}

.block3_area>div {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  width: max-content;
  grid-row: 1;
}

.block3_area>div>div {
  width: 3em;
  height: 3em;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 0 0 1px white;
}

.block3_area>div.middle {
  grid-row: 2;
  grid-column: 2;
  width: min-content;
  text-align: center;
  justify-content: center;
  color: white;
  font-size: 50px;
  line-height: 25px;
}

.block3_area>div.middle~div {
  grid-row: 3;
}

.block3_area> :nth-child(2),
.block3_area> :nth-child(5) {
  grid-column: 3;
}

.block3_area {
  background: rgb(0, 192, 255);
  display: grid;
  grid-template-columns: repeat(2, auto);
  grid-template-rows: repeat(3, auto);
  margin: auto;
}

body {
  margin: 0;
  min-height: 100vh;
  display: flex;
  background: rgb(0, 128, 0);
}

TL-1

TL-2

TL-3

TL-4

TL-5

TL-6

TL-7

TL-8

TL-9

TR-1

TR-2

TR-3

TR-4

TR-5

TR-6

TR-7

TR-8

TR-9

+

BL-1

BL-2

BL-3

BL-4

BL-5

BL-6

BL-7

BL-8

BL-9

BR-1

BR-2

BR-3

BR-4

BR-5

BR-6

BR-7

BR-8

BR-9

https://codepen.io/gc-nomade/pen/LYVOqKV
or the plus sign drawn in the background if its only about design :

/* color for blocks */

.red {
  background: #f00;
}

.orange {
  background: #f80;
}

.yellow {
  background: #ff0;
}

.green {
  background: #0f0;
}

.cyan {
  background: #0ff;
}

.blue {
  background: #00f;
}

.purple {
  background: #f0f;
}

.block3_area>div {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  width: max-content;
  grid-row: 1;
  grid-column: 1;
}

.block3_area>div>div {
  width: 3em;
  height: 3em;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 0 0 1px white;
}

.block3_area> :nth-child(2n) {
  grid-column: 2;
}

.block3_area> :nth-child(2)~div {
  grid-row: 2;
}

.block3_area {
  background: linear-gradient(white, white) no-repeat center center, linear-gradient(white, white) no-repeat center center rgb(0, 192, 255);
  background-size: 2px 2em, 2em 2px;
  display: grid;
  grid-template-columns: repeat(2, auto);
  grid-template-rows: repeat(2, auto);
  margin: auto;
  grid-gap: 1.5em;
}

body {
  margin: 0;
  min-height: 100vh;
  display: flex;
  background: rgb(0, 128, 0);
}

TL-1

TL-2

TL-3

TL-4

TL-5

TL-6

TL-7

TL-8

TL-9

TR-1

TR-2

TR-3

TR-4

TR-5

TR-6

TR-7

TR-8

TR-9

BL-1

BL-2

BL-3

BL-4

BL-5

BL-6

BL-7

BL-8

BL-9

BR-1

BR-2

BR-3

BR-4

BR-5

BR-6

BR-7

BR-8

BR-9

https://codepen.io/gc-nomade/pen/dyoZaBG
if you are not familar with grid and flex , these links can be usefull to you :

*

*https://css-tricks.com/snippets/css/complete-guide-grid/

*https://gridbyexample.com/

*https://css-tricks.com/snippets/css/a-guide-to-flexbox/


text:
Q: Download zip file in web view in react native I'm trying to download file from a web view. I have used javascript inject to click on submit button.
I'm specifically trying this for offline aadhaar - https://resident.uidai.gov.in/offline-kyc
Reference Code -
            <WebView
                source={{ uri: "https://resident.uidai.gov.in/offline-kyc" }}
                ref={webviewRef}
                renderLoading={LoadingIndicatorView}
                startInLoadingState={true}
                injectedJavaScript={runFirst}
                onMessage={onMessage}
                renderError={loadError}
                // onFileDownload={({ nativeEvent: { downloadUrl } }) => {
                //     console.log(downloadUrl);
                //   }}
            />

I have tried with api request by creating/replicating the browser behaviour for api call but it's not working. Any suggestions.

A: You can try react-native-fs
You can use downloadFile API to download and save the file to the device.


text:
Q: AFNetworking vs SDWebimage I am developing a news app. Get the image and news from the server. I want to use cache to get the old news. And the custom can remove the cache when there is less disk storage.
The NSURLSession seems have bug for cache. So I decided to use AFNetworking or SDWebImage. But I don't know which one is suit for my app.

A: SDWebImage is very convenient especially with the progressive image download. But it's based out of NSURLConnection ( even in the latest version 3.7.5 ) and we know that that is deprecated starting iOS 9. NSURLSession has been around for 3+ years now. Surprisingly SDWebImage has still not migrated to NSURLSession.
See the SDWebImage: [Discussion] Migration to NSURLSessions.
AFNetworking 3.0 is completely based on NSURLSession. So I think AfNetworking would a better choice than SDWebImage.


text:
Q: Why the body of onStartCommand() is getting executed only once? To know the difference between IntentService and Service in Android, I created the below posted small test of a Service class. The MainActivity has a Button, when pressed, the
service will be started using startService() as shown below in the code, which will result in a call to onStartCommand(). In onStartCommand(), i run a loop for 10 seconds, and I
expected that, that loop will block the UI "the butoon". Actually that what happened exactly when I first time start the Service, but when I press the button after the 10 seconds
elapsed, it will result in a call to onStartCommand() but the log message inside the onStartCommand() never get displayed plus the UI is never blocked.
can anyone please explain what the body of the onStartCommand() is executed and blocks the UI only when the Service first started and never afterwards?
MainActivity
public class MainActivity extends AppCompatActivity {

private Button mbtnSend = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    this.mbtnSend = (Button) findViewById(R.id.btn_send);
    this.mbtnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(), MyService.class);
            startService(intent);
        }
    });
}
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    registerReceiver(this.mBCR_VALUE_SENT, new IntentFilter(MyIntentService.INTENT_ACTION));

    this.mbtnSend = (Button) findViewById(R.id.btn_send);
    this.mbtnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(), MyIntentService.class);
            intent.putExtra("intent_key", ++i);
            startService(intent);
        }
    });
}

}
MyIntentService:
public class MyService extends Service{
private final String TAG = this.getClass().getSimpleName();
private long mStartTime;

@Override
public void onCreate() {
    super.onCreate();
    Log.w(TAG, SubTag.msg("onCreate"));

    this.mStartTime = TimeUtils.getTSSec();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.w(TAG, SubTag.msg("onStartCommand"));

    while ( (TimeUtils.getTSSec() - this.mStartTime) <=10) {
        Log.w(TAG, SubTag.msg("time: " + (TimeUtils.getTSSec() - this.mStartTime)));
        SystemClock.sleep(1000);
    }

    return Service.START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    Log.w(TAG, SubTag.msg("onBind"));

    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.w(TAG, SubTag.msg("onDestroy"));
}

}

A: You are setting mStartTime to TimeUtils.getTSSec() in onCreate(), which means that it will get intialized only once.
Afterwards, onStartCommand() is called, but the mStartTime timestamp is not being updated, so the while loop never runs.
I believe that moving the line where you initialize mStartTime to onStartCommand() before the while loop will make your thread hang again.


text:
Q: Inverse of the function $\frac{(1+x)^2-i(1-x)^2}{(1+x)^2+i(1-x)^2}$ It can be proved that the function $f:[-1,1]\to \mathbb{C}$ defined by $$f(x)=\frac{(1+x)^2-i(1-x)^2}{(1+x)^2+i(1-x)^2}$$ maps the interval $[-1,1]$ one to one onto the lower part of the unit circle. Does anyone have an explicit formula for the inverse function $f^{-1}(\theta)=?, -\pi<\theta<0$? It seems unlikely, but I cannot be sure.

A: The angle $\theta$ that corresponds to $x$ is $$\theta=-2\tan^{-1}\left(\frac{1-x}{1+x}\right)^2,$$
so $$\frac{1-x}{1+x}=\sqrt{-\tan (\theta/2)}.$$
Solving for $x$ we get $$ x=f^{-1}(\theta)=\frac{1-\sqrt{-\tan (\theta/2)}}{1+\sqrt{-\tan (\theta/2)}}, -\pi<\theta<0.$$


text:
Q: One frontend for iPhone/iPad, Android and Multi-Touch displays I have built a multi-touch application which is based on a Java EE backend and combined with BlazeDS to a Adobe Flex frontend. The application runs on a DIY-Multi-Touch which I built. Now I want to use another solution. The Adobe Flex frontend (with a multitouch library) and the BlazeDS adapter should be replaced by a solution which covers iPhone/iPad, Android and commercial Multi-Touch displays.
The problem is the iPad/iPhone, there is no Flash Player runtime (not the jail-breaked ones), but the application should be runnable also on those devices. So Adobe Flex and a Java frontend (no JVM on the iPhone/iPad) is not possible anymore. At first, starting the developing of the application it was not neccessary, to run it on Apples mobile devices, but this changed :-(
So, what can I do, using HTML5? So I can use it for Android and iPhone/iPad. But I also want to make it possible to use it on a commercial multi-touch-display and normal display with a mouse (I only have gestures for one finger, the 2-finger gestures are not neccessary). Are there any frameworks that allow this? Because I do not want to create several frontends (App for iPhone/iPad on Objective-C and a Adobe Flex for all other devices), it would be great if I can build a frontend for all devices.
Does anyone know how I could realize this?
Best Regards Tim

A: Take a look at Sencha Touch, it's a HTML5 framework dedicated to iOS and Android devices, which should make it relatively easy to build web apps that feel like native apps on those devices.

A:
The Adobe Flex frontend (with a
  multitouch library) and the BlazeDS
  adapter should be replaced by a
  solution which covers iPhone/iPad,
  Android and commercial Multi-Touch
  displays.

Android 2.2 and higher supports the full Flash Player, and therefore also supports Flex applications.  However, Adobe has spoken of improving such support for the next Flex release, expected out early next year.
Apple has kind of specifically said they want to prevent the type cross platform development you're trying to accomplish.
Without knowing, or seeing, your application it is hard to say whether HTML5 will support you.  But, yes, many parts of HTML5 should work across multiple browsers.
You may want to investigate Elips Studio which brings ActionScript applications to multiple devices including apple devices.


text:
Q: Why does appending to innerHTML in a bookmarklet overwrite the entire page? I have this little bookmarklet:
javascript:document.getElementsByTagName("div")[0].innerHTML+="Chuck Norris";

Now it's obviously supposed to take the very first div on the page, and add Chuck Norris into it.
Instead, when pasted on the address bar, Chuck Norris overwrites the page.
Why is this so?
Note: this doesn't occur on Safari...

A: You are not cancelling the action. add void 0; to then end.
javascript:document.getElementsByTagName("div")[0].innerHTML+="Chuck Norris";void 0;

A: I'm not sure what the exact problem is, but I got it working by making a textNode and appending it:
javascript:var d=document.getElementsByTagName("div")[0];var n=document.createTextNode("Chuck Norris");d.appendChild(n);


text:
Q: A question about resistivity ( high school physics ) Resistivity = (Resistance times area ) divided by length
$$\rho = (RA)/l$$
now my question is that in order to calculate the resistivity for some metal we have to take into account its length and area then why is it said that the resistivity of a metal is independent of its area or length . i.e. Why does every piece of copper have the same resistivity regardless of its area or length?

A: One way to think about it is as an empirical law.  If you have a bunch of copper wires of varying lengths $l$, all with the same cross-sectional area, and you measure their resistances, you will find that the resistance is directly proportional to the length:
$$
R \propto l  \qquad \text{(constant $A$)}.
$$
Similarly, if you have a bunch of wires with different cross-sectional areas $A$, all with the same length, you will find that their resistance is inversely proportional to their area:
$$
R \propto \frac{1}{A}  \qquad \text{(constant $l$)}.
$$
Putting these two equations together, we have that $R \propto l/A$, or
$$
R = \rho \frac{l}{A}.
$$
for some proportionality constant $\rho$.  This number is what we define to be the resistivity of copper.
If you turn it around, and calculate $\rho = RA/l$, you're right that you'll get different numbers for $R$, $A$, and $l$ depending on what wire you're talking about.  But because of the above proportionalities, these differences will all cancel each other out.  For example, if you had two copper wires with the same $A$, but one was twice as long as the other, then the resistance $R$ of the longer wire would be twice as high as well.  The factors of two would cancel out, and you'd get the same value of $\rho$.

A: Because $R$ also depends on the dimensions of wire. Recall that:
 $$ R=\dfrac{m_e l} {n e^2 A \tau} $$
So, the resistivity is
$$\begin{align}\rho &=R\left(\dfrac {A}{l}\right)\\&=\left(\dfrac{m_e l}{n e^2 A \tau}\right )\left(\dfrac Al\right)\\&= \dfrac{m_e}{n e^2 \tau}\end{align}$$
This is independent of $A$ and $l$.

A: Another way to think about resistivity, as sammy gerbil alluded, is that it is analogous to density. Density is a property of a material, but mass is a property of a particular specimen of that material. Similarly, resistivity is a property of a material, but resistance is a property of a particular specimen of that material. Think about that for a minute. To calculate density, we normally measure the mass of a specimen, then calculate the density by dividing mass by volume. So, we need the dimensions of that specimen (because we need the volume) to determine the density. Same with resistivity; we need the dimensions of the particular specimen to relate resistance to resistivity. This is one of those distinctions that you will understand suddenly, not gradually. When you think about it the right way, at some point you will say "Ah, of course!"


text:
Q: faster way to handle T-SQL Result , alternative to CURSOR i am working on a  Report  to generate

*

*All Fleet movement  a temp table

*All Fleet Stops in a temp table set

*All Fleet idle in a temp table set

i have data like this
CREATE TABLE stops
    ([TripStopId] [int] IDENTITY(1,1) NOT NULL,[ObjectId] int, [DateFrom] varchar(23), [DateTo] varchar(23), [X] int, [Y] int, [ByIgnition] int, [BySpeed0] int, [BySpeed5] int, [BySpeed10] int, [BySpeed15] int, [ByCanSpeed0] int, [ByCanSpeed5] int, [ByCanSpeed10] int, [ByCanSpeed15] int, [GpsDistance] int, [CanDistance] int, [OdometerDistance] int, [Location] int)
;

INSERT INTO stops
    ([ObjectId], [DateFrom], [DateTo], [X], [Y], [ByIgnition], [BySpeed0], [BySpeed5], [BySpeed10], [BySpeed15], [ByCanSpeed0], [ByCanSpeed5], [ByCanSpeed10], [ByCanSpeed15], [GpsDistance], [CanDistance], [OdometerDistance], [Location])
VALUES
    (2729, '2016-01-27 06:21:51.320', '2016-01-27 06:22:27.070', 46.651984, 24.6881872, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0.0086855611934854, 0, 0, NULL),
    (2729, '2016-01-27 06:22:27.070', '2016-01-27 06:22:54.000', 46.652, 24.6881104, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0.0667479017095136, 0, 0, NULL),
    (2729, '2016-01-27 06:22:54.000', '2016-01-27 06:23:03.920', 46.651408, 24.68804, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0.0248830291828213, 0, 0, NULL),
    (2729, '2016-01-27 06:23:03.920', '2016-01-27 06:23:05.920', 46.6511616, 24.6880448, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0.00384351436414536, 0, 0, NULL),
    (2729, '2016-01-27 06:23:05.920', '2016-01-27 06:23:15.910', 46.651136, 24.6880704, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0.104523323509783, 0, 0, NULL),
    (2729, '2016-01-27 06:23:15.910', '2016-01-27 06:25:32.820', 46.6509376, 24.6889936, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1.57522938946324, 0, 0, NULL),
    (2729, '2016-01-27 06:25:32.820', '2016-01-27 06:25:53.810', 46.636304, 24.6873888, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0.0144023488655963, 0, 0, NULL),
    (2729, '2016-01-27 06:25:53.810', '2016-01-27 06:27:14.700', 46.6361632, 24.6874096, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0.00893761079401728, 0, 0, NULL),
    (2729, '2016-01-27 06:27:14.700', '2016-01-27 06:27:21.680', 46.6360864, 24.6873696, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0.0369525263958736, 0, 0, NULL),
    (2729, '2016-01-27 06:27:21.680', '2016-01-27 06:27:34.680', 46.6358208, 24.6871408, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0.0333843719279574, 0, 0, NULL),
    (2729, '2016-01-27 06:27:34.680', '2016-01-27 06:27:45.660', 46.6354912, 24.6871648, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0.114545761834751, 0, 0, NULL),
    (2729, '2016-01-27 06:27:45.660', '2016-01-27 06:35:00.480', 46.6346432, 24.6878496, 1, 1, 1, 1, 1, 0, 0, 0, 0, 7.52942986526197, 0, 0, NULL)
;

--
+----------+-------------------------+-------------------------+------------+------------+------------+----------+----------+-----------+-----------+-------------+-------------+--------------+--------------+---------------------+-------------+------------------+----------+
| ObjectId |        DateFrom         |         DateTo          |     X      |     Y      | ByIgnition | BySpeed0 | BySpeed5 | BySpeed10 | BySpeed15 | ByCanSpeed0 | ByCanSpeed5 | ByCanSpeed10 | ByCanSpeed15 |     GpsDistance     | CanDistance | OdometerDistance | Location |
+----------+-------------------------+-------------------------+------------+------------+------------+----------+----------+-----------+-----------+-------------+-------------+--------------+--------------+---------------------+-------------+------------------+----------+
|     2729 | 2016-01-27 06:21:51.320 | 2016-01-27 06:22:27.070 | 46.651984  | 24.6881872 |          1 |        0 |        0 |         0 |         0 |           0 |           0 |            0 |            0 | 0.0086855611934854  |           0 |                0 |          |
|     2729 | 2016-01-27 06:22:27.070 | 2016-01-27 06:22:54.000 | 46.652     | 24.6881104 |          1 |        1 |        1 |         0 |         0 |           0 |           0 |            0 |            0 | 0.0667479017095136  |           0 |                0 |          |
|     2729 | 2016-01-27 06:22:54.000 | 2016-01-27 06:23:03.920 | 46.651408  | 24.68804   |          1 |        1 |        1 |         1 |         1 |           0 |           0 |            0 |            0 | 0.0248830291828213  |           0 |                0 |          |
|     2729 | 2016-01-27 06:23:03.920 | 2016-01-27 06:23:05.920 | 46.6511616 | 24.6880448 |          1 |        1 |        1 |         0 |         0 |           0 |           0 |            0 |            0 | 0.00384351436414536 |           0 |                0 |          |
|     2729 | 2016-01-27 06:23:05.920 | 2016-01-27 06:23:15.910 | 46.651136  | 24.6880704 |          1 |        1 |        1 |         1 |         0 |           0 |           0 |            0 |            0 | 0.104523323509783   |           0 |                0 |          |
|     2729 | 2016-01-27 06:23:15.910 | 2016-01-27 06:25:32.820 | 46.6509376 | 24.6889936 |          1 |        1 |        1 |         1 |         1 |           0 |           0 |            0 |            0 | 1.57522938946324    |           0 |                0 |          |
|     2729 | 2016-01-27 06:25:32.820 | 2016-01-27 06:25:53.810 | 46.636304  | 24.6873888 |          1 |        1 |        1 |         1 |         0 |           0 |           0 |            0 |            0 | 0.0144023488655963  |           0 |                0 |          |
|     2729 | 2016-01-27 06:25:53.810 | 2016-01-27 06:27:14.700 | 46.6361632 | 24.6874096 |          1 |        0 |        0 |         0 |         0 |           0 |           0 |            0 |            0 | 0.00893761079401728 |           0 |                0 |          |
|     2729 | 2016-01-27 06:27:14.700 | 2016-01-27 06:27:21.680 | 46.6360864 | 24.6873696 |          1 |        1 |        1 |         0 |         0 |           0 |           0 |            0 |            0 | 0.0369525263958736  |           0 |                0 |          |
|     2729 | 2016-01-27 06:27:21.680 | 2016-01-27 06:27:34.680 | 46.6358208 | 24.6871408 |          1 |        1 |        1 |         1 |         1 |           0 |           0 |            0 |            0 | 0.0333843719279574  |           0 |                0 |          |
|     2729 | 2016-01-27 06:27:34.680 | 2016-01-27 06:27:45.660 | 46.6354912 | 24.6871648 |          1 |        1 |        1 |         1 |         0 |           0 |           0 |            0 |            0 | 0.114545761834751   |           0 |                0 |          |
|     2729 | 2016-01-27 06:27:45.660 | 2016-01-27 06:35:00.480 | 46.6346432 | 24.6878496 |          1 |        1 |        1 |         1 |         1 |           0 |           0 |            0 |            0 | 7.52942986526197    |           0 |                0 |          |
+----------+-------------------------+-------------------------+------------+------------+------------+----------+----------+-----------+-----------+-------------+-------------+--------------+--------------+---------------------+-------------+------------------+----------+

This data for each car move  and its start X,Y, AND total Distance,
any way better than CURSOR as i believe CURSOR is SLOW,  to make the following

*

*list all drives ,  and X,Y  from the start drive and x,y of the next drive stop
grouped by Objectid

*list all Stops ,  and its X,Y  as Stop mean time between each 2 drive rows
grouped by Objectid  "for same object in reportgroup"

i am asking about best way as this report can have more than 1 million tripstop row
Thats the expected result  i have by CURSOR , it take long time to output
    +----------+-------------------------+-------------------------+------------+------------+------------+------------+----------+----------+----------+----------+----------+--------+-----------+----------+-----------+----------+---------+--------------+--------------+------------+------------+---------------------+------------+----------+-------------+----------+
| ObjectId |        DateFrom         |         DateTo          |     X      |     Y      |     X2     |     Y2     | IsMoving | Distance | Location | AvgSpeed | DriverId | Driver | IButtonId | DateYear | DateMonth | DateWeek | DateDay | StartGeoName | StartAddress | EndGeoName | EndAddress | DeductionPointValue | PoiAtStart | PoiAtEnd | DrivingTime | StopTime |
+----------+-------------------------+-------------------------+------------+------------+------------+------------+----------+----------+----------+----------+----------+--------+-----------+----------+-----------+----------+---------+--------------+--------------+------------+------------+---------------------+------------+----------+-------------+----------+
|     2729 | 2016-01-27 06:21:51.320 | 2016-01-27 06:22:27.070 | 46.651984  | 24.6881872 | 46.652     | 24.6881104 |        0 | 0.01     |          | 0.87     | NULL     | NULL   | NULL      |     2016 |         1 |        5 |      27 |              | NULL         | NULL       | NULL       | 0.01                | NULL       | NULL     |           0 |    35750 |
|     2729 | 2016-01-27 06:22:27.070 | 2016-01-27 06:25:53.810 | 46.652     | 24.6881104 | 46.6361632 | 24.6874096 |        1 | 1.79     |          | 31.16    | NULL     | NULL   | NULL      |     2016 |         1 |        5 |      27 |              | NULL         | NULL       | NULL       | 1.8                 | NULL       | NULL     |      206740 |        0 |
|     2729 | 2016-01-27 06:25:53.810 | 2016-01-27 06:27:14.700 | 46.6361632 | 24.6874096 | 46.6360864 | 24.6873696 |        0 | 0.01     |          | 0.4      | NULL     | NULL   | NULL      |     2016 |         1 |        5 |      27 |              | NULL         | NULL       | NULL       | 1.81                | NULL       | NULL     |           0 |    80890 |
|     2729 | 2016-01-27 06:27:14.700 | 2016-01-27 06:35:00.480 | 46.6360864 | 24.6873696 | NULL       | NULL       |        1 | 7.71     |          | 59.62    | NULL     | NULL   | NULL      |     2016 |         1 |        5 |      27 |              | NULL         | NULL       | NULL       | 9.52                | NULL       | NULL     |      465780 |        0 |
+----------+-------------------------+-------------------------+------------+------------+------------+------------+----------+----------+----------+----------+----------+--------+-----------+----------+-----------+----------+---------+--------------+--------------+------------+------------+---------------------+------------+----------+-------------+----------+

A: I have not tested this to be sure that I have no errors, but something like this should do the trick.  The idea is to group values together based on the BySpeed0 column then aggregate.
WITH AdjacentValues AS (
  /*
  This adds the prior BySpeed0 value to the row
  */
  SELECT
    ObjectID,
    DateFrom,
    DateTo,
    X,
    Y,
    [BySpeed0] AS 'IsMoving',
    LAG([BySpeed0]) OVER (PARTITION BY ObjectID ORDER BY DateFrom ASC) AS 'PriorValue'
  FROM
    stops
), GroupedResults AS (
  /*
  This will create a number that increments every time the current BySpeed0 value is not the same as the next one.
  */
  SELECT
    ObjectID,
    DateFrom,
    DateTo,
    X,
    Y,
    IsMoving,
    NextValue,
    SUM(IIF(IsMoving <> PriorValue, 1, 0)) OVER (PARTITION BY ObjectID ORDER BY DateFrom ASC) AS 'GroupingValue'
  FROM
    AdjacentValues
), AggregateResult AS (
  /*
  This will Select the minimum date and maximum date for a particular grouping
  */
  SELECT
    ObjectID,
    MIN(DateFrom) AS 'DateFrom',
    MAX(DateTo) AS 'DateTo'
  FROM
    AdjacentValues
  GROUP BY
    ObjectID,
    GroupingValue
)
  /*
  This will add the X/Y information
  */
  SELECT
    R.*,
    A.X,
    A.Y,
    AA.X AS 'X2',
    AA.Y AS 'Y2'
  FROM
    AggregateResult R
  LEFT JOIN
    AdjacentValues A
  ON
    A.DateFrom = R.DateFrom
    AND A.ObjectID = R.ObjectID
  LEFT JOIN
    AdjacentValues AA
  ON
    AA.DateTo = R.DateTo
    AND A.ObjectID = R.ObjectID

P.S. If you are using spatial data at all, it would only take minor adjustments to turn these coordinate pairs into geometry/geography lines.

A: with cte as
(
select tripstopid,datefrom,dateto,x,y,byspeed0,
case when lag(byspeed0,1,'') over(order by datefrom,dateto) = byspeed0 then 0 else 1 end as ischange from stops
),cte1 as
(
select t.*,
 (select sum(ischange)  from cte where tripstopid <= t.tripstopid) groupno
from cte t
),cte3 as
(
select *,row_number() over(partition by groupno order by tripstopid) as rn1 from cte1
),cte4 as
(
select *from cte3
where rn1=1
)
select *from cte4 c1 left
join cte4 c2  on c1.groupno+1 =c2.groupno
order by c1.datefrom

A: This is the core query, where you can include your other calculated columns:
WITH CTE AS
(
SELECT S.*
FROM stops S
INNER JOIN
    (SELECT A.TripStopId AS TA, B.TripStopId AS TB
    FROM stops A
    INNER JOIN stops B ON A.ObjectId = B.ObjectId AND A.DateTo = B.DateFrom
    WHERE A.BySpeed0 = 0 AND B.BySpeed0 = 1) T ON S.TripStopId = T.TA OR S.TripStopId = T.TB
)
SELECT CTE.TripStopId, CTE.ObjectId, CTE.DateFrom, CTE.DateTo, CTE.X, CTE.Y, S.X AS X2, S.Y AS Y2, CTE.BySpeed0 AS IsMoving
FROM CTE
LEFT JOIN stops S ON CTE.ObjectId = S.ObjectId
    AND ((CTE.BySpeed0 = 0 AND S.BySpeed0 = 1 AND CTE.DateTo = S.DateFrom)
        OR (CTE.BySpeed0 = 1 AND S.BySpeed0 = 0 AND CTE.DateTo <= S.DateFrom))


text:
Q: To prove isomorphism and thereby find Quotient Ring of Gaussian Integers I am required to prove the following:

$\Bbb Z[i]/\langle a+bi\rangle\,\cong\Bbb Z/(a^2+b^2)\Bbb Z=:\Bbb Z_{a^2+b^2}$, where $\gcd(a,b)=1$.

While I have looked into the various solutions given here Quotient rings of Gaussian integers I wish to find a function $\phi:\Bbb Z[i] \to\Bbb Z_{a^2+b^2}$  such that $\phi$ is an onto ring homomorphism. According to the second answer in the aforementioned link I take such  $\phi (x + yi) = x-(ab)^{-1}y$ but I am unable to prove the multiplicativity of the ring homomorphism $\phi$ and its surjectivity.
PS. I want to prove the result using first isomorphism theorem.

A: The required homomorphism $\varphi:\Bbb Z[i]\to\Bbb Z/\langle a^2+b^2\rangle$ is defined by:
$$\varphi(x+iy)=x-avy+\langle a^2+b^2\rangle$$
where $v\in\Bbb Z$ is an inverse of $b$ modulo $a^2+b^2$ (note that $b$ is invertible because $\gcd\{a,b\}=1$).
To prove this, recall that $\Bbb Z[i]\cong\Bbb Z[x]/\langle x^2+1\rangle$ where $x$ is an indeterminate.
By universal property of polynomial ring $\Bbb Z[x]$, there exists one and only one ring homomorphism
\begin{align}\tag1
\Bbb Z[x]&\to\Bbb Z/\langle a^2+b^2\rangle&
x&\mapsto -av+\langle a^2+b^2\rangle
\end{align}
Since $(-av)^2+1=(a^2+b^2)v^2$, we have $(-av)^2\equiv-1\pmod{a^2+b^2}$, hence (1) gives rise to one and only one ring homomorphism $\varphi:\Bbb Z[i]\to\Bbb Z/\langle a^2+b^2\rangle$ such that $\varphi(i)=-av+\langle a^2+b^2\rangle$.
Clearly, for every $n\in\Bbb Z$ we have $\varphi(n)=n\varphi(1)=n+\langle a^2+b^2\rangle$, hence $\varphi$ is surjective.
On the other hand, if $x+iy\in\ker\varphi$, then $x\equiv avy\pmod{a^2+b^2}$, hence
$$x+iy=(x-avy)+(a+ib)vy$$
is a mutliple of $a+ib$ in $\Bbb Z[i]$.


text:
Q: how do i run an R script in batch mode by passing different arguments each time I have zero knowledge about running an R script in batch mode. I need to run an R script multiple times automatically by taking different arguments each time.
I want to create some kind of file which has some commands something like below (I have no knowledge about the commands too)
 COMMAND   myscript.R arg1 arg2
 COMMAND   myscript.R arg3 arg4
 COMMAND   myscript.R arg5 arg6
 COMMAND   myscript.R arg7 arg8
 COMMAND   myscript.R arg9 arg10

I want to run this file in the end and go to sleep.
Can someone please help me with create this file and instructions on how to run it?
I understand that I can spend some time on google to figure this out but I honestly don't have time to do that much research. My other plan backfired and have no other option left apart from somehow being able to run the script in batch mode. I need to finish this task overnight. Any help would be really appreciated. Thanks a lot.

A: You may use environment variables.  Something like
ARG1=arg1 ARG2=arg2 Rscript script.R
ARG1=arg3 ARG2=arg4 Rscript script.R
...

and later in the code you use `Sys.getenv("ARG1") etc.


text:
Q: Copying List of Files(with spaces in path) in .txt file to a Folder I need to copy some files separated line by line from a text file to a folder.
I have used the following command
cat list.txt | xargs -J % cp % folder

Since the file path has spaces in between, a File not found exception is thrown.How can I overcome this issue?
Please advice.

A: GNU parallel is also a good alternative to xargs, it handles input arguments well even when special characters (spaces, quotes) exists
$ cat list.txt | parallel cp {} folder/

A: try the following:
IFS=$'\n' && for i in $(cat list.txt); do cp "$i" folder/; done


text:
Q: ibm WebSphere MQ pausing the queue through java api I need to pause the receiver queue some time (for process the already received messages)  in ibm websphere queue through the ibm java api.

A: If you want to stop Applications from being able to get messages from a Queue you can inhibit the Queue by setting the GET attribute on the Queue to DISABLED. This will still allow applications to put messages to the Queue but no applications will be able to get messages from the Queue. IF you want to stop messages from being able to be put to a queue you can do this by setting the PUT attribute to DISABLED.
When you're ready for the applications to be able to get messages from the Queue again you set the GET attribute to ENABLED and applications will be able to get messages from the Queue.
example MQSC command to set GET to DISABLED

ALTER QLOCAL('') GET(DISABLED)

Be warned: If you inhibit the put or get on a Queue, applications attempting to put or get messages on that Queue will receive an error return code of MQRC_PUT_INHIBITED or MQRC_GET_INHIBITED. If you don't anticipate this your applications could fail.


text:
Q: Trigger not firing correctly on import? So I've written this trigger below. I am having issues with this trigger firing off when I import records. It's meant to reassign Lead owners from querying the system on certain factors, and it works fine inside Salesforce when you update or insert a record. The issue comes up when I try to insert via data loader.
To be clear, even if i insert one record via dataloader, the trigger does not fire.
Any insight into this issue would be great, thanks!
    trigger LeadReassignmentTrigger on Lead (before insert, before update) //after update before insert,
     {
    public Lead LeadRecordName {get;set;}
    public Contact contactInsert {get;set;}
    public QueueSobject Queue {get;set;}
    list<Id> LeadIdList = new list<Id>();
    public Account AccountRecordsName {get;set;}
    public Lead LeadInsert {get;set;}
    public integer Counter {get;set;}

      if(Lead_Trigger_Helper.runonce()){
    for(Lead leads : trigger.new)
    {
      LeadIdList.add(leads.id);

    }

    try{
                LeadInsert = [SELECT id,
                              email,
                              Ownerid
                              FROM Lead
                              //where Id IN: Trigger.newMap.keySet()
                              where id in : LeadIdList
                              //limit 1
                             ];
    }
    Catch(Exception e)

    {}
    try{
     contactInsert =        [SELECT email,
                             Ownerid
                             FROM Contact
                             where email =: LeadInsert.email
                             //limit 1
                             ];

    }
    catch(Exception e){

    }
//3.3

    //List<Contact> ContactRecords = [SELECT email, Ownerid FROM Contact where id in : LeadIdList];
    /*List<Lead> LeadRecords = [SELECT
                              email,
                              Lead.Lead_Lifecycle__c,
                              id,
                              ownerid
                              FROM Lead
                              where Id IN: Trigger.newMap.keySet()
                              //limit 1
                             ]; */

       // for (Lead LD: LeadRecords){
        for (Lead LD: Trigger.new){
            if(LD.Lead_Lifecycle__c == 'AQL' && LD.email == null){
                if(LD.Lead_Lifecycle__c == 'AQL' && LD.email == contactInsert.email){
                    if(LD.email != null){
     //List<Contact> ContactRecords = [SELECT email FROM Contact];
     //List<Lead> LeadRecords = [SELECT email FROM Lead where email =:ContactRecords.email];
             LD.OwnerId = contactInsert.ownerid;

                }

                 }

           // }

            }
            //leadrecords.add()
        }

    //update LeadRecords;

//3.3, number 2 FSR

   /* List<Lead> LeadRecordsName = [SELECT email,
                                  Lead.Lead_Lifecycle__c,
                                  id, ownerid,
                                  Company,
                                  name
                                  FROM Lead
                                  where Id IN: Trigger.newMap.keySet()]; */

                Queue =           [SELECT Id,
                                  queue.Name,
                                  QueueId
                                  FROM QueueSobject
                                  WHERE queue.Name = :'VP Queue'
                                  limit 1];
    try{
                 LeadRecordName = [SELECT email,
                                  Lead.Lead_Lifecycle__c,
                                  id,
                                  ownerid,
                                  Company,
                                  name
                                  FROM Lead
                                  where Id IN: Trigger.newMap.keySet()
                                  //limit 1
                                  ];
    }
          Catch (Exception e)
            {}

     try{
                AccountRecordsName =
                                  [SELECT id,
                                  Name,
                                  ownerid
                                  FROM Account
                                  where Name =: LeadRecordName.Company
                                  //limit 1
                                  ];
     }
            Catch (Exception e)
            {}
    try{
                 counter =
                                 [SELECT
                                  Count()
                                  FROM Accountteammember
                                  where accountid=:AccountRecordsName.id
                                  ];
    }
    catch (Exception e){}

        //for (Lead LD2: LeadRecordsName){
    for (Lead LD2: Trigger.new){

     //List<Lead> LeadRecordsName = [SELECT email, Lead.Lead_Lifecycle__c, id, ownerid, Company, name FROM Lead where Id IN: Trigger.newMap.keySet()];
        if(LD2.Company != null && counter != null)
        {
        if(LD2.Company == AccountRecordsName.Name && counter == 1)
        {
            if(LD2.Lead_Lifecycle__c == 'AQL'){

            try{
              Accountteammember AccountTeamMemberInfo = [SELECT
                                               accountid,
                                               userid,
                                               TeamMemberRole
                                               from Accountteammember
                                               where accountid=:AccountRecordsName.id
                                               limit 1];

        LD2.ownerid = AccountTeamMemberInfo.userid;
            }
            catch (Exception e){}
            }
        }

        if(LD2.Company == AccountRecordsName.Name && counter > 1)
            if(LD2.Lead_Lifecycle__c == 'AQL'){
                //&&
        {
                        //try{
             /*  Accountteammember AccountTeamMemberInfo = [SELECT
                                               accountid,
                                               userid,
                                               TeamMemberRole
                                               from Accountteammember
                                               where accountid=:AccountRecordsName.id
                                               ]; */

           // if(AccountTeamMemberInfo.TeamMemberRole == 'FSR')
           // {
            //Add FSR ISR Logic
            //Finish Query. Test?

                //}
            //}

             //catch (Exception e){}

            LD2.ownerid = queue.QueueId;

                        }
                    }

                }

            }

        }

      }

    //3.4, ISR

A: A couple things I would suggest:

*

*Break this down and get one task accomplished at a time even if in a
developer org or a separate sandbox.

*You do not need to use the getter and setter methods

*Before insert the Id of the lead will not be available so the keyset
will be null and your leadidlist will not have any ids.

*Eliminate all of your try and catch blocks and let the system handle
it since you are really just eliminating errors and not handling
them.

*You are still only grabbing the first email, assuming this is not
desired to use the 1st email on a lead for all remaining leads being
inserted.

*Add a system.debug at the beginning of your trigger and you should see that the trigger is indeed running but you are not getting the desired results

I would do suggest doing something like:

*

*Create a map of emails to the corresponding lead record.

*Use the email keyset to query the matching contacts.

*Create a map of emails to contactOwnerId

*Reloop through the new leads and check the contact email map to see
if it contains the lead email and update the ownerid.


text:
Q: Appending a script to  doesn't work, but writing it manually does? Chrome debugger renders them the same Why doesn't this work? I know the question is frowned upon, but in my case, I just can't seem to get why appending this script into head doesn't work the way I want it to.
It appends the script, I'm able to see it in the chrome debugger.  But I still get the error
tools.js:26 Uncaught ReferenceError: script_object is not defined
which doesn't make sense, because if I copy/paste the outerHTML directly from the chrome debugger (the one that was created by my script and appended to head), and paste it directly into my index.htm.  Then it works just fine.
Code:
var afterTools = document.getElementById("toolsId").nextSibling;
var script = document.createElement("script");
script.setAttribute("type","text/javascript");
script.setAttribute("src","scripts/thescript.js");

document.head.insertBefore(script, afterTools);

let temp = script_object;  // Object hardcoded in thescript.js
console.log(temp);

The script I'm appending after:
  <script id="toolsId" type="text/javascript" src="scripts/tools.js" defer></script>

What it boils down to is that chrome's debugger shows no difference between manually writing the script in, or appending it.  Yet it doesn't recognise the object within the script unless it's manually written.

A: tools.js:26 Uncaught ReferenceError: script_object is not defined

You are referencing a variable before it is instantiated. It must be available BEFORE referencing it, probably caused by the fact that you are using defer..

defer
This Boolean attribute is set to indicate to a browser that the
script is meant to be executed after the document has been parsed, but
before firing DOMContentLoaded. The defer attribute should only be
used on external scripts.

source: https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/script
So the browser is only executing it after your first code that depends on it, hence it is not available at that moment.


text:
Q: How to use identity aspnetusers I asked a question earlier but I don't think I asked it correctly.
in my asp.net mvc application I am using aspnetusers for my login and registration.
If I have another model for Employees containing their information, How do I connect these two models so when a user logs in, it grabs their information from the employee table to be used. I created the Employees Model with sql server and used ado.net entity data model to use it in visual studio.
Employee Model:
 public partial class Employee
{
    public int UserID { get; set; }
    [Key]
    public int EmployeeID { get; set; }
    public string FullName { get; set; }
    public string Email { get; set; }
    public System.DateTime StartDate { get; set; }
    public int RoleID { get; set; }
    public int ShiftID { get; set; }
    public int AreaID { get; set; }
    public int DisciplineID { get; set; }
    public int SiteID { get; set; }
    public int ALCategory { get; set; }
    public int HoursTaken { get; set; }
    public Nullable<int> AwardedLeave { get; set; }
    public Nullable<int> TotalHoursThisYear { get; set; }
    public int HoursCarriedForward { get; set; }
    public Nullable<int> EntitlementRemainingThisYear { get; set; }
    public string Comments { get; set; }
    public int SickLeaveTaken { get; set; }
    public Nullable<int> SickLeaveEntitlement { get; set; }
    public Nullable<int> SickLeaveEntitlementRemaining { get; set; }
    public int StudyLeaveEntitlement { get; set; }
    public int StudyLeaveTaken { get; set; }
    public Nullable<int> StudyLeaveRemaining { get; set; }
    public int ExamLeaveTaken { get; set; }
    public int ForceMajeure { get; set; }
    public int BereavementLeaveTaken { get; set; }
    public int MaternityLeaveTaken { get; set; }
    public int ParentalLeaveTaken { get; set; }
    public int AdoptionLeaveTaken { get; set; }
    public string ManagerEmail { get; set; }
    public string AreaManagerEmail { get; set; }

    public virtual Area Area { get; set; }
    public virtual Discipline Discipline { get; set; }
    public virtual Shift Shift { get; set; }
    public virtual Site Site { get; set; }
    public virtual Employee Employee1 { get; set; }
    public virtual Employee Employee2 { get; set; }
}

And the log-in model:
public class LoginViewModel
{
    [Required]
    [Display(Name = "Email")]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

So can I connect these two?
Does it matter that I use database first model?
Could I use a Foreign  Key to connect by email?
I want to use it for example to filter a table of employees to only show the employees who have the same siteID for the user logged in.
So when a user logs in, I want them to only see employees with the same site as themselves on the employee HTML table.

A: After successful login, you will get Id of AspNetUser. Take foreign key reference of column Id from AspNetUser table in your Employee table. By doing this, you can achieve expected result. Simply one more thing you need to add in your Employee model as mentioned below:
public virtual ApplicationUser ApplicationUser { get; set; }


text:
Q: Slater-Determinant: When is this appopriate? Imagine we have a N-particle Hamiltonian without any interaction between the electron particles
$$ H = \sum_{i=1}^{N} \frac{p_i^2}{2m} + V(r_i)$$
then the solution to this equation $H\Psi = E \Psi$ will be a product wavefunction $\Psi = \psi_1..\psi_N.$
Now for this Hamiltonian it is true that all permutation operators $P$ commute with the Hamiltonian.
This means that there is a system of eigenfunctions to the Hamiltonian and the permutation operators and the eigenfunctions can be found by antisymmetrizing the single particle wavefunctions (Slater determinant). For this Hamiltonian we can apparently find a system of eigenfunctions that is completely antisymmetric.
Now assume that we have a Hamiltonian that does NOT commute with all permutation operators, because it acts differently on the electrons. For instance
$$H = \frac{p_1^2}{2m} + \frac{p_2^2}{2m} + V_1(r_1) + V_2(r_2),$$ where $V_1$ is very different from $V_2.$
What does second quantization tell us in this case, when the permutation operator does not commute with the Hamiltonian, are the "right" eigenstates of the Hamiltonian still antisymmetrized states?
Is there any physical difference in a symmetric in $N$-particles Hamiltonian vs a non-symmetric one?

A:
Now assume that we have a Hamiltonian that does NOT commute with all
  permutation operators, because it acts differently on the electrons.
  For instance H=K+V_1(r1)+V_2(r2), where V_1 is very different
  from V_2.

In the honest-to-god physical world that we live in you can not have $V_1$ being very different from $V_2$ because all electrons are identical, i.e., indistinguishable.
The anit-symmetrization postulate of quantum mechanics was derived from observations based on the honest-to-god physical world that we live in--a world in which all electron are indistinguishable. So this question is absurd. [Note to mods: I do not mean "absurd" in a rude way]


text:
Q: Blur/focus event (delegeted) on inputs in iframe I have an iframe on a page. In iframe there are few inputs in a form tag and more can be loaded via ajax.
I'm tring to bind blur or focus event to this inputs but it doesn't work. Other events, such as click works very well.
$(function () {
    $("iframe").each(function () {
        $(this).load(function () {
            $(this).contents().find("input").focus(function() { // works but this is only for existing inputs
                alert(1);
            });
            $(this).contents().find("form").on("click", "input", function (e) { // works
                alert(1);
            });
            $(this).contents().find("form").on("focus", "input", function (e) { // doesnt work
                alert(1);
            });
        });
    });
});

Thanks in advance.

A: To select inputs and forms inside the iframe try this:
$(function () {
    $("iframe").each(function () {
        $(this).load(function () {
            $(this).contents().find('body').find("input").blur(function() {
                alert(1);
            });
        });
    });
});


text:
Q: Automate what type of HTML element to pick React I'd like to pick from headers h1-h6 using a prop, and then insert styles and text into the header. I have now:
import React from 'react';
import ReactLoading from 'react-loading';

import MyComponent from '../main/MyComponent';

export default class THDSpinner extends {
    constructor(props) {
        super(props);
        this.state = {};
    }

    render() {
        let header_size = `h${this.props.size}`;

        return (

Just a moment...Your request is being processed.

              <ReactLoading type="cylon" color="#F96302" />

        )
    }
}

THDSpinner.defaultProps = {size: 2}

I then realized I've never had to automate picking element types before and don't even know where to start. Can this be done with React, and how?

A: sure -- just create the element dynamically and compose it.
render(){
  const Tag = `h${this.props.size}`

  return <Tag>Just a moment...</Tag>
}

...

<Foo size={2} />


text:
Q: Exception handling within a constructor Can you use a throw or try-catch within a constructor?
If so, what is the purpose of having a constructor that has an argument that can throw an exception?
This constructor is an example:
public Chat()
{
    chatClient = new Client(Configuration.LoginEmail, Configuration.LoginPassword);
    chatRoom = chatClient.JoinRoom(Configuration.RoomUrl);
}

The line chatRoom = chatClient.JoinRoom(Configuration.RoomUrl); can throw exceptions.

A: Throwing an exception when appropriate is part of a constructor's job.
Let's consider why we have constructors at all.
One part is convenience in having a method that sets various properties, and perhaps does some more advanced initialisation work (e.g. a FileStream will actually access the relevant file). But then if it was really that convenient all the time we wouldn't sometimes find member initialisers convenient.
The main reason for constructors is so that we can maintain object invariants.
An object invariant is something we can say about an object at the beginning and end of every method call. (If it was designed for concurrent use we would even have invariants that held during method calls).
One of the invariants of the Uri class is that if IsAbsoluteUri is true, then Host will be string that is a valid host, (if IsAbsoluteUri is false Host might be a valid host if it's scheme-relative, or accessing it might cause an InvalidOperationException).
As such when I'm using an object of such a class and I've checked IsAbsoluteUri I know I can access Host without an exception. I also know that it will indeed be a hostname, rather than e.g. a short treatise on mediaeval and early-modern beliefs in the apotropaic qualities of bezoars.
Okay, so some code putting such a treatise in there isn't exactly likely, but code putting some sort of junk into an object certainly is.
Maintaining an invariant comes down to making sure that the combinations of values the object holds always make sense. That has to be done in any property-setter or method that mutates the object (or by making the object immutable, because you can never have an invalid change if you never have a change) and those that set values initially, which is to say in a constructor.
In a strongly typed language we get some of the checking from that type-safety (a number that must be between 0 and 15 will never be set to "Modern analysis has found that bezoars do indeed neutralise arsenic." because the compiler just won't let you do that.) but what about the rest?
Consider the constructors for List<T> that take arguments. One of them takes an integer, and sets the internal capacity accordingly, and the other an IEnumerable<T> that the list is filled with. The start of these two constructors are:
public List(int capacity)
{
    if (capacity < 0) throw new ArgumentOutOfRangeException("capacity", capacity, SR.ArgumentOutOfRange_NeedNonNegNum);

/* … */

public List(IEnumerable<T> collection)
{
    if (collection == null)
        throw new ArgumentNullException("collection");

So if you call new List<string>(-2) or new List<int>(null) you get an exception, rather than an invalid list.
An interesting thing to note about this case, is that this is a case where they could possibly have "fixed" things for the caller. In this case it would have been safe to consider negative numbers as the same as 0 and null enumerables as the same as an empty one. They decided to throw anyway. Why?
Well, we have three cases to consider when writing constructors (and indeed other methods).

*

*Caller gives us values we can use directly.

Eh, use them.

*Caller gives us values we can't meaningfully use at all. (e.g. setting a value from an enum to an undefined value).

Definitely throw an exception.

*Caller gives us values we can massage into useful values. (e.g. limiting a number of results to a negative number, which we could consider as the same as zero).

This is the trickier case. We need to consider:

*

*Is the meaning unambiguous? If there's more than one way to consider what it "really" means, then throw an exception.

*Is the caller likely to have arrived at this result in a reasonable manner? If the value is just plain stupid, then the caller presumably made a mistake in passing it to the constructor (or method) and you aren't doing them any favours in hiding their mistakes. For one thing, they're quite likely making other mistakes in other calls but this is the case where it becomes obvious.
If in doubt, throw an exception. For one thing if you're in doubt about what you should do then it's likely the caller would be in doubt about what they should expect you to do. For another it's much better to come back later and turn code that throws into code that doesn't than turn code that doesn't throw into code that does, because the latter will be more likely to turn working uses into broken applications.
So far I've only looked at code that can be considered validation; we were asked to do something silly and we refused. Another case is when we were asked to do something reasonable (or silly, but we couldn't detect that) and we weren't able to do it. Consider:
new FileStream(@"D:\logFile.log", FileMode.Open);

There's nothing invalid in this call that should definitely fail. All validation checks should pass. It will hopefully open the file at D:\logFile.log in read mode and give us a FileStream object through which we can access it.
But what if there's no D:\logFile.log? Or no D:\ (amounts to the same thing, but the internal code might fail in a different way) or we don't have permission to open it. Or it's locked by another process?
In all of these cases we're failing to do what is asked. It's no good our returning an object that represents attempts to read a file that are all going to fail! So again, we throw an exception here.
Okay. Now consider the case of StreamReader() that takes a path. It works a bit like (adjusting to cut out some indirection for the sake of example):
public StreamReader(String path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
{
    if (path==null || encoding==null)
        throw new ArgumentNullException((path==null ? "path" : "encoding"));
    if (path.Length==0)
        throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
    if (bufferSize <= 0)
        throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
    Contract.EndContractBlock();

    Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan, Path.GetFileName(path), false, false, true);
    Init(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, false);
}

Here we've got both cases where a throw might happen. First we've got validation against bogus arguments. After that we've a call to the FileStream constructor that in turn might throw an exception.
In this case the exception is just allowed to pass through.
Now the cases we need to consider are a tiny bit more complicated.
With most of the validation cases considered at the beginning of this answer, it didn't really matter in what order we did things. With a method or property we have to make sure that we've either changed things to be in a valid state or thrown an exception and left things alone, otherwise we can still end up with the object in an invalid state even if the exception was thrown (for the most part it suffices to do all of your validation before you change anything). With constructors it doesn't much matter what order things are done in, since we're not going to return an object in that case, so if we throw at all, we haven't put any junk into the application.
With the call to new FileStream() above though, there could be side-effects. It's important that it is only attempted after any other case that would throw an exception is done.
For the most part again, this is easy to do in practice. It's natural to put all of your validation checks first, and that's all you need to do 99% of the time. An important case though is if you are obtaining an unmanaged resource in the course of a constructor. If you throw an exception in such a constructor then it will mean the object wasn't constructed. As such it won't be finalised or disposed, and as such the unmanaged resource won't be released.
A few guidelines on avoiding this:

*

*Don't use unmanaged resources directly in the first place. If at all possible, work through managed classes that wrap them, so it's that object's problem.

*If you do have to use an unmanaged resource, don't do anything else.
If you need to have a class with both an unmanaged resource and other state, then combine the two guidelines above; create a wrapper class that only deals with the unmanaged resource and use that within your class.

*Better yet, use SafeHandle to hold the pointer to the unmanaged resource if at all possible. This deals with a lot of the work for point 2 very well.

Now. What about catching an exception?
We can certainly do so. The question is, what do we do when we've caught something? Remember that we have to either create an object that matches what we were asked for, or throw an exception. Most of the time if one of the things we've attempted in the course of that fails, there isn't anything we can do to successfully construct the object. We're likely therefore to just let the exception pass through, or to catch an exception just to throw a different one more suitable from the perspective of someone calling the constructor.
But certainly if we can meaningfully continue on after a catch then that's allowed.
So in all, the answer to "Can you use a throw or try and catch within a constructor?" is, "Yes".
There is one fly in the ointment. As seen above the great thing about throwing within a constructor is that any new either gets a valid object or else an exception is thrown; there's no in between, you either have that object or you don't.
A static constructor though, is a constructor for the class as a whole. If an instance constructor fails, you don't get an object but if a static constructor fails you don't get a class!
You're pretty much doomed in any future attempt to make use of that class, or any derived from it, for the rest of the life of the application (strictly speaking, for the rest of the life of the app domain). For the most part this means throwing an exception in a static class is a very bad idea. If it's possible that something attempted and failed might be attempted and succeed another time, then it shouldn't be done in a static constructor.
About the only time when you want to throw in a static constructor is when you want the application to totally fail. For example, it's useful to throw in a web application that lacks a vital configuration setting; sure, it's annoying to have every single request fail with the same error message, but that means you're sure to fix that problem!

A:
Can you use a throw or try and catch within a constructor?

Both are possible.
If an exception can happen during construction of an object instance, and there is something you can do about it, catch it and try to fix it.
If there is nothing you can do about the exception, it is generally best to allow it to propagate (rather than leaving the object instance in an improperly initialized state).

A: The normal lifecycle of an object is interrupted if an exception is thrown in a instance constructor. So if the object has a destructor to clean up any resources then an exception thrown in the constructor will prevent the destructor running and thus forms a memory leak. Always catch, clean up, and re-throw if you have any disposable resources allocated in the constructors or for any fields.
If an exception is thrown in a static constructor then the class is no longer in a state that can be used by the AppDomain. So always catch exceptions in static constructors and deal with them. Do not re-throw and do not leave them uncaught.
Catching and handling exceptions in any constructor is fine to do.
But as per normal, it is 1000x better to code to avoid exceptions rather than let them occur.
See MSDN Constructor Design & Eric Lippert's Vexing Exceptions.


text:
Q: JavaScriptSerializer :After serialization Date becomes less by one day  JavaScriptSerializer js = new JavaScriptSerializer();
 var result = js.Serialize(data);

This is my model:
 public class EmployeeDetailsDTO : IEmployeeDetailsDTO
 {
    public int EmployeeId { get; set; }
    public string EmployeeName { get; set; }
    public Datetime date{get;set;}
 }

I Passed this serialized object into webapi from an MVC application through the
 body of the request.But in my webapi controller the date become one less(11-02- 2018 is changed into 10-02-2018).
but when i used this code the problem is solved.Did anybody know what is happening?
 var data = JsonConvert.SerializeObject(data);

webapi is deserializing the data for me.so explicitly writing (.ToLocalTime();) is not possible in this case.


text:
Q: How do I make a GUI appear when a specific part is touched? local TDHitbox = script.Parent
local Enemy = game.Workspace.Enemy
local GUI = game.Players.LocalPlayer.ScreenGui.TextLabel

TDHitbox.Touched:Connect(function(hit)
    local humanoid = hit.Parent:WaitForChild("Humanoid")
    if humanoid then
        GUI.TextTransparency = 0
    else
        GUI.TextTransparency = 1
    end
end)

This is the code I have written,I don't see any errors when I test it.But it still doesn't work

A: LocalPlayer can't be called from the server (I presume the script is located inside a part in the workspace).
You'd need to set up remote events. Read the documentation on Remote Functions and Events


text:
Q: bash script , how to optionally log to log file, and/or console I'm trying to create a bash script that prints results optionally to the console (STDOUT and STDERR), a log file or both.
I've got the getops working to set the options, but I can't seem to figure out the command.  So far, I have something like this:
# default logs to both
export LOG_COMMAND=" 2>&1 | tee ${INSTALL_LOG}"

if [ "$ONLY_CONSOLE" == "true" ] ; then
  export LOG_COMMAND=""
elif  [ "$ONLY_LOG" == "true" ] ; then
  export LOG_COMMAND=" | tee ${INSTALL_LOG}"
fi

echo "Starting script" ${LOG_COMMAND}
# ... then do more stuff ...

This script prints this to the console only and nothing to the log file:
Starting script 2>&1 | tee scriptfile.log

But I would like the script to print to the console and to the file scriptfile.log.
Has anyone done this before?  It appears that the echo command is processing the ${LOG_COMMAND} as a variable.
Replacing the echo command with this works will print both:
echo "Starting script" 2>&1 | tee -a ${INSTALL_LOG}

However, this means that there is no option to print to console, log file, or both.  It is hard coded to print to both.

A: There is definitely more than one way to do this, but the easiest may be to keep things simple.
After getopts is done and you've figured out what goes where, you use that to call main in the correct manner, and put all the rest of your logic in main (or called from main).  For example:
main() {
  # do stuff
  # call other functions
  # do more stuff
}

if [ $ONLY_CONSOLE -eq 0 ]
then
  main
elif [ $ONLY_LOG -eq 0 ]
then
  main > $INSTALL_LOG 2>&1
else # both
  main 2>&1 | tee $INSTALL_LOG
fi

The alternative is an arcane combination of execs and other flow, but for a small number of options, this just makes the most sense to me.


text:
Q: How to display a system account with the highest user id root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
polkitd:x:999:998:User for polkitd:/:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
chrony:x:998:996::/var/lib/chrony:/sbin/nologin
adilfanta:x:1000:1001::/home/adilfanta:/bin/bash
scripty:x:1001:1002::/home/scripty:/bin/bash
brencklen1:x:1002:1003::/home/brencklen1:/bin/bash

So above I have a list of system accounts. I am trying to figure out how I can display a system account with the highest user id.
For example, let's say I only want to display this
script:x:1001:1002::/home/script:/bin/bash

cat /etc/passwd | grep scripty

I was gonna do this grep command above but I can not assume script has highest user id for every system.

A: With awk:
awk -F':' '$3 > maxid{ maxid=$3; line=$0 } END{ print line }' /etc/passwd