Modifying server side text file

Question: Currently I am working on static HTML website. Now I am using following javascript code to read server side text file:
<!DOCTYPE html>

content

<button type="button" onclick="loadXMLDoc()">Change Content</button>

Here on click event data is just displayed.But now I want to change the content of text file on click event.I want to increment the number by 1 which resides in the file as content.
Please help me to do this...Thank you so much in advance.!!
EDIT:
I am using windows hosting.
Comment: You need to post to the server and have the server update the file. You need a server process like PHP
Comment: Server side text files can't be modified from client side .. you can only as much as send the instruction to the server to modify it.
Comment: If it was possible to simply update any text file on a server via Javascript, no website would be alive for more than 2 seconds... You need a server-side language to cooperate here.
Answer: You may do it like this
This is the index page. I have done it in JSP.
index.jsp
<!DOCTYPE html>

content

    <button type="button" onclick="loadXMLDoc()">Change Content</button>

Then the server side coding
newjsp.jsp
<%@page contentType="text/html" pageEncoding="UTF-8" import="java.io.*"%>
<%
    try {
        BufferedReader in = new BufferedReader(new FileReader("C:/Users/sar/Documents/NetBeansProjects/WebApplication1/web/results.txt"));
        // change the path to the txt file
        String line;
        int a = 0;
        if((line = in.readLine()) != null)
            a = Integer.parseInt(line)+1;
        else
            a = 1;
        PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Users/sar/Documents/NetBeansProjects/WebApplication1/web/results.txt"));
        // change the path to the txt file
        pw.println(a);
        pw.close();
        out.println(a);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
%>

You will have to create a results.txt file at the location specified.

Modifying server side text file


How to print text in a box of asterisks in an output file?

Question: I am working on the following hw question, and am now just trying to fine-tune my code...
Write a program that takes in a file that has a message. The message can be any length.
Your program will contain two functions. The first should have a function that processes the contents of the file. The second will take the output from the first function and will print the message in a box of asterisks.
The input file should just be a single-lined message (see attached input example). The output should take that message, split it between two lines, and center it in the box
This is my current code:
import textwrap

def func1():
    infile=open("october.txt", "r")
    'Pull text from file and assign it to process_contents variable'
    process_contents=infile.read()
    return process_contents

def asterisk_box(width, height):
    'Create a box of asterisks and return it as a string'
    box = '*' * width + '\n'
    for i in range(height - 2):
        box += '*' + ' ' * (width-2) + '*\n'
    box += '*' * width
    return box

def asterisk_message(width, height, message):
    'Put a message within the asterisk box'
    assert len(message) <= height  # Make sure there is room for a message
    assert len(message) <= width  # Make sure the box is wide enough
    box = asterisk_box(25,20)
    box = box.splitlines()
    row = height // 2
    box[row] = "*" + message.center(width) + "*"
    box[row] = textwrap.fill(message,4)
    return '\n'.join(box)

def func2():
    outfile=open("october_output.txt", "w")
    print(asterisk_message(30,25, func1()), file=outfile)
    outfile.close()

func2()

The code I have will only work with a very small word like "hello"; with any longer message, the 'assert' kicks in and the code won't run. Is there any way to make the box of asterisks automatically expand or compress based on the length of my message? I was trying to use textwrap to compress longer messages to fit into the box, but doing that is leaving me with weird formatting & is messing up the asterisk box, like so:

*************************
*                       *
*                       *
*                       *
*                       *
*                       *
*                       *
*                       *
*                       *
*                       *
*                       *
*                       *
so l
et's
try
long
er?
*                       *
*                       *
*                       *
*                       *
*                       *
*                       *
*************************

Answer: width = 30
message = "This is a test"
msg_ary = message.split(' ')
message1 = ' '.join(msg_ary[0: len(msg_ary) // 2]).center(width, ' ')
message2 = ' '.join(msg_ary[len(msg_ary) // 2:]).center(width, ' ')

print('*' * (width + 4))
print(f'* {message1} *')
print(f'* {message2} *')
print('*' * (width + 4))

> **********************************
> *            This is             *
> *             a test             *
> **********************************

Since this is homework, some explanation:
width = 30:   Just some arbitrary width I chose, just as long as it fits your text.
msg_ary = ...... : Split the message by words (spaces) to make the break into to not split a word
messag1 = ...., message2 = .... : make the array in to a sentence again, note the handy call to "center" at the end : )


Reference numeric identifier from postively predicted target

Question: I built a machine learning model that was able to accurately predict potentially fraudulent customers. My dataset is around 12,000 observations and around 43 features(and around 147 after I one hot encoded several features). Each row corresponds to a different customer, and I have a feature called CUSTOMER_NUMBER which contains each customer's numeric identifier(so since there are around 12,000 customers there are around 12,000 unique numeric identifiers). Since this feature is an identifier, I do not include it in the machine learning model itself and I drop it from my original dataframe(along with other features such as date,etc.)
 df = df.drop(['CUSTOMER_NUMBER','TRANSACT_DT','CUSTOMER_NAME'],axis=1)

After running my model
 #get this loss year:
 #train loss year =2014-2016
 #test loss year = 2017
 this_year = 'LY_' + str((pd.to_datetime('today').year)-1)

#partition train and test set by this LY
train = df.loc[df[this_year] == 0]
test = df.loc[df[this_year] == 1]

X_train =train.drop(['Target_Variable'],axis=1)
X_test =test.drop(['Target_Variable'],axis=1)
y_train = train['Target_Variable']
y_test = test['Target_Variable']
training_data = X_train,y_train
test_data = X_test,y_test

clf2= SVC(C=100,kernel='linear',class_weight='balanced')

#class_weight = class_weight.compute_class_weight('balanced', np.unique(y_train), y_train)
clf2.fit(X_train, y_train)
X = df.drop(['Target_Variable'],axis=1)

#define the predicted estimators
y_pred = clf2.predict(X_test)

and evaluating my true positive rate, I was able to predict the some of rows where df['Target_Variable'] ==1. However, although I'm able to get a list the predicted 1's by print(y_pred==1) it does me no good if I do not know which customer number (which I dropped from my dataframe) it corresponds to. Thus I was wondering if someone could help me figure out how to get the customer numbers that correspond to y_pred==1? Or should I not drop the feature df['CUSTOMER_NUMBER'] and include it in my model? If so, would it alter my predictive results since it is just a unique numeric identifier?
Comment: It's better to don't drop columns and instead write a list of `features`.  you then can call  `clf2.fit(X_train[features], y_train)`.
Then I'd suggest to use `df[df[this_year] == 0]` instead of `df.loc[df[this_year] == 0]`.
Answer: I agree with the first comment. You shouldnt include 'CUSTOMER_NUMBER' as feature. Since every number is unique, it doesnt add any value to your model. Just create a subset of features
clf2.fit(X_train[features], y_train)

and when you want to know the 'CUSTOMER_NUMBER'
df.loc[df['y_pred'] == 1, 'CUSTOMER_NUMBER']


In FarCry 3 is there an easier way of finding your kills than stumbling upon the body?

Question: I often lose my kills in the grass and brush, even after tagging them with the camera or by aiming at them.  Is there any better way of finding them than having to search?
Even with the flashing texture, I often I can't see it until I'm right on top of the corpse.
Answer: Unfortunately, no. Other then the bright flashing texture, there is no indication. Roaming around the area looking for the pulsating texture is the best you can do.
Comment: sadly this is the case. Luckily you wont need to hunt for that long to have everything maxed / near maxed out
Comment: Yeah, I'm starting to see that. I've only done a couple story missions and I'm up to most of my craftables needing skins from the Hunting side missions.


Cannot Access Remote Network IP & Host from Openvpn server

Question: I have installed OpenVPN server on Ubuntu 14 in my LAN and I have configured OpenVPN client on DD-WRT router at remote site, same client connected to OpenVPN server and can able to access server side host successfully (ERP or Mail).
Now I'm not able to ping from server LAN network or OpenVPN server to remote host.
My server config
port 4096
proto udp
mode server
tls-server
dev tun
ca ca.crt
cert server.crt
key server.key
dh dh2048.pem
auth SHA512
tls-auth ta.key 0
topology subnet
server 172.30.30.0 255.255.255.0
ifconfig-pool-persist ipp.txt
client-to-client
push "route 192.168.0.0 255.255.255.0"
route 22.214.171.124 255.255.255.0 172.30.30.3
#push "dhcp-option DNS 184.108.40.206"
#push "dhcp-option DNS 220.127.116.11"
#push "redirect-gateway def1"
keepalive 10 120
cipher AES-256-CBC
comp-lzo
persist-key
persist-tun
status openvpn-status.log
verb 3
#crl-verify crl.pem

Client config
client
dev tun
proto udp
remote xx.xx.xxx.xx 4096
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
auth SHA512
cipher AES-256-CBC
comp-lzo
key-direction 1
verb 3

Current Routing & Firewall on Server
netstat -rn
Kernel IP routing table

Destination Gateway Genmask Flags MSS Window irtt Iface
0.0.0.0 192.168.0.1 0.0.0.0 UG 0 0 0 ens33
172.20.20.0 172.30.30.3 255.255.255.0 UG 0 0 0 tun0
172.30.30.0 0.0.0.0 255.255.255.0 U 0 0 0 tun0
192.168.0.0 0.0.0.0 255.255.255.0 U 0 0 0 ens33

Current Routing & Firewall INFO on Client DD WRT
route -n
Kernel IP routing table

Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.20.1 0.0.0.0 UG 0 0 0 eth0
127.0.0.0 0.0.0.0 255.0.0.0 U 0 0 0 lo
169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 br0
172.20.20.0 0.0.0.0 255.255.255.0 U 0 0 0 br0
172.30.30.0 0.0.0.0 255.255.255.0 U 0 0 0 tun1
192.168.0.0 172.30.30.1 255.255.255.0 UG 0 0 0 tun1
192.168.20.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0

I tried to enable NAT & disable NAT at DD-WRT, still the server side cannot access any remote host even from VPN server.
Appreciate for your time and if any solution available, if I can access remote LAN host from OpenVPN server end.
Anybody can help, everything is working except, the server side, cannot ping to OpenVPN client configured on DD-WRT route & its LAN host?
Top
-Thanks,
 Sam
Answer: You have configured server.conf and created a self signed certificate, but after that you have missed a step. After creating self signed certificates, edit the server.conf file again and give a path to the certificates in the server folder:
ca /file_path/ca.crt
cert /file_path/server.crt
key /file_path/server.key
dh /file_path/dh2048.pem


mojarra jsf api / impl 2.1.12 prints out css comments

Question: i switched the implementation from 2.1.3 up to 2.1.12 mojarry.
But now i can see in any IE Explorers the CSS switch comments:

is now visible instead off rendering this.
Means, in my source code the characters  get escaped with lt and gt.
this comes from the api change. does someone had the same expierence ?
thanks !
Answer: You can use <h:outputText escape="false"> to render it the way you want:
<h:outputText value="<!--[if lt IE 7]><div>...</div><![endif]-->" escape="false" />

Or you can use OmniFaces <o:conditionalComment> to keep it less scary:
<o:conditionalComment if="lt IE 7">

...

</o:conditionalComment>

Comment: thanks BalusC, this is an option but not the way it should usually goes. can you confirm, that this is a bug ? thanks and regards


Calculating Percentile Score for every value in the list

Question: I've been searching for a way to calculate the percentile rank for every value in a given list and I've been unsuccessful thus far.
org.apache.commons.math3 gives you a way to fetch the pth percentile from a list of values but what I want is the opposite. I want to have a ranking for every value in the list. Is anyone aware of a library or a way in Apache commons math to achieve that?
For example: given a list of values {1,2,3,4,5}, I'd want to have the percentile rank for every value with the maximum percentile being 99 or 100 and the minimum being 0 or 1.
Updated code:
public class TestPercentile {

public static void main(String args[]) {
    double x[] = { 10, 11, 12, 12, 12, 12, 15, 18, 19, 20 };
    calculatePercentiles(x);
}

public static void calculatePercentiles(double[] arr) {
    for (int i = 0; i < arr.length; i++) {
        int count = 0;
        int start = i;
        if (i > 0) {
            while (i > 0 && arr[i] == arr[i - 1]) {
                count++;
                i++;
            }
        }
        double perc = ((start - 0) + (0.5 * count));
        perc = perc / (arr.length - 1);
        for (int k = 0; k < count + 1; k++)
            System.out.println("Percentile for value " + (start + k + 1)
                    + " = " + perc * 100);
    }
}}

Sample Output:
Percentile for value 1 = 0.0
Percentile for value 2 = 11.11111111111111
Percentile for value 3 = 22.22222222222222
Percentile for value 4 = 50.0
Percentile for value 5 = 50.0
Percentile for value 6 = 50.0
Percentile for value 7 = 50.0
Percentile for value 8 = 77.77777777777779
Percentile for value 9 = 88.88888888888889
Percentile for value 10 = 100.0

Can someone let me know if this is correct and if there is a library for doing this more cleanly?
Thank you!
Comment: What about you show what you've tried
Comment: I've made the updates!
Answer: It really depends on your definition of percentile. Below is a solution using NaturalRanking and rescaling to 0-1 interval. It is nice that NaturalRanking has a few strategies for handling equal values and nans already implemented.
import java.util.Arrays;
import org.apache.commons.math3.stat.ranking.NaNStrategy;
import org.apache.commons.math3.stat.ranking.NaturalRanking;
import org.apache.commons.math3.stat.ranking.TiesStrategy;

public class Main {

    public static void main(String[] args) {
        double[] arr = {Double.NaN, 10, 11, 12, 12, 12, 12, 15, 18, 19, 20};

        PercentilesScaledRanking ranking = new PercentilesScaledRanking(NaNStrategy.REMOVED, TiesStrategy.MAXIMUM);
        double[] ranks = ranking.rank(arr);

        System.out.println(Arrays.toString(ranks));
        //prints:
        //[0.1, 0.2, 0.6, 0.6, 0.6, 0.6, 0.7, 0.8, 0.9, 1.0]
    }
}

class PercentilesScaledRanking extends NaturalRanking {

    public PercentilesScaledRanking(NaNStrategy nanStrategy, TiesStrategy tiesStrategy) {
        super(nanStrategy, tiesStrategy);
    }

    @Override
    public double[] rank(double[] data) {
        double[] rank = super.rank(data);
        for (int i = 0; i < rank.length; i++) {
            rank[i] = rank[i] / rank.length;
        }
        return rank;
    }
}


Can I play Final Fantasy 3 (mobile) with any jobs?

Question: I'm playing Final Fantasy III (remake, mobile) and I choose not to use any black magic casters. I was planning on not using those for the whole game but I was forced too: when your whole team are mini, physical performs very poorly. It seems like you can't go through that part without a black or red mage. Now I'm wondering:

Am I going to be forced to use black magic again ? Should I keep at least 1 black mage in my team ?
Are there any other jobs that you absolutely need to train to complete the game?

I'd rather know early so I can train in those jobs.
Comment: why are the mages not getting any love?
Comment: If I recall there is a boss that is VERY difficult (possibly impossible) without a Dragoon. But other than that the game can be beaten using any combination of people.
Comment: @Quinma Probably because [they smell](http://www.nuklearpower.com/2001/08/25/episode-071-sometimes-he-should-really-keep-quiet/).
Answer: Any combination will work. It's been a while since I went through the 'small' part, but even then you should just buy some basic dmg spells, and temp switch other classes to lowbie casters. In fact, for 99% of the game, black magic is weak, and vastly overshadowed by any melee: while the 9,999 dmg cap is visually reported, my knight and monk have hit for 59,999 (at lvl 98/job level 99) (per achievement page, so this is probably the hard internal cap). There is also certainly no need for a dragoon. If a boss is hard, keep levelling up, then come back.
Simply choosing your favorite classes is fine (a white mage, for heals, though, is recommended).


Why doesn't my gcc compiler recognize the bzip2 functions, yet allows me to include the library they belong to?

Question: I'm writing a file parser in C using gcc on Windows using MSYS2.
Using pacman I've downloaded the required libraries for using libbzip2.
For some reason, I can include the bzlib.h file and use the structures it contains, but not its functions.
Here's my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <bzlib.h>

void init_decompress_stream(bz_stream *stream, char *next_in, unsigned int avail_in, char *next_out, unsigned int avail_out);

int main(){
  // Open FILE
  FILE *ptr;
  ptr = fopen("example.bin", "rb");

  // Read Metadata
  int metadata[10];
  fread(metadata, sizeof(int), 10, ptr);

  // Init stream
  bz_stream *stream;
  unsigned int avail_in = metadata[0] * sizeof(char);
  unsigned int avail_out = metadata[1] * sizeof(int);
  char *compressed_data = malloc(avail_in);
  char *data = malloc(avail_out);

  // Read data
  fread(compressed_data, 1, avail_in, ptr);
  init_decompress_stream(stream, compressed_data, avail_in, data, avail_out);

  // Decompress data -- COMPILES FINE UNTIL HERE --
  int bz_result = BZ2_bzDecompressInit(stream, 0, 0);
}

void init_decompress_stream(bz_stream *stream, char *next_in, unsigned int avail_in, char *next_out, unsigned int avail_out){
  stream->next_in = next_in;
  stream->avail_in = avail_in;
  stream->next_out = next_out;
  stream->avail_out = avail_out;
}

This all compiles fine until the last line of main: int bz_result = BZ2_bzDecompressInit(stream, 0, 0);
when I compile using at which point I get the error:
C:/msys64/bin/../lib/gcc/x86_64-w64-mingw32/10.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\{User Name}\AppData\Local\Temp\cct30tb5.o:test.c(.text+0xc4): undefined reference to 'BZ2_bzDecompressInit'
collect2.exe: error: ld returned 1 exit status
While troubleshooting I've used three different compile commands:
gcc test.c This compiles #include <bzlib.h> and bz_stream *stream; just fine until the last line.
gcc test.c -L/usr/lib/libbz2.a this performs same as above.
gcc test.c -libbz2 this one cannot find -libbz2
I'm totally perplexed as to what I'm doing wrong.
Answer: In gcc, -L add a directory to the library search path, and -l specifies a library to load (using the search path to find it).
Hence you probably need something like:
gcc test.c -L /usr/lib -l bz2

I'd be surprised if /usr/lib wasn't already on the library path but you may want to specify it just in case. And the toolchain is smart enough to prefix your library names with lib and suffix them with extensions as needed.
You should be aware that gcc test.c -libbz2 is probably equivalent to gcc test.c -l ibbz2 which is going to be looking for ibbz2, not what you wanted.


Error NoClassDefFoundError on Android 5 but it's Working on Higher Android Versions like 8, 9, 10

Question: I'm frustrating for a while due to this error, I have an Android app and it's working fine on my phone(android version 8), and my moms(version 10) but not working on my sisters tablet with android version 5. the error happens when the app is going to create a ClientConfig object to sending a sms after entering phone number for registration. it syas:
Method threw 'java.lang.NoClassDefFoundError' exception.

and here is the stack trace:
0 = org.glassfish.jersey.client.ClientConfig$State.<init>(ClientConfig.java:160)
1 = org.glassfish.jersey.client.ClientConfig.<init>(ClientConfig.java:515)
2 = com.xyz.asd.services.UserServices.RegisterNewUser(UserServices.java:48)

also the cause says:
java.lang.NoClassDefFoundError: org.glassfish.jersey.model.internal.CommonConfig

although I can see there is

jersey-common-2.27.jar
and I can locate CommonConfig on the package org.glassfish.jersey.model.internal.

and these are some settigs:
   compileSdkVersion 30
    minSdkVersion 14
    targetSdkVersion 30
    multiDexEnabled true

I have cleaned up Android Studio's gradle and all caches, cleaned the project, used some Dex options but nothing happened. before sending read all related wuestions about NoClassDefFoundError on stack overflow with o gain.
I will appreciate any help...
Answer: after googling and trying some ways, sugar saved me!
compileOptions {
        coreLibraryDesugaringEnabled true
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

then we need to add :
dependencies {
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9'
    ....
}

and it's working fine...
here is some description of sugar:
java-8-in-android-apps
and this is the resource at develper:
Use Java 8 language features and APIs


WebStorm has marked all files in a directory as non-project files

Question: WebStorm has marked all files in a subdirectory of my project (the server portion of the root) as non-project files.
It happened sometime during my conversion to Babel and then again to TypeScript. I've removed the TypeScript stuff, wondering if it's something to do with that configuration. I believe it's just a WebStorm setting somewhere - because my tests run, builds work, all that.
Whenever I refactor or rename a file it says:

"Selected element is used from non-project files. These usages won't be renamed. Proceed anyway?"

It also highlights the code in these files differently.
Each of these file's icons has a small x in the top corner.
In their docs it says that these are " non-project files (e.g, library sources, external sources etc." This makes me think at some point I just marked a whole folder external at some point, thought I don't know where that could be.
Update I've tried deleting .idea folder and then running invalidate cache and restart. This didn't fix it either.
The myProject.iml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
  <component name="NewModuleRootManager">
    <content url="file://$MODULE_DIR$">
      <excludeFolder url="file://$MODULE_DIR$/.tmp" />
      <excludeFolder url="file://$MODULE_DIR$/temp" />
      <excludeFolder url="file://$MODULE_DIR$/tmp" />
    </content>
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
  </component>
</module>

Comment: can be related to https://youtrack.jetbrains.com/issue/WEB-30895; please check your `.idea/workspace.xml` - do you have any entries like `` with `` in it?
Answer: Close all Webstorm windows and from project folder in terminal run:
rm -rf .idea

Note: deleting from within Webstorm is not enough.
Comment: This seems like a good solution, since I don't have this issue anymore I'm not sure how to verify it - so I'll upvote it but not mark as accepted.
Comment: Worked for me too,  Webstorm thought all my files were external after I had deleted and re-cloned my project.
Comment: In Windows, We need to close WebStorm completely (I have even quit the Toolbox also). After that, go to inside the parent folder of .idea folder and open command prompt from that location and execute this command: `rd /s /q ".idea"`
Comment: Since Jono stated the issue was gone before trying this solution, I can instead verify that this solution worked. Upvote granted. Thanks for this solution!
Comment: it works. looks like it is related to the miss config stuffs
Answer: I had the same problem and none of these solutions didn't work.
Just right-click on the folder that has been marked as none-project, then click on Mark directory as, then click on Cancel Exclusion or Not Excluded and enjoy features of project-files :'))
screenshot of: how to mark none-project folder, as project folder


How can I write variables inside PHP query with LIMIT

Question: I'm trying to get some data from MySql database - but when I'm adding variables after LIMIT and LIMIT at all - I don't get anything from DB.
Where's the problem?
<code>$start = $_POST["start"];
$limit = $_POST["limit"];
$link = mysqli_connect("localhost", "root", "root", "admins");
$result = mysqli_query($link , "SELECT * FROM pikabu_news WHERE id>'".$start."' LIMIT '".$start."','".$limit."'");
</code>
Comment: by using prepared statement. This way = SQL injection - and that's a BIG no no..
Comment: `id` and your `limit` probably aren't related. That is the number of rows to return, and where to start the offset at.
Comment: SQL tables/resultsets are by SQL standards definition **orderless**, using `LIMIT` without `ORDER BY` is pretty much **meaningless**.. In fact using `LIMIT` without `ORDER BY` without atleast using a column that has a primary key or unique key would cause non deterministic (random) results
Answer: <code> "SELECT * FROM pikabu_news WHERE id>'".$start."' LIMIT '".$start."','".$limit."'");
</code>
has to be
<code> "SELECT * FROM pikabu_news WHERE id>".$start." LIMIT ".$start.", ".$limit);
</code>
You don't need to give <code>'</code> in limit values.
Passing parameters like this would lead to SQL Injection.
Comment: I'd do a prepared statement example (or mark as dupe to the other posts) to encourage safer querying :)
Comment: OMG, the truth was so near.
Thank You!
Comment: @НикитаЛямный welcome, mark it as answered if that solved your problem.
Comment: SQL tables/resultsets are by SQL standards definition **orderless**, using `LIMIT` without `ORDER BY` is pretty much **meaningless**.. In fact using `LIMIT` without `ORDER BY` without atleast using a column that has a primary key or unique key would cause non deterministic (random) results
Comment: limit is just used to limit the dataset, maybe, he is fetching the data for pagination, getting a limited dataset and sending it back via json or anything. There could be multiple reasons where it can be used even without order. @RaymondNijland
Comment: i know how limit works @DanyalSandeelo Yes if you like playing russian roulette with your resultset, mine previous statement/comment is mentioned in the MySQL [manual](https://dev.mysql.com/doc/refman/8.0/en/limit-optimization.html)  *"If it is important to ensure the same row order with and without LIMIT, include additional columns in the ORDER BY clause to make the order deterministic. For example, if id values are unique, you can make rows for a given category value appear in id order by sorting like this: "*
Comment: We have a system we CDRs (call detail records are added). The insertion takes place via a cron job. For example, I want to view those million records with no order, I just want to view them in the way they were stored. Calling a server side pagination would be fine there. Not sure if I am getting your point correctly or not.


How should a Bronze Protoss defend probes mid game?

Question: I'm Bronze Protoss and I have an issue with losing lots of workers to harasses - either pure air or drops, usually not long after 1st expansion.
Being Bronze I only have one strategy - cannons on the mineral line (when I remember to do that) and maybe I leave a few stalkers behind too.
What options does a limited skill player like myself have?  Should I continue with cannons and work on more aggression?  How many defender units (if any) should I leave in my main and natural expansion? Any other advice on how to better protect my economy?
Comment: I would also work on trying to predict drop-play or air assaults.
Answer: Try to have vision of your entire base. Place Pylons at the edges so that you know when a drop is about to happen. Keep an eye on the mini map.
This should give you more time to react.
When a drop happens and it is clearly targeted at your workers and potent enough to cause major damage evacuate. Just select all of your workers and move them away. At least momentarily. The short time that you don't mine is easily made up by saving most of your workers. Workers (unlike your gateway units) take a lot of time to built! Make sure your workers are on the way to safety and then get your army to defend against the drop.
Once the drop is cleared don't forget to get your workers back to work (and don't forget to put them back on the Vespene too).
If the drop is small and early in the game you may also attack with your workers directly. For example if there are a couple Zerglings or a few marines and I can surround them with my workers I usually do. Later in the game this is usually not such a good idea since upgraded Zerglings or Marines with stim-pack can really cause havoc on your workers.
Scouting is another thing that is crucial in any game and it can give you good hints how likely worker harass will be.
As a Protoss player your army is better if you have them together. I wouldn't recommend leaving parts of your army behind. If you know that a drop is very likely, placing a cannon or two is more cost effective than leaving units and is also a safeguard against any cloaked units harassment (Dark Templar/ Banshee etc.).
Answer: Part 1: Detection
Early detection is a key.
The 1st thing you MUST do is scouting (getting map vision) and looking at the mini-map. You can say, that is hard. No, it is not correct. It is VERY hard. And it is very important. If you are controlling a XelNaga tower (usually they are located in the map center) but not looking at the minimap - that gives nothing to you.
Try to put pylons on the edges of your base. Outside of the base... You will see much more area and will have much more time to react. Often opponent forces (Mutas, Banshees, etc) are send with 'Attack' command, then they will begin to kill your cheap pylon (with 400 HP), instead of expensive probes that are slow to be build.
Also good to have a few observers patrolling the edges of the opponent's base. In this case you will see out-coming dropships.
Part 2: Early prevention
If you have some air units - it is always good to harass dropships with them. If you are building for another army - don't keep you air force in center of the map. Put few phoenixes patrolling those ares that are not covered with XelNagas/Pylons.
Besides scouting they will often kill those dropships... and give you time to react if they are overwhelmed by other units (mutas, vikings, Voidrays, etc).
Part 3: Saving probes
Once medivac/WarpPrism/Overlord/NydusChannel/Mutalisks/Banshees, etc detected:
As other answers tell: get you probes out first. Be sure they are not currently attacking. To do so select all of them with BIG BOX and right click on the minimap to he most defendable place in your base. Usually that is your gateways' rally point, or location where the army is concentrated.
If your probes are followed by hellions - that won't help too much: hellions kill "lined" probes easily. Try to split your probes in a few (2-3) groups and send them to a little bit different directions.
You also need to do that quickly, each second of delay could cost you an additional probe lost.
Part 4: Take your army to deny aggression
Once you have detected that the opponent is doing a drop - don't panic. Don't pull ALL of your army to mineral lines. If he has 1 medivac - just take 8 stalkers. Ok, you can take 12, but not ALL 30!!! Otherwise he will do a front attack (it is not a case on Bronze level, but if you are asking here, guess you are going to be at least gold, right?).
It is good to bring some flying units too. Even though stalkers often are good to kill opponent's ground army, you will want to kill their air too. But while stalkers are shooting the ground - air forces could withdraw.
As Protoss you have Warp Gates. Usually, that is one of the first technologies to be researched. Therefore, after you have ordered your army to attack back to the mineral line - warp-in all stalkers that you can.
Part 5: Restoration

Take all your probes back to the mineral line. DON'T forget about gas!!! (usually people forget about and are left with no gas..)
Build new probes (you should do that constantly, but currently is a good additional check-point for that).
Analyze if it is possible to make another drop through the same way. If so - build at least 1 cannon. Probably two - but not more.
Analyze if there is another way to made a drop. If so - build at least 1 cannon there.

If you have at least 1 expand - it not a a big deal to have 2-3 cannons to defend the mineral line. If you have 2 or more expansions - it is ok to have 2-3 cannons to defend it right after building (it will pay for itself quickly, and usually 'late'-expansions are far away from your base and are hard to defend.
But:

Don't over-invest in static defense (otherwise, if you build 5 cannons per mineral line - your opponent will have 750 minerals more in the army - 7 zealots or 4-5 stalkers);
Don't invest in static defense too early

Others
I wouldn't recommend to keep your army in the mineral line in general. But there are few exceptions. If you have detected opponents medivac/warpprism leaving base, but not sure from which direction to expect a drop. In this case it will be reasonable to get your stalkers back to the mineral line for some time. But right after that I would add some cannons (1-2 - not more). For bronze/silver level - that is ok, later you will learn how to prevent expected drops without cannons.
Answer: Harassment is one of the primary strategies that are genuinely effective against Protoss, especially as Terran. Protoss usually deal with it by leaving their army in their base(s), and then pushing out and pressuring their opponent, forcing them to use all units to defend.


Send date to an activity.

Question: I moved Integers and also serialized object to another activity but now I'm stuck
with move java.util.Date to my activity ,that sound like nothing but if I'll get an answer here.
It might be the first on the net.
Comment: Can you use sharedPrefs?
Comment: convert the date to string or long and sent it through extra
Answer: From the current activity:
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("date", dateObj.getTime());
startActivity(intent);

From next activity:
Date dateObj = new Date(getIntent().getExtras().getLongExtra("date", -1));

You should pass the time as a long value and convert it back on the other activity to avoid date parsing from string issues on different devices.
Comment: you can also just pass the long to the constructor and it will take care of it.
Answer: In the calle class try:
Intent intent = getIntent();
intent.putExtra("Date",dateSelected);
setResult(RESULT_OK, intent);
finish();

And, in the new activity:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if(resultCode==RESULT_OK && requestCode==1) {
    Bundle mBundle = data.getExtras();
    String mMessage = mBundle .getString("Date");
  }
}

Answer: this is how i ended my issue
Intent i = new Intent(this, EventListActivity.class);
    i.putExtra("date",date);
    startActivityForResult(i, Intent.EXTRA_DOCK_STATE_DESK);

and the get:
Date date = (Date) this.getIntent().getExtras().get("date");

it look like it works ,what you think about it,what is the best way?
Comment: You should pass the date as a long value and convert it back in the other activity to avoid date-parsing-from-string issues on different devices with different locales. See my answer below. :)

Send date to an activity.


jQuery. make menu float to the right of parent?

Question: Sorry the title is a bit misleading. I have a menu that I want to float to the top-right of its parent div. So that the menu begins to drop from the same height as its parent's top. I know I can use margin-left:100% to make the menu float to the right of the parent. But right now the menu begins to drop from the bottom right corner of the parent. However, trying to use margin-top to line the tops up causes the menu to expand upwards to reach the top instead of beginning at the top and dropping down.
Here is the base code I was using :      http://jsfiddle.net/4jxph/915/
<code>margin-left:100%
</code>
So to put it simply. I'd like the menu to begin at the top right corner of the parent div rather than the bottom corner.
Comment: well u see how the jfiddle menu begins to drop from the bottom of the parent div? I want it to drop from top of the div (and to the right) like most side menus.
Answer: You need to set the position of the button to relative and the position of the drop down to absolute. Like this:
<code>#button {
    height: 32px;
    width: 184px;
    margin: auto;
    position: relative;
}
.file_menu {
    display:none;
    width:300px;
    border: 1px solid #1c1c1c;
    position: absolute;
    left:100%;
    top:0px;

}
</code>
See here: http://jsfiddle.net/T946y/


Hyperledger Composer query not working

Question: I'm developing an application using Hyperledger composer and its related part of the model file as bellows.
abstract participant Stakeholder {
 o String name
 o Address address
 o String email optional
 o String telephone optional
 o Certification certification optional
 o String[] images optional
 o Company company
 o String username
 o String password
}

participant Farmer identified by stakeholderId extends Stakeholder {
 o String stakeholderId
 o String description optional
 --> Farm[] farms
}

I'm trying to retrieve specific farmers by their username using below query.
query getUserFromUsername{
description:"get user from username"
statement:
        SELECT org.ucsc.agriblockchain.Stakeholder
          WHERE  (username == _$username)
}

But it does not work as expected. Here, since Farmer is not the only stakeholder in the system, the Stakeholder abstract participant is used.
Any suggestions?
Answer: You can move the  identified by stakeholderId to the abstract participation as mentioned below.

abstract participant Stakeholder identified by stakeholderId{
 o String stakeholderId
 o String name
 o Address address
 o String email optional
 o String telephone optional
 o Certification certification optional
 o String[] images optional
 o Company company
 o String username
 o String password
}

participant Farmer  extends Stakeholder {
 o String description optional
 --> Farm[] farms
}

To query for getUserFromUsername

query getUserFromUsername{
  description:"get user from username"
  statement:
    SELECT org.ucsc.agriblockchain.Farmer
    WHERE  (username == _$username)
}
Comment: It's my pleasure :-)
Answer: Because it is an abstract type, there is no data for the "Stakeholder" registry.  You need to query the Farmer registry ... SELECT org.ucsc.agriblockchain.Farmer ...
Changing Stakeholkder from abstract to concrete won't help either if Farmer extends it because the Farmer will still be part of the Farmer registry.
I'm not sure exactly what you are wanting to achieve from the model, but you could revert to a single Participant type with optional fields for the different Stakeholder types, otherwise just write separate queries for the different Participant Types, and collate the results yourself in your code.
Update Following Comment
That Query against the Farmer registry should work.
Couple of hints ...

If you have changed the model or the Query, remember to stop and restart the REST server so that it can Discover the changes.
If you have changed the model, create some new test data.
If you are testing with the REST server, when you enter the parameter for the username, do not use quotes round the value.

(If you still have problems, please post the whole model, the latest query, and some example data that you are using in JSON format.)
Comment: Thanks. Can't I use a query like "SELECT org.ucsc.agriblockchain.Farmer           WHERE  (username == _$username) ". It seems not working either.
Comment: yes you can use. It needs to match entirely, what's stored in your `username` field and the executing user needs to be able to read the Farmer registry (ie not restricted via ACLs).  You should be able to try it out using REST API query endpoint - or, if you're calling the query from a transaction function, can you paste how you're calling it.

Hyperledger Composer query not working


Where does the term "dropship" come from?

Question: I'm talking about those things:

They fly about in the sky, and when they land, enemy soldiers come out of them and try to kill you. Almost every video game has them, yet there is no such thing as a "dropship" in modern military. Where does the term come from?
Comment: There are plenty of such things in the military, they just don't have rocket engines and descend from space.
Comment: I'm voting to close this question as off-topic because I don't think it belongs on this site; an expert gamer is not more likely to be able to answer this question than a complete non-gamer.
Comment: It's used in science fiction in general, and is not exclusive to gaming. Nonetheless, since it has no real-life use, it might be of general interest to gamers.
Comment: C-130 Hercules, V-22 Osprey, C-17 Globemaster, H47 Chinook, etc. are all famous  (U.S.) military "dropships" in real life. The concept of airborne troop transport is as old military use of aircraft -- it predates even WWII.
Comment: I'm voting to close this question as off-topic because it is a better fit for Scifi.stackexchange (where this term originates from far longer than the scope of video games), or even english.stackexchange, for etymology purposes.
Comment: May be on topic at [scifi.se]
Comment: @AzulShiva That's debatable, but not a game term exclusively in any case. I also doubt that a long-standing member of this community is aimlessly clicking on buttons. I didn't close it at first, like I mentioned, but I don't see any proper ground to reopen it.
Comment: I'm trying to find the first game to use it, which would be a first step. There is Starcraft in 98 (Terran Dropship) but there's also Dune 2 in 92 (Harkonnen Drop-ship) although, it was taken from a concept art for the 84 movie.
Comment: It was also used in Battletech manuals and in Sci-Fi magazine/journals as the term for this type of craft ~1986/1987. [Interesting ngram search?](https://books.google.com/ngrams/graph?content=dropship%2Cdrop-ship&year_start=1800&year_end=2016&corpus=15&smoothing=3&share=&direct_url=t1%3B%2Cdropship%3B%2Cc0%3B.t1%3B%2Cdrop%20-%20ship%3B%2Cc0#t1%3B%2Cdropship%3B%2Cc0%3B.t1%3B%2Cdrop%20-%20ship%3B%2Cc0). Anything before 1985 seems to describe a method of shipping products from catalogues straight from manufacturer, rather than stock
Comment: @Fana The game Cosmic Ark (1982) has a small ship that drops from the mothership and returns to it.
Comment: I thought it came from Starship Troopers, though I may be misremembering.
Comment: @DJClayworth this seems to be the full text of Starship Troopers https://archive.org/stream/StarshipTroopersRobertHeinlein/Starship_Troopers_-_Robert_Heinlein_djvu.txt  but I don't see the term.  And the serialized version (Starship Soldier) part 1: https://archive.org/stream/Fantasy_Science_Fiction_v017n04_1959-10_PDF/Fantasy__Science_Fiction_v017n04_1959-10_PDF_djvu.txt and part 2: https://archive.org/stream/Fantasy_Science_Fiction_v017n05_1959-11_PDF/Fantasy__Science_Fiction_v017n05_1959-11_PDF_djvu.txt
Comment: @DJClayworth I see where it says "The other half are the spaceships that drop us and the capsules we drop in" though.
Comment: @senpai the word dropship is not in the english dictionary. Dropship became popular with games, not science-fiction comic books.
Comment: Question is not off-topic: https://gaming.stackexchange.com/help/on-topic

3rd point: Game mechanics and terminology

Dropship is a game term. Read rules before aimlessly clicking on buttons
Comment: @Joachim It doesn't matter wether it's a game term exclusively or not. It is a game term. And it's not an official word.
Comment: Everything points to the word being a word used in (science) fiction. And your second point depends on how one interprets 'official' in this context. If the meaning is obvious but the use is irregular and niche, it can still be a perfectly fine word absent from dictionaries.
Answer: The term "dropship" was used in the December 1983 issue of Isaac Asimov's Science Fiction Magazine in the story "Remembering Siri" by Dan Simmons.
Page 36:

There were only five of us in the dropship. It was always a thrill to me to fall out of high orbit into the atmosphere of a real world.

Used also on pages 38 and 62.
Much earlier, in the July 1960 Amazing Science Fiction Stories in "All the Stars a Stage" by James Blish:
page 84

There was the beginning of a
muted stir throughout the Javelin, as battle gear and drop
ships began to be readied.

There is a very detailed 1978 description in Analog Science Fiction/science Fact (also in Best Science Fiction of the Year, Volume 7):

Because Celia's father was in the mining business, Lisa Maria batted her eyes at a handsome drop-ship jockey and he took them out to see one of the drop-ships being scrapped in a flickering of cutting torches. These were perhaps the heaviest spaceships ever built by man, rivaling in weight battleships of the Yamato class, but had only one flight in them, down. The jockeys who rode them to Earth called them rafts. They were assembled crudely of massive metal in a low orbit and needed to be able to perform only two functions: to hold together while they burned off their heat shield in the atmosphere and to float when they hit the water. Sometimes they were scrapped at Tongaro and sometimes towed all the way to San Francisco or San Diego or Yokahama.

But the oldest example is not from science fiction.  Instead it is an actual military drop ship.
Richard C. Hottelet was a reporter who flew along with the 24 March 1945 Operation Varsity and wrote in a 5 May 1945 article in Collier's Magazine:

hundreds of C-47s flying along in tight formation ...
The three photographers, their cameras clicking away, jostled one another at the waist windows as we swooped around the drop ships.
P-Hour, the drop hour for the paratroops, was 10 a.m.

So the original "drop ships" were C-47s.
Comment: Hey, DavePhD, funny seeing you with a "New contributor" tag.
Comment: "**fall** out of high orbit".  **This** is what a dropship is.  **Shuttles fly** out of the mothership, but dropships are... **dropped**.  That's why they're called **drop**ships, not shuttles.
Comment: @RonJohn On the contrary, in the earliest sense it was the *cargo* that dropped, not the ship. (At least if all went well.)
Answer: The term was popularized in Aliens(1986), where the military shuttle is referred to Cheyenne Dropship. Concept of dropship is very similar to space shuttle, a small craft meant to ferry passengers or cargo around.
What Aliens did, essentially, was to popularize term dropship to specifically refer to military shuttles. Shuttlecraft (another term not from real world, but borrowing term shuttle from the real world) had already been codified by Star Trek to specifically mean small craft meant to travel between mothership and planetary bodies for short distances, as opposed to longer distance made by starships.
Dropships do not exist in real world because the term was specifically coined for scifi. However, there have been concepts of a dropship for Mars travel, where a mothership "drops" shuttles into Martian athmosphere and they travel the rest of the way on their own power. In essence, being dropships, or dropshuttles.
TL;DR
Aliens called military shuttles dropships first (as far as I have been able to find) and everyone else followed the lead. Possible term variants might have existed before, but Aliens is the trope codifier.
Comment: Actually just on the above, ngram seems to suggest there might have been a use of the word dropship in the 1940s, and then a significant surge in use from the early 60s. https://books.google.com/ngrams/graph?content=dropship&year_start=1900&year_end=2000&corpus=15&smoothing=3&share=&direct_url=t1%3B%2Cdropship%3B%2Cc0#t1%3B%2Cdropship%3B%2Cc00 That said, the leap of use after 1986 when Aliens releases - is massive - and definitely marks a solid point where it became suddenly more popular.
Comment: Yeah, which is why I decided to cite Aliens as the source. IIRC the "drop ships" (two words instead of one) of Starship Troopers serve as different role from the "dropship"(single word). That is to say, their job to fly to combat zone and literally DROP the MI and maybe later come pick them up as slower pace. Where as the dropship, as popularized by Aliens, has dropships land, deploy troops and then take off. Effectively, they are military tactical air/space transports (Something like Osprey, Blackhawk or Chinook).
Comment: First know usage of term "dropship" comes from Aliens. There is no real story beyond that. Aliens creators used the term dropship and everyone followed the example of "military shuttles are known as dropships". There is no records of where the Aliens writers got the name. Most likely they just made it up on the spot.
Comment: Added extra mention that Aliens might not be original source of the term, but it is the one that codified the term.
Comment: Just finished editing my post.
Comment: The only thing that *could possibly* be added (that is, I've not been able to verify it as I don't have a copy of the Starship Troopers novel to hand) - is that the use in Alien *might* come from Starship Toopers. https://avp.fandom.com/wiki/UD-4L_Cheyenne_Dropship (see "Behind The Scenes" -> "Design"). Definitely it seems in the book, the act of landing on a planet from the ship is known as a "drop". Really hard to verify though, as all sources discussing it use the term "dropship" freely as it's become part of standard sci-fi vocabulary.
Comment: As per the design section: "The name itself is likely taken from Robert A. Heinlien's [sic] 1959 novel *Starship Troopers*, in which similar craft are used to deploy ground forces on other planets". Google Ngram shows the first occurence of the word around 1943 (wanted to post that as answer based on another answer that has been deleted, but figured it might be considered an attack on this answer :).
Comment: As noted, "likely taken", not "taken". We are not sure. Also, term might have been used before *but* it didn't achieve its meaning until Aliens, when it was commonly accepted to mean "military transport shuttle". If you look at pre-Alien and post-Alien uses of "dropship", post-Alien dropship strongly resemble use and design (in rough terms) to that of Aliens dropship. That is to say, a military transport craft.

Also, I don't take someone posting alternative answer as an attack. This is supposed to be "questions and answers", not just an answer.
Comment: Good point. But didn't achieve what?
Comment: If you consider the Mars dropships (i.e. shuttle to atmo) as fitting the "dropship" designation (i.e. troops to ground), then I'm going argue in favor of the [Curiosity Sky Crane](https://www.youtube.com/watch?v=p1WX0CATyn8) already being an existing example of such a Martian dropship. It fits the designation even better because it actually drops its payload on the surface instead of somewhere in atmo.
Comment: Well, main difference (as far as I have read) is that the hypothetical Mars dropship (which is purely a concept at this point, not an actual thing) would actually be able to leave. The Curiosity Sky Crane is closer to what is commonly known as a drop pod. A pod that contains stuff and gets dropped at the target to deliver the payload. Of course, difference between drop pod and bomb is that drop pod doesn't explode (by design, at least)

In contrast, Sky Crane delivers the cargo and then goes off to crash, clearing the delivery zone. It's a single-use thing.
Comment: In the context of videogames especially, many other common tropes originated in Aliens.
Comment: This does not answer the question, though.


Sampling data from two collections with multiple array matching MongoDB

Question: I'm trying to find all unread messages, by chat ID, and user ID. Unread message is if chats_users.max_read_date is less than message.create_date and message.from_id is not equal to user.
How it works now. I have an array of chat IDs, and I search all chats_users documents by chat_id and user_id and then just loop search for messages.
I'd like to rewrite it all into one query, but I'm running into a few problems. What is my problem, how do I find all chats_users by chat ID and user ID to then find all messages that are written by a non-user, and the creation date message.create_date is greater than chats_users.max_read_date
How to make a condition so that for each chat, find its chats_users and then select only those messages which are written not by the user who makes the request and all other chatters, and the creation date of the message message.create_date is greater than chats_users.max_read_date
Message collection
type ChatsUsers struct {
    ID     string `json:"id" bson:"id"`
    ChatID string `json:"chat_id" bson:"chat_id"`
    // user ID, which corresponds to the user ID in the system.
    UserID string `json:"user_id" bson:"user_id"`
    // MaxReadDate time of the last message read
    MaxReadDate int64 `json:"max_read_date" bson:"max_read_date"`
}

ChatsUsers collection
type Message struct {
    ID         string `json:"id" bson:"id"`
    ChatID     string `json:"chat_id" bson:"chat_id"`
    FromID     string `json:"from_id" bson:"from_id"`
    CreateDate int64  `json:"create_date" bson:"create_date"`
    Body     string `json:"body" bson:"body"`
}

Rewrite the query to get a single aggregation, the purpose of the query is to find all messages, by all chats that are unread and unscripted by a non-user, the uid variable is the user looking for such messages

fun (r *Mongo) UnreadMessageCount(ctx context.Context, chats []*Chat, uid string) (map[string]int64, error) {

    match := bson.A{}
    for _, chat := range chats {
        match = append(match, chat.ID)
    }

    chatsUsersList := make([]*domain.ChatsUsers, 0)
    for _, ch := range chats {
        chu, err := r.FindChatUser(ctx, ch.ID, uid)
        if err != nil {
            l.Error().Err(err).Msg("failed to find chat user")
            return nil, err
        }
        chatsUsersList = append(chatsUsersList, chu)
    }

    list := make([]*domain.Message, 0)

    for _, ch := range chats {
        for _, chu := range chatsUsersList {
            if chu.ChatID == ch.ID {
                filter := bson.D{
                    // search for messages by active chat IDs
                    { Key: "chat_id", Value: ch.ID},
                    // add filtering: that the message has not yet been read,
                    // and that the messages we select are not written by the current user.
                    {Key: "$and",
                        Value: bson.A{
                            bson.D{
                                {
                                    Key: "create_date", Value: bson.D{ bson.D{
                                    // $gt Matches values that are greater than the specified value.
                                    { Key: "$gt", Value: chu.MaxReadDate}}
                                },
                                // $ne Matches all values that are not equal to the specified value.
                                // https://www.mongodb.com/docs/manual/reference/operator/query-comparison/
                                {Key: "from_id", Value: bson.M{"$ne": uid}}
                            },
                        },
                    },
                }

                cursor, err := r.colMessage.Find(ctx, filter)
                ....

                var res []*domain.Message
                ....
            }
        }
    }

    // it doesn't make sense to use an array of messages, we need to create a map,
    // which will have the chat ID and the number of unread messages in it.
    messages := make(map[string]int64)
    for _, msg := range list {
        messages[msg.ChatID]++
    }

    return messages, nil
}

My try (sorry, but this is a very crooked query, but I'm still trying to write the right query)
db.message.aggregate([
    {
        $match: {
            $expr: {
                $and: [
                    {
                        chat_id: {
                            $in: ["ad0a3405-1a16-48f9-93e6-51b17a7283e2"]
                        }
                    },
                    {
                        from_id: {
                            $ne: "63f5002735bb916dab3f2b1d"
                        }
                    },
                    {
                        $gt: ["$create_date", { $max: "$chats_users.max_read_date" }]
                    }
                ]
            }
        }
    },
    {
        $lookup: {
            from: "chatsusers",
            localField: "chat_id",
            foreignField: "chat_id",
            as: "chats_users"
        }
    },
    {
        $unwind: "$chats_users"
    },
    {
        $group: {
            _id: "$chat_id",
            messages: {
                $push: {
                    id: "$id",
                    chat_id: "$chat_id",
                    from_id: "$from_id",
                    create_date: "$create_date",
                    type: "$type",
                    media: "$media",
                    body: "$body",
                    update_at: "$update_at",
                    modifications: "$modifications",
                    viewed: "$viewed"
                }
            },
            max_read_date: { $max: "$chats_users.max_read_date" }
        }
    }
]);

In the response I expect to get only four objects from the test data
{
      "_id": {
        "$oid": "63f502d3c1be2b78aaa6152e"
      },
      "body": "полковник конь тобі копитом в грудь! 3",
      "chat_id": "ad0a3405-1a16-48f9-93e6-51b17a7283e2",
      "create_date": 1677001427977,
      "from_id": "63f5002735bb916dab3f2b1d5g",
      "id": "G30uZ1HvlYQCZVwRRTBi",
      "media": "",
      "modifications": null,
      "type": "text",
      "update_at": 0,
      "viewed": false
    },
    {
      "_id": {
        "$oid": "63f502d2c1be2b78aaa6152d"
      },
      "body": "полковник конь тобі копитом в грудь! 2",
      "chat_id": "ad0a3405-1a16-48f9-93e6-51b17a7283e2",
      "create_date": 1677001428101,
      "from_id": "63f5002735bb916dab3f2b1d5g",
      "id": "RzrfvZuLWyhrKOHEx5gK",
      "media": "",
      "modifications": null,
      "type": "text",
      "update_at": 0,
      "viewed": false
    },

    {
      "_id": {"$oid": "63f5002735bb916dab3f2bb2"},
      "body": "after you",
      "chat_id": "ad0a3405-1a16-48f9-93e6-51b17a7283e2-y7y3r2",
      "create_date": 1677001427398,
      "from_id": "63f5002735bb916dab3f2b23",
      "id": "e5189d64-0c43-41dd-befa-f554d09475cf",
      "media": "",
      "modifications": null,
      "type": "text",
      "update_at": 0,
      "viewed": true
    },
    {
      "_id": {"$oid": "63f5002735bb916dab3f2bb1"},
      "body": "I'm not religious",
      "chat_id": "ad0a3405-1a16-48f9-93e6-51b17a7283e2-y7y3r2",
      "create_date": 1677001427327,
      "from_id": "63f5002735bb916dab3f2b23",
      "id": "a1fbc6b0-5f8d-4fa2-aef7-807314dfba0d",
      "media": "",
      "modifications": null,
      "type": "text",
      "update_at": 0,
      "viewed": true
    }

Test data
And my second try
db.chats_users.aggregate([
    {
        $match: {
            user_id: "63f5002735bb916dab3f2b1d",
            chat_id: { $in: ["ad0a3405-1a16-48f9-93e6-51b17a7283e2"] },
        }
    },
    {
        $lookup: {
            from: "message",
            let: { chat_id: "$chat_id", max_read_date: "$max_read_date" },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                { $eq: ["$chat_id", "$$chat_id"] },
                                { $ne: ["$from_id", "63f5002735bb916dab3f2b1d"] },
                                { $gt: ["$create_date", "$$max_read_date"] },
                            ]
                        }
                    }
                }
            ],
            as: "messages"
        }
    },
    {
        $project: {
            chat_id: 1,
            message_count: { $size: "$messages" }
        }
    }
])

Answer: It turned out to be simpler, I made a query using the chatsusers collection - which simplified the query.
db.chatsusers.aggregate([
    {
        $match: {
            chat_id: {
                $in: ["ad0a3405-1a16-48f9-93e6-51b17a7283e2", "22e1e6f1-459a-4ed1-bc8f-c9947492972d"],
            },
        }
    },
    {
        $lookup: {
            from: "message",
            localField: "chat_id",
            foreignField: "chat_id",
            let: { chat_id: "$chat_id", max_read_date: "$max_read_date" },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                { $eq: ["$chat_id", "$$chat_id"] },
                                { $ne: ["$from_id", "63f5002735bb916dab3f2b1e"] },
                                { $gt: ["$create_date", "$$max_read_date"] },
                            ]
                        }
                    },
                }
            ],
            as: "messages"
        }
    },
    {
        $project: {
            chat_id: 1,
            message_count: { $size: "$messages" },
        }
    },
    {
        $group: {
            _id: "$chat_id",
            message_count: { $sum: "$message_count" },
        },
    },
    {
        $sort: { "message_count": -1 },
    },
    {
        $project: {
            _id: 0,
            chat_id: "$_id",
            message_count: 1,
        },
    },
])

Playground


Gzip time to decompress?

Question: I wanted to backup my entire server, which is hosted.  So I used dd and gzip to make the file smaller.  The disk was 500GB, but with less than 5% used.  I managed to dd the whole partition into a 200 GB gzip file over the internet to my home in 8 hours.  Now I am trying to decompress the file into a partition onto a new disk.  It has already taken more than 8 hours and of course I have no way of determining progress.

How long should it take to decompress in relation to compressing?
I assume the local processor is the key ingredient in determining how long it takes?  (Rather than the bandwidth of the network)
Is there a way of seeing progress?

Can I do this a better way next time?
Comment: Seems to be a rather inefficient way of doing a copy, provided you have only 25Gb of data - i.e. likely less than 20Gb gzipped :)
Comment: If you already downloaded it, why would the network bandwidth be relevant?
Answer: Here's an article I saw with some benchmarks for gzip and some other compression algorithms: http://tukaani.org/lzma/benchmarks.html. I would assume that decompression time varies with your CPU speed. Also, if you look through the tests, it seems like decompression is almost always faster than compression.
Edit:
In response to your latest question about other ways to back up your server, I found this article that talks about various backup methods: http://www.techrepublic.com/blog/10things/10-outstanding-linux-backup-utilities/895. I'm not sure what access you have to the server, but if it is a common commercial host, you might be able to ask Tech Support how you should do it.
Comment: Thanks, that is very useful.  Do you know of any way I can determine if it is still progressing?  The target disk is unmounted and I assume mounting it would halt the progress?  How do I see if the process is still active?  I can see the drive light flashing, but that does not really indicate progress.
Comment: I think I've used dd on a flash drive that was mounted before.I could be wrong... I'm a little new to Linux. If you can, try mounting the drive and seeing GB's have been copied? That should give you information on how much is left.
Comment: Thanks, according to the benchmark, my 200 GB disk will take 38 days to decompress!!!  200GB/61MB/S
Comment: 200GB at 61MB/sec it will only take around hour, not 38 days.
Answer: You don't want to (ab)use dd like that.  It will waste time copying the 95% of the disk that is not being used, and you will get a corrupt image if you have it mounted read/write at the time.  If you want to backup the system, it is best to make sure you shut down all services that could be writing to the disk, and use tar.
Answer: The simplest way to look at the progress of a running gzip process is to simply look at the file size of the written file, potentially in combination with watch if you want real time updates. If you are dealing with partitions that is of course not easily possible.
An alternative to estimate the progress is to use iotop. iotop will show you the speed at which data is written to the disk by every process on the system, your gzip process will likely show up on top and give you the amount of data processed per second. Then simply multiply the MB/sec with how long the process has been running (see ps auxw START column) and you will get a rough idea how long it will take.
As for further backup runs: Use rsync when you want to copy data from one computer on a network to another. rsync handles compression and deltas, thus you only have to transfer the data that you don't already have, which makes it very fast for regular updates. rsync also has the --backup and --backup-dir options that can be used to create not just copies, but proper backups that keep track of deleted files.
And when doing diskimages partimage is a good alternative to dd, as unlike dd partimage is file system aware and will only copy blocks actually used by the file system, not empty unused blocks, it is thus able to create much smaller disk images on mostly empty file systems. But it's not a good tool for backup over a network either, use rsync instead.
Answer: Your hoster should have provided you with a backup plan and (most preferably) a web-interface to the backup and restore facilities. The better way would be to ask them if they let you access a copy of an automated backup.
Answer: Generally decompressing in gzip should be faster than compressing.  I suspect the problem here is that the target disk is slower than the disk from which it was compressed: or perhaps you're reading from and writing to the same physical disk which is causing a lot of seeking.
Other answers are correct that generally it's better to back up the files, rather than the raw device.
To see progress, I would install pv and then say something like this:
zcat /tmp/myimg.gz |pv -s500G > /tmp/myimg

Gzip time to decompress?


Python tkinter Copy Widget to New Master

Question: I wrote a collapsible frame widget and was hoping to give it a dock/undock property. From what I've read, widgets can't be placed "over" other widgets (except on canvases, which I wish to avoid) so I can't just "lift" the frame, and their master cannot be changed so I can't simply place the frame into a new Toplevel. The only other option I can think of is to copy the widget into the new Toplevel. Unfortunately, I don't see any options on the copy or deepcopy operations to change the Master before the new widget is created.
So, the question:
Are these assumptions accurate, or is there a way to do any of these things?
If not, do I have any other options than the solution I put together here:
def copywidget(self, frame1, frame2):
    for child in frame1.winfo_children():
        newwidget = getattr(tkinter,child.winfo_class())(frame2)
        for key in child.keys(): newwidget[key] = child.cget(key)
        if child.winfo_manager() == 'pack':
            newwidget.pack()
            for key in child.pack_info():
                newwidget.pack_info()[key] = child.pack_info()[key]
        elif child.winfo_manager() == 'grid':
            newwidget.grid()
            for key in child.grid_info():
                newwidget.grid_info()[key] = child.grid_info()[key]
        elif child.winfo_manager() == 'place':
            newwidget.place()
            for key in child.place_info():
                newwidget.place_info()[key] = child.place_info()[key]

Answer: There is no way to reparent a widget to a different toplevel. The easiest thing is to make a method that recreates the widgets in a new parent.
Widgets can be stacked on top of each other, though it requires care. You can, for instance, use grid to place two widgets in the same cell, and you can use place to put one widget on top of another .
Answer: Using this answer you are able to copy one widget onto another master. Then, you simply forget the previous widget, and it will work as a moved widget.
Example code:
root = tk.Tk()

frame1 = tk.Frame(root, bg='blue', width=200, height=100)
frame1.grid(row=0, column=0, pady=(0, 5))

frame_to_clone = tk.Frame(frame1)
frame_to_clone.place(x=10, y= 15)
tk.Label(frame_to_clone, text='test text').grid(row=0, column=0)

frame2 = tk.Frame(root, bg='green', width=80, height=180)
frame2.grid(row=1, column=0, pady=(0, 5))

# Move frame_to_clone from frame1 to frame2
cloned_frame = clone_widget(frame_to_clone, frame2)
cloned_frame.place(x=10, y=15)

# frame_to_clone.destroy()  # Optional destroy or forget of the original widget

root.mainloop()

Gives:


Why does VS warn me that typeof(T) is never the provided type in a generic method where the type parameter is restricted to implement T?

Question: I hope the question is correct, so let's give you an example. Imagine the following generic method:
public abstract class Base : IDisposable
{
    public static IEnumerable<T> GetList<T>()
        where T : Base
    {
        // To ensure T inherits from Base.
        if (typeof(T) is Base)
            throw new NotSupportedException();

        // ...
    }
}

According to the MSDN the keyword where restricts the type parameter T to be of type Base or to inherit from this class.

[...] a where clause can include a base class constraint, which states that a type must have the specified class as a base class (or be that class itself) in order to be used as a type argument for that generic type.

Also this code does compile:
public static T GetFirst()
    where T : Base
{
    // Call GetList explicitly using Base as type parameter.
    return (T)GetList<Base>().First();
}

So when following the last code typeof(T) should return Base, shouldn't it? Why does Visual Studio then prints this warning to me?

warning CS0184: The given expression is never of the provided ('Demo.Base') type.
Comment: What do you want to do? Ensuring that `T` inherits from `Base` is useless, since the generic constrain already ensures that.
Comment: The constraint ensures that `T` either inherits from `Base` **OR** is `Base` itself. I want `T` only to inherit from `Base`.
Answer: typeof(whatever) always returns an instance of type Type. Type doesn't derive from Base.
What you want is this:
if(typeof(T) == typeof(Base))
    throw new NotSupportedException("Please specify a type derived from Base");

Something that looks like it is the same is this:
if(variableOfTypeT is Base)

But that has a different meaning.
The first statement (with typeof(Base)) only is true if T is  Base. It will be false for any type derived from Base.
The second statement (variableOfTypeT  is Base) is always true in your class, because any class derived from Base will return true for a check for its base class.
Comment: The alternative doesn't work... `T` is a type parameter but is used like a variable ;) But the first approach works... How did I miss that?! Sometimes the solution is too simple :D
Answer: That's not how you check inheritance.
typeof(T) is of type System.Type, it's not Base. To see if T is derived from Base you should use the IsSubclassOf method, like this:
if(typeof(T).IsSubclassOf(typeof(Base))  ...

Comment: Note that will returns `false` if `T==Base`
Comment: I thought that was the point. Because of the restriction, OP already knows T is either Base or derived from it.
Comment: I wanted to know if `T` *is* `Base` to make sure only implementations of that abstract class get passed to the method. `IsSubclassOf` would perform the check I already have expressed with the `where` constraint.


How can I accentuate values in this form to aid fast visual identification?

Question: My web app has a need to display multiple values.  Right now I find it hard to visually discern quickly.
Observe UI

Observe minimized html:

    gpm
    rpm
    psi
    ft-lbs

    3410.480271
    699.999
    55.095466
    50.454966

    3410.480271
    50.4549
    50.607433
    55.095466

</table

I tried underlining the values, which kind of works to help delineate values, but not really, since it also makes the interface more messy.
For example, if you are looking for the last value of psi in the first (50.607...), is there a way to make it visually stand out amongst other values, for ease of reference?  Right now it is crowded between other values, which make it visually lost.   I am looking for numbers to not run into each other (not for any particular number to stand out).
To make things easier it is acceptable to format values up to first decimal point
Comment: What have you tried? What determines the "importance" of a value in your use-case?
Comment: I have tried `text-decoration: underline`, which looked a tad messy although acceptable in the worst case, and `background-color: lightblue`, which looked horrible. Importance is "not being lost in a wall of numbers when looking at the spread".  I can perhaps try "Excel" approach, where I emphasize borders of the cells.
Comment: Have you tried padding the table cells?
Comment: not yet but the thought have crossed my mind ... I think I would like some borders or some coloring or some accentuation though to go with the padding, to make it more distinguishable
Answer: Have you tried using colors? if colors are not an options, then different shades of grey with different variations of weights should help.
remember, just because one column is important that does not mean other columns do no needs any effects(like less important columns could be made thinner or with different shades grey to reduce importance)
My suggestion, do this for alternate rows and use colors on hover or for very important columns.
Comment: to clarify, I am more so looking for ... all numbers not to run into each other.  Not for any particular number to stand out.
Comment: sorry..i meant alternate columns and not rows
Answer: sparked by rajankz, I am thinking of perhaps doing alternate coloring on columns . ..
yep that worked: http://www.textfixer.com/tutorials/css-table-color-columns.php


How to run a program as elevated in Windows 7?

Question: I created an application in Excel VBA that needs to run a batch file out of script and I was wondering how I can elevate all the processes that the process creates. Please I need to know how to elevate processes?
Answer: If you have an EXE, you can embed a manifest it that will make it require adminrights on Windows 7/Vista.
Edit: The entire that does this manifest would be:
<code> <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
        <requestedPrivileges>
        <requestedExecutionLevel level="highestAvailable" uiAccess="False" />
        </requestedPrivileges>
     </security>
    </trustInfo>
  </assembly>
</code>
Comment:
Comment: So this on top of the manifest file or is this the entire file with a return at the bottom?
Comment: You're welcome :) I edited my original answer to include it :)
Comment: How is the OP going to embed the manifest in Excel.exe compiled by Microsoft?


Make blank hard drive bootable without bootqble USB or DVD

Question: I accidentally formatted my hard drive which earlier had Ubuntu installed on it.
My computer is x86 and does not support bootable USB and there is no DVD Player installed.
How to repair this?
Comment: Network boot possible (probably not)? You are not going to solve this without a bootable device, so install a DVD-player or a second harddrive (which must have  a system installed already, a live-system would be ok). Or move your HDD to a different machine and restore a backup (if you have one) . Your question appears to be off-topic, it has nothing to do with Ubuntu...
Comment: Is there a working **CD player** in the computer? In that case you can try with the Ubuntu **`mini.iso`**. See [this link and links from it](https://askubuntu.com/questions/1014149/how-come-ubuntu-18-04-lts-has-a-32bit-iso-installer/1014230#1014230). I think Lubuntu, Ubuntu Budgie, Ubuntu MATE or Xubuntu will work better than standard Ubuntu in such an old computer. [Try them according to this link](http://ubuntuforums.org/showthread.php?t=2230389)
Comment: Tried mini.iso bootable from bootable USB but it gets stuck after initrd ready
Comment: **Which version** of the Ubuntu `mini.iso` did you try? Did you check the **md5sum**? Please tell me, and I will test it. And **which tool** did you use to create a CD boot disk from the iso file? -- Depending on the computer, you may have better luck with another version, so finally, please specify the **computer, brand name and model**.
Comment: I am using Ubuntu mini.iso 14.04 which have correct md5sum, further I used Ubuntu Startup Disk Creator to create bootable usb . My Computer processor is Intel Core2Duo 32 bits with 2Gb Ram and 320GB HDD
Comment: There are 4 supported 14.04 LTS mini.iso files for PC computers: 32-bit (i386) and 64-bit (amd64), trusty kernel and xenial kernel at [this link](http://cdimages.ubuntu.com/netboot/trusty/). I hope that you are trying one of the 32-bit versions for your x86 computer.
Comment: I think Core2Duo has 64-bit architecture (and probably the motherboard too, but I am not sure). So I think the computer can run both 32-bit and 64-bit linux. Anyway, I have downloaded and tested both of the currently supported 32-bit versions of 14.04 mini.iso. I used mkusb to clone from the iso files to a USB boot drive. Both installers work, I installed mini systems without any graphical desktop environment, and the installed systems work for me. -- So I suggest that you connect via **wired internet (ethernet cable)** and try again.
Answer: There aren't many options, and all the options I can think of require another computer.
Some BIOSes provide the option to boot from LAN. Even if there is no OS installed, you should be able to configure the BIOS, or the boot order by pressing a certain key (typically Del, sometimes F10 or F12.
I never tried booting from LAN, and I don't know your computer, so I can't help you. In the chance someone else replies here, posting more information about your computer, or pictures of your screen on boot would be very helpful. (logos, trademarks, boot screens, BIOS menu).
The other method is not likely to work, but you can try swapping the hard drive with another computer with better boot support, reinstalling Ubuntu in this new computer, and then swapping hard drives again. But both computers must at the very least use the same CPU architecture.
Good luck.
Comment: Technically, the OS must be for the destined computer's CPU architecture. If that one is x86, and the other computer is x64, you can still install Ubuntu 32-bit on a 64-bit CPU, and it will work on the 32-bit computer


$\mathfrak{sl}_4(\mathbb{C})$ is semisimple

Question: I want to prove in several different ways that $\mathfrak{sl}_4(\mathbb{C})$ is semisimple, where
$$\mathfrak{sl}_4(\mathbb{C}) = \{ x \in \mathfrak{g}_4(\mathbb{C})\, | \, Tr(x)=0\}.$$
I know there exist a lot of criterions of semisemplicity. In particular, for $L=\mathfrak{sl}_4(\mathbb{C})$, I can use:

Brute force
$Rad(L) = Z(L) = 0$
Killing form is non degenerate
$L$ is simple
$L$ doesn't have abelian ideal

4)There exists a basis of $L$ of the form $\{ e_{ij}$ with $i \neq j$ and $h_i=e_{ii}-e_{i+1,i+1} \}$. Let $I$ be a non-empty ideal of $L$, I want to show $I=L$.
Indeed, let $0 \neq x \in I$ then $[e_{ij},x] \in I$ such that $x = \sum_{i=1}^4 \sum_{j \neq i} \alpha_{ij}[e_{mn},e_{ij}]+\sum_{i=1}^3 \beta_i[e_{mn},h_i]$. Thus, applying ad $e_{mn}$ twice, I get $-2\alpha_{nm}e_{mn} \in I$, and $-2 \alpha_{mn}e_{nm} \in I$ by the same calculation. However, applying ad $h_m$ twice I obtain $4(\alpha_{m,m+1}e_{m,m+1}+\alpha_{m+1,m}e_{m+1,m}) \in I$. Since one of those $\alpha_{ij}, \beta_i$ must be non-zero, then I can say $I=L$, right?
What about the other methods? In particular 3), I can't figure out the solution.
Comment: I also think that it is quite easy to show directly that $\mathfrak{sl}_n(\Bbb C)$ is simple, see [this question](https://math.stackexchange.com/questions/1598356/how-to-show-that-mathfraksl-n-mathbbr-and-mathfraksl-n-mathbbc?rq=1). For the  Killing form, there are several duplicates here on this site, e.g. [this one](https://math.stackexchange.com/questions/2578195/how-to-derive-the-general-formula-for-the-killing-form-for-classical-lie-algebra?noredirect=1&lq=1).
Comment: It's maybe worthwhile to note that none of these proofs should use any property of $\Bbb C$ besides that it's a field of characteristic $0$. -- I wonder what exactly is meant by method 1, "brute force" though. You still got to compute something?
Comment: With "brute force" i mean "try to compute $Rad(L)$ directly
Answer: The Killing form can be explicitly calculated. Let $A,B\in \mathfrak{sl}_n(\mathbb{C})$, Killing form is $$\kappa(A,B) = 2n\text{tr}(AB)$$
it is straightforward to show this is non-degenerate. Briefly, if $A$ is such that $\text{tr}(AB) = 0$ for all $B\in \mathfrak{sl}_n(\mathbb{C})$, then testing with $B=e_{ij}, i\neq j$ shows $a_{ji}=0$, testing with $B=e_{ii}-e_{jj}$ shows $a_{ii}=a_{jj}$, this forces all entries of $A$ to be $0$.

To see why the Killing form is this one, let $V=\mathbb{C}^n$, view elements of $V$ as column vectors. $\text{ad}_A\text{ad}_B$ is a operator sending $\text{End}(V)$ to $\text{End}(V)$, sending $X\mapsto ABX-AXB-BXA+XBA$, we need to compute its trace.
It suffices to find trace of the operator: $T:X\mapsto CXD$. View $\text{End}(V)$ as $V\otimes V$, where $v_1\otimes v_2$ corresponds to $v_1 v_2^T$. Then under this identification, $T$ is $C\otimes D^T$ (check this!). Therefore $\text{tr}(T) = \text{tr}(C)\text{tr}(D)$.
For our original $X\mapsto ABX-AXB-BXA+XBA$, it is the sum of four operators. The first one take $C=AB, D=I$, the second one take $C=A,D=B$ etc. The trace of $\text{ad}_A\text{ad}_B$ is then $$\text{tr}(AB)\text{tr}(I) - \text{tr}(A)\text{tr}(B)- \text{tr}(B)\text{tr}(A)+\text{tr}(I)\text{tr}(BA) = 2n \text{tr}(AB)-2 \text{tr}(A)\text{tr}(B)$$
Restricting on $\mathfrak{sl}_n(\mathbb{C})\subset \text{End}(V)$ gives the result.
Comment: How can you say tr($T$)=tr($C$)tr($D$)? And what about the other methods? Any hint?


Intersecting circles and the sine and cosine rules

Question: So I wrote a question using three numbers $r_1$, $r_2$ and $l$. I am struggling to solve it "in general" while playing by certain rules. The rules are: no calculator and no half- or double-angle formulae. (The rules are necessary because they mimic the world of my students!) The question is meant to be on the cosine (and sine) rules.

Question. Two circles with centres $c_1$ and $c_2$ of radius $r_1=2\operatorname{cm}$ and $r_2=4\operatorname{cm}$ have their centres $l=5\operatorname{cm}$ apart. The circles meet at the points $p$ and $q$ (so the segments $c_1p$ and $c_1q$ have length $r_1$ while $c_2p$ and $c_2q$ have length $r_2$). Denote by $\theta_1$ the angle between $c_1p$ and $c_1q$, and denote by $\theta_2$ the angle between $c_2p$ and $c_2q$.
Find $\cos\theta_1$ and $\cos\theta_2$.

I picked the values $r_1=2\operatorname{cm}$, $r_2=4\operatorname{cm}$ and $l=5\operatorname{cm}$ almost at random. Note that if these are chosen carefully the question becomes much more tractable (for example, $r_1=2\operatorname{cm}$, $r_2=\sqrt2\operatorname{cm}$and $l=1+\sqrt3\operatorname{cm}$).
Comment: Why not ask for $\angle PC_1C_2$ and $\angle PC_2C_1$?
Comment: That is, use cosine law to find $\angle PC_1C_2$ first  and then find the cosine (double that of $\angle PC_1C_2$).
Comment: @almagest Because that is too simple!
Comment: @Mick How would you do that without using a half- or double-angle formulae?
Answer:
By cosine formula, $\alpha$ can be found from the given 2, 4, 5.
Since the two triangles are congruent, $\beta = \alpha$.
∴ $\theta_1 = \alpha + \beta = 2 \times \alpha$.
Then, $\cos \theta_1$ is found by calculating  its equivalent, $\cos (2 \times \alpha)$, which should not be considered as a double angle formula.
$\cos \theta_2$ can be treated in the similar fashion.

Edit: Second method
By Pythagoras theorem, we have $x^2 + (5 – x)^2 = 4^2 – x ^2$, we get $5 – x = 1.3$
Then $\cos \alpha = 0.65$ and $\alpha = 49.4584….$
I don't think one can obtain the last result without using calculator.
Comment: Yeah, using similar logic to finding $\sin\theta$ and $\tan\theta$ if you are given that $\cos\theta=12/13$ with $0\leq\theta\leq\pi$. (Then $\sin\theta=5/13$ and $\tan\theta=5/12$.)
Comment: How do you find $\alpha$ though? This requires a calculator (in general).
Comment: @user1729 Sorry that I missed the no calculator part of your requirement.   I have just added a second method. However, it still need a calculator in the very last part. ... Do you mean we can choose any arrangements of r1, r2 and L?
Comment: continue.... so that $\cos \alpha$ (or $\cos (2 \alpha)$) ends up as some surd involving fraction?
Comment: @user1729 If that is the case, your example can have the job done already. See my second post.
Answer: let the center line $c_1c_2$ cut the bigger circle at $a$ and the smaller circle at $b.$  from the isoscles triangles $c_2pa, c_1pb,$ you can show that $pa=pb = x(say)$ now use the cosine rule(or stewarts theorem) to show that $x = \sqrt 2.$ once you have that you can find that $\frac12 pq = \sqrt{x^2 - (\frac12) ^2} = \frac{\sqrt 7}2.$ now use use the cosine rule on the isocles triangle $c_1pq$ with sides $2,2$ and $\sqrt 7$ to find the $\angle pc_1 q.$
Comment: I do not understand why $pa=pb$ (and I think it is wrong in general). For example, using the easier $\sqrt2$, $2$ and $1+\sqrt3$ values I mentioned in the question gives $(pa)^2=8-2\sqrt3$ while $(pb)^2=4-\sqrt2$.
Answer: I use the $"5-12-13"$ special angled triangle as illustration. We intentionally choose $C_1P = 13, C_2P = 2 \sqrt 5$ and then $C_1C_2 = 12 +5$. Thus, $C_1PY$ formed the said triangle.

Construct (1) $YH \bot CP$; and (2) $e$, the perpendicular bisector of $C_1P$. ….
It should be clear that all green marked angles are equal and some triangles are similar. This means $a = \dfrac {5 \times 5}{13}$ and $XZ = 6.5  -  \dfrac {25}{13} = h$, say
In $\triangle XYZ, XY = \dfrac {13h}{12} = k$, say
In $\triangle PXY, PX = \sqrt {5^2 + k^2} = j$. say. Therefore $\cos \angle PXY = \cos (2\theta) = \dfrac {k}{j}$.
I hope your students know the method of finding $j$, a number involving square roots, without using calculator.


Custom Sort in Crystal Reports

Question: We have a report that has one group. The group header is based on a (rather extensive) formula which says if the item number is equal to "AAAAAA" then the header should read one of the following:
Conduit
Metal Flex
Copper Wire
Aluminum Wire
Aluminum SE
SO Cord
SQ D
Breakers
etc.
Currently, the groups are sorted in alphabetical order when the report is run. How can we change this so it prints in the order we want (for example as above)?
On the "Use a Formula as Group Sort Order" formula, it says we can only return the group sort order constants as Ascending, Descending or Original order. I tried Original Order seeing as how the group formula is set up in the order wanted, but it still does it in alpha order.
Comment: Is the data coming from a database source?  If so, can you specify the database?  Because when I wanted custom sorting, I had to use a procedure and did not use sorting in Crystal.
Comment: Yes, the information is coming from a database, but I'm not following how that specifically would help.

It is a custom view that we created.
Comment: In oracle, you can query data using a decode statement, assigning a number to specific values (that can then be sorted on).  If you have a lot of categories that won't help.  But another option is to make a sort table in your database.  So, knowing the database can allow someone to give a database specific answer, suggesting a way to provide the list already custom sorted to Crystal.
Comment: And then don't do any sorting in Crystal, including Original.
Answer: If you are using the field from database to group then you can use option "Group in Specified order" and there provide the order you want to view.
You can get the option if you go to change group.
Comment: can you give some example function to do this?
Comment: What is your question? Have you downvoted this?What example you need?
Comment: Can u give screenshot of a simple example?

Custom Sort in Crystal Reports


How to resolve the issue while recording a video at 60fps with iphone 4s, ipad 2?

Question: Question in short:
Getting exception while trying to record at 59fps. How to resolve it?

2014-09-16 15:16:27.740 RosyWriter[2294:60b] ** Terminating app due
  to uncaught exception 'NSInvalidArgumentException', reason: 'The
  activeVideoMaxFrameDuration passed is not supported by the receiver's
  active format.  Use -activeFormat.videoSupportedFrameRateRanges to
  discover valid ranges.

My Question in detail:
What i am trying to do?
Trying to record the video in 30+ fps(60 fps or more fps).
What have i tried so far?

Initially tried with "AVCaptureConnection"'s property as below and later understood that the properties i used were depreciated.

AVCaptureConnection *conn = [output connectionWithMediaType:AVMediaTypeVideo];

CMTimeShow(conn.videoMinFrameDuration);
CMTimeShow(conn.videoMaxFrameDuration);

if (conn.isVideoMinFrameDurationSupported)
    conn.videoMinFrameDuration = CMTimeMake(1, CAPTURE_FRAMES_PER_SECOND);
if (conn.isVideoMaxFrameDurationSupported)
    conn.videoMaxFrameDuration = CMTimeMake(1, CAPTURE_FRAMES_PER_SECOND);

reference:
    According to the header file (AVCaptureSession.h),
This property is deprecated on iOS, where min and max frame rate adjustments are applied exclusively at the AVCaptureDevice using the activeVideoMinFrameDuration and activeVideoMaxFrameDuration properties.

Then, i tried with "AVCaptureDevice" as below:
-(void)setupCaptureSession
{
    if ( _captureSession ) {
        return;
    }

    _captureSession = [[AVCaptureSession alloc] init];

    AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  ....................................
  ....................................

_videoConnection = [videoOut connectionWithMediaType:AVMediaTypeVideo];

int frameRate;
NSString *sessionPreset = AVCaptureSessionPreset640x480;
CMTime frameDuration = kCMTimeInvalid;
// For single core systems like iPhone 4 and iPod Touch 4th Generation wI
//use a lower resolution and framerate to maintain real-time performance.
if ( [[NSProcessInfo processInfo] processorCount] == 1 )
{
    if ( [_captureSession canSetSessionPreset:AVCaptureSessionPreset1280x720] ) {
        sessionPreset = AVCaptureSessionPreset1280x720;
    }
    frameRate = 59;
}
else
{
    // USE_GPU_RENDERER is set in the project's build settings
 #if ! use_gpu_renderer
    // When using the CPU renderer we lower the resolution to 720p so that all devices can maintain real-time performance (this is primarily for A5 based devices like iPhone 4s and iPod Touch 5th Generation).
    if ( [_captureSession canSetSessionPreset:AVCaptureSessionPreset640x480] ) {
        sessionPreset = AVCaptureSessionPreset640x480;
    }
 #endif // ! use_gpu_renderer

    frameRate = 59;
}

_captureSession.sessionPreset = sessionPreset;

frameDuration = CMTimeMake( 1, frameRate );

NSError *error = nil;

if ( [videoDevice lockForConfiguration:&error] ) {
    videoDevice.activeFormat = bestFormat;
    [**videoDevice setActiveVideoMaxFrameDuration:frameDuration];
    [videoDevice setActiveVideoMinFrameDuration:frameDuration**];
    [videoDevice unlockForConfiguration];
}
else {
    NSLog(@"videoDevice lockForConfiguration returned error %@", error);
}

self.videoOrientation = [_videoConnection videoOrientation];

[videoOut release];

return;

}
My issue:

I got the exception

2014-09-16 15:16:27.740 RosyWriter[2294:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'The activeVideoMaxFrameDuration passed is not supported by the receiver's active format.  Use -activeFormat.videoSupportedFrameRateRanges to discover valid ranges.'
        *** First throw call stack:
        (0x2da2ff83 0x385d2ccf 0x2c919e4f 0xb4c7d 0xb4317 0x38aba81f 0x38ac07cb 0xb42b1 0xb2539 0x302676df 0x30258e89 0x3025864d 0x302584bf 0x30257fe5 0x30255827 0x302bf33d 0x302bbfad 0x302b656b 0x302526e9 0x30251851 0x302b5ca9 0x3288baed 0x3288b6d7 0x2d9faa67 0x2d9faa03 0x2d9f91d7 0x2d963ebf 0x2d963ca3 0x302b4ed1 0x302b014d 0xb1b4d 0x38adfab7)
        libc++abi.dylib: terminating with uncaught exception of type NSException

Am i doing anything wrong here?

Later,I changed the code as

  AVCaptureDeviceFormat *bestFormat = nil;
  AVFrameRateRange *bestFrameRateRange = nil;
  for ( AVCaptureDeviceFormat *format in [videoDevice formats] ) {
    for ( AVFrameRateRange *range in format.videoSupportedFrameRateRanges ) {
        if ( range.maxFrameRate > bestFrameRateRange.maxFrameRate ) {
            bestFormat = format;
            bestFrameRateRange = range;
        }
    }
}
NSError *error = nil;

if ( bestFormat ) {
if ( [videoDevice lockForConfiguration:&error] ) {
    videoDevice.activeFormat = bestFormat;
    videoDevice.activeVideoMinFrameDuration = bestFrameRateRange.minFrameDuration;
    videoDevice.activeVideoMaxFrameDuration = bestFrameRateRange.maxFrameDuration;
    [videoDevice unlockForConfiguration];
    }}

But I get the video that gets recorded at 30fps with bestFrameRateRange, but not at 59fps..
Comment: Another typo: `videoDevice.activeVideoMinFrameDuration = bestFrameRateRange.maxFrameDuration;
    videoDevice.activeVideoMaxFrameDuration = bestFrameRateRange.minFrameDuration;`, min is max and max is min in your code.
Comment: Maybe, that's not supported on those devices, and that's why you are getting the exception? Maybe this line `videoDevice.activeVideoMaxFrameDuration = bestFrameRateRange.minFrameDuration;` should be `videoDevice.activeVideoMaxFrameDuration = bestFrameRateRange.maxFrameDuration;`?
Comment: Thanks for your input.. I corrected the typo error you noted in the code snippet. However,many developers have already achieved 60fps in older apple devices.As per my analysis, i hope its possible..
Answer: Here is a working example how to use higher frame rate:
Find and set active mode to use maximum frame rate available.
float maxFrameRate = 0.0;
int maxIndex = 0;
for(int i=0;i<_videoCaptureDevice.formats.count;i++) {
    AVCaptureDeviceFormat *format = [_videoCaptureDevice.formats objectAtIndex:i];
    AVFrameRateRange *frameRateRange = [format.videoSupportedFrameRateRanges firstObject];
//You can add hard coded checking for specific format like if(frameRateRange.maxFrameRate == 240) etc I am using the max one
    if(maxFrameRate<frameRateRange.maxFrameRate) {
        maxFrameRate = frameRateRange.maxFrameRate;
        maxIndex = i;
    }
}

AVCaptureDeviceFormat *format = [_videoCaptureDevice.formats objectAtIndex:maxIndex];
AVFrameRateRange *frameRateRange = [format.videoSupportedFrameRateRanges firstObject];
[self.videoCaptureDevice lockForConfiguration:nil];
self.videoCaptureDevice.activeFormat = format;
self.videoCaptureDevice.activeVideoMinFrameDuration = frameRateRange.minFrameDuration;
self.videoCaptureDevice.activeVideoMaxFrameDuration = frameRateRange.maxFrameDuration;
[self.videoCaptureDevice  unlockForConfiguration];

After that change the frame rate
if(YourFrameRate<=frameRateRange.maxFrameRate && YourFrameRate>=frameRateRange.minFrameRate) {
    if([device lockForConfiguration:&error]) {
        [device setActiveVideoMinFrameDuration:CMTimeMake(1, YourFrameRate)];
        [device setActiveVideoMaxFrameDuration:CMTimeMake(1, YourFrameRate)];
        [device unlockForConfiguration];
    } else {
        [self passError:error];
    }
}

Got the answer from here
Answer: You should set a valid format to AVCaptureDevice.
You can do this
// get device what you like
let device = xxxxx

// list all default formats for this device
for format in device.formats {
    var founded = false

    // check what you want and pick a perfect format.
    let formatDesc = format.formatDescription

    // mediaType / SubType
    let mediaType = format.mediaSubType
    // if your target is above(equal) iOS 13. use formatDesc.mediaSubType
    let mediaSubType = CMFormatDescriptionGetMediaSubType(formatDesc)

    // dimensions
    // if your target is above(equal) iOS 13. use formatDesc.dimensions
    let dimensions = CMVideoFormatDescriptionGetDimensions(formatDesc)

    // fps
    let ranges = format.videoSupportedFrameRateRanges.first
    for supportedFPSRange in ranges {
        if supportedFPSRange.maxFrameRate == 60 {
            founded = true
        }
    }

    // support Multi cam
    let isMultiCamSupported = format.isMultiCamSupported

    ....

    if founded {
        // Set activeFormat for device! Your capture device is up and loaded.
        do {
            try device.lockForConfiguration()
            device.activeFormat = format
            device.unlockForConfiguration()
        } catch {
            // catch some locking error
        }

        // Don't forget break the loop.:p
        break
    }
}