text:
Q: System very Slow, Trying to find the bottleneck I have Ubuntu 12.10 installed in Sony VIAO E Series VPCEH16EN, 4GB RAM, 320 GB HDD, Intel Core i3-2310M Processor 2.10GHz. It is a dual boot with Windows7 alongside with it.
I see the system is very slow in responding, any video gets stuck in between the play. Can you please help me find where the bottleneck is. Here is the output of hdparm and smartctl:
------------- HDPARM -------------------
anil@anil-ubuntu:~$ sudo hdparm -Tt /dev/sda6
/dev/sda6:
 Timing cached reads:     2 MB in  3.51 seconds = 584.17 kB/sec
 Timing buffered disk reads: 160 MB in  3.02 seconds =  52.91 MB/sec
anil@anil-ubuntu:~$
-----------------------------------------

-------------- SMARTCTL -----------------
anil@anil-ubuntu:~$ sudo smartctl -a /dev/sda6
smartctl 5.43 2012-06-30 r3573 [x86_64-linux-3.5.0-25-generic] (local build)
Copyright (C) 2002-12 by Bruce Allen, http://smartmontools.sourceforge.net
=== START OF INFORMATION SECTION ===
Device Model:     TOSHIBA MK3265GSXN
Serial Number:    419CD3X3B
LU WWN Device Id: 5 000039 33ab02a3c
Firmware Version: GH012H
User Capacity:    320,072,933,376 bytes [320 GB]
Sector Size:      512 bytes logical/physical
Device is:        Not in smartctl database [for details use: -P showall]
ATA Version is:   8
ATA Standard is:  Exact ATA specification draft version not indicated
Local Time is:    Thu Feb 28 23:08:07 2013 IST
SMART support is: Available - device has SMART capability.
SMART support is: Enabled
=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED
General SMART Values:
Offline data collection status:  (0x00) Offline data collection activity
                    was never started.
                    Auto Offline Data Collection: Disabled.
Self-test execution status:      (   0) The previous self-test routine completed
                    without error or no self-test has ever
                    been run.
Total time to complete Offline
data collection:        (  120) seconds.
Offline data collection
capabilities:            (0x5b) SMART execute Offline immediate.
                    Auto Offline data collection on/off support.
                    Suspend Offline collection upon new
                    command.
                    Offline surface scan supported.
                    Self-test supported.
                    No Conveyance Self-test supported.
                    Selective Self-test supported.
SMART capabilities:            (0x0003) Saves SMART data before entering
                    power-saving mode.
                    Supports SMART auto save timer.
Error logging capability:        (0x01) Error logging supported.
                    General Purpose Logging supported.
Short self-test routine
recommended polling time:    (   2) minutes.
Extended self-test routine
recommended polling time:    (  95) minutes.
SCT capabilities:          (0x003d) SCT Status supported.
                    SCT Error Recovery Control supported.
                    SCT Feature Control supported.
                    SCT Data Table supported.
SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  1 Raw_Read_Error_Rate     0x000b   100   100   050    Pre-fail  Always       -       0
  2 Throughput_Performance  0x0005   100   100   050    Pre-fail  Offline      -       0
  3 Spin_Up_Time            0x0027   100   100   001    Pre-fail  Always       -       1258
  4 Start_Stop_Count        0x0032   100   100   000    Old_age   Always       -       2560
  5 Reallocated_Sector_Ct   0x0033   100   100   050    Pre-fail  Always       -       47
  7 Seek_Error_Rate         0x000b   100   100   050    Pre-fail  Always       -       0
  8 Seek_Time_Performance   0x0005   100   100   050    Pre-fail  Offline      -       0
  9 Power_On_Hours          0x0032   088   088   000    Old_age   Always       -       4940
 10 Spin_Retry_Count        0x0033   150   100   030    Pre-fail  Always       -       0
 12 Power_Cycle_Count       0x0032   100   100   000    Old_age   Always       -       2553
191 G-Sense_Error_Rate      0x0032   100   100   000    Old_age   Always       -       118
192 Power-Off_Retract_Count 0x0032   100   100   000    Old_age   Always       -       169
193 Load_Cycle_Count        0x0032   099   099   000    Old_age   Always       -       13993
194 Temperature_Celsius     0x0022   100   100   000    Old_age   Always       -       43 (Min/Max 20/47)
196 Reallocated_Event_Count 0x0032   100   100   000    Old_age   Always       -       5
197 Current_Pending_Sector  0x0032   100   100   000    Old_age   Always       -       0
198 Offline_Uncorrectable   0x0030   100   100   000    Old_age   Offline      -       0
199 UDMA_CRC_Error_Count    0x0032   200   200   000    Old_age   Always       -       0
220 Disk_Shift              0x0002   100   100   000    Old_age   Always       -       19
222 Loaded_Hours            0x0032   091   091   000    Old_age   Always       -       3918
223 Load_Retry_Count        0x0032   100   100   000    Old_age   Always       -       0
224 Load_Friction           0x0022   100   100   000    Old_age   Always       -       0
226 Load-in_Time            0x0026   100   100   000    Old_age   Always       -       245
240 Head_Flying_Hours       0x0001   100   100   001    Pre-fail  Offline      -       0
SMART Error Log Version: 1
ATA Error Count: 108 (device log contains only the most recent five errors)
    CR = Command Register [HEX]
    FR = Features Register [HEX]
    SC = Sector Count Register [HEX]
    SN = Sector Number Register [HEX]
    CL = Cylinder Low Register [HEX]
    CH = Cylinder High Register [HEX]
    DH = Device/Head Register [HEX]
    DC = Device Command Register [HEX]
    ER = Error register [HEX]
    ST = Status register [HEX]
Powered_Up_Time is measured from power on, and printed as
DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,
SS=sec, and sss=millisec. It "wraps" after 49.710 days.
Error 108 occurred at disk power-on lifetime: 3337 hours (139 days + 1 hours)
  When the command that caused the error occurred, the device was active or idle.
  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 41 4a 6a 9d bb 64  Error: WP at LBA = 0x04bb9d6a = 79404394
  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  61 08 58 f0 f6 b8 40 00      03:49:54.536  WRITE FPDMA QUEUED
  61 08 50 00 f7 b8 40 00      03:49:54.536  WRITE FPDMA QUEUED
  60 00 48 98 9c bb 40 00      03:49:54.535  READ FPDMA QUEUED
  61 38 40 c8 0b b9 40 00      03:49:54.535  WRITE FPDMA QUEUED
  61 02 38 88 3a 39 40 00      03:49:54.535  WRITE FPDMA QUEUED
Error 107 occurred at disk power-on lifetime: 3337 hours (139 days + 1 hours)
  When the command that caused the error occurred, the device was active or idle.
  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 41 f2 6a 9d bb 64  Error: WP at LBA = 0x04bb9d6a = 79404394
  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  61 08 f8 68 c9 65 40 00      03:49:50.336  WRITE FPDMA QUEUED
  60 00 f0 98 9c bb 40 00      03:49:50.335  READ FPDMA QUEUED
  61 08 e8 28 71 61 40 00      03:49:50.335  WRITE FPDMA QUEUED
  61 18 e0 08 c8 61 40 00      03:49:50.335  WRITE FPDMA QUEUED
  61 20 d8 d8 90 6c 40 00      03:49:50.335  WRITE FPDMA QUEUED
Error 106 occurred at disk power-on lifetime: 3337 hours (139 days + 1 hours)
  When the command that caused the error occurred, the device was active or idle.
  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 41 62 6a 9d bb 64  Error: WP at LBA = 0x04bb9d6a = 79404394
  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  61 08 70 f8 f6 b8 40 00      03:49:46.159  WRITE FPDMA QUEUED
  61 08 68 08 f7 b8 40 00      03:49:46.159  WRITE FPDMA QUEUED
  60 00 60 98 9c bb 40 00      03:49:46.157  READ FPDMA QUEUED
  61 08 58 c0 0b b9 40 00      03:49:46.157  WRITE FPDMA QUEUED
  61 08 50 e8 38 62 40 00      03:49:46.157  WRITE FPDMA QUEUED
Error 105 occurred at disk power-on lifetime: 3337 hours (139 days + 1 hours)
  When the command that caused the error occurred, the device was active or idle.
  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 41 aa 6a 9d bb 64  Error: WP at LBA = 0x04bb9d6a = 79404394
  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  61 08 00 28 87 7e 40 00      03:49:41.973  WRITE FPDMA QUEUED
  61 08 f8 78 7d 7e 40 00      03:49:41.972  WRITE FPDMA QUEUED
  61 08 f0 40 7d 7e 40 00      03:49:41.972  WRITE FPDMA QUEUED
  61 08 e8 88 72 7e 40 00      03:49:41.972  WRITE FPDMA QUEUED
  61 08 e0 d0 5e 7e 40 00      03:49:41.972  WRITE FPDMA QUEUED
Error 104 occurred at disk power-on lifetime: 3337 hours (139 days + 1 hours)
  When the command that caused the error occurred, the device was active or idle.
  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 41 52 6a 9d bb 64  Error: WP at LBA = 0x04bb9d6a = 79404394
  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  61 08 78 f0 04 bd 40 00      03:49:37.805  WRITE FPDMA QUEUED
  61 08 70 20 03 bd 40 00      03:49:37.804  WRITE FPDMA QUEUED
  61 08 68 08 03 bd 40 00      03:49:37.804  WRITE FPDMA QUEUED
  61 10 60 e8 02 bd 40 00      03:49:37.803  WRITE FPDMA QUEUED
  61 03 58 d8 f2 6f 40 00      03:49:37.803  WRITE FPDMA QUEUED
SMART Self-test log structure revision number 1
No self-tests have been logged.  [To run self-tests, use: smartctl -t]
SMART Selective self-test log data structure revision number 1
 SPAN  MIN_LBA  MAX_LBA  CURRENT_TEST_STATUS
    1        0        0  Not_testing
    2        0        0  Not_testing
    3        0        0  Not_testing
    4        0        0  Not_testing
    5        0        0  Not_testing
Selective self-test flags (0x0):
  After scanning selected spans, do NOT read-scan remainder of disk.
If Selective self-test is pending on power-up, resume after 0 minute delay.
--------------------------------------------------------------------

A: Your S.M.A.R.T. data from your disk shows that your hard drive is failing. I would backup any information you might have important in your disk and replace it asap.
All the Type: Pre-fail warnings should be clear of that with addition to the 104, 105, 106, 107 and 108 errors in the smartctl report.
You can also check the status of your hard disk conditions (show by the S.M.A.R.T. data) by using the palimpsest (Disk Utility) and checking the status there


text:
Q: Android Java -It does not create and save both albums I said I have a problem.
1. saved album can not be created for the URL of the picture.
Is there a bug in the code, I still do not understand, I'm glad you throw a hand.
private void downloadImage() {
    if (future != null) {
        //set the callback and start downloading
        future.withResponse().setCallback(new FutureCallback<Response<InputStream>>() {
            @Override
            public void onCompleted(Exception e, Response<InputStream> result) {
                boolean success = false;
                if (e == null && result != null && result.getResult() != null) {
                    try {
                        //prepare the file name
                        String url = mSelectedImage.getUrl();
                        String fileName = url.substring(url.lastIndexOf('/') + 1, url.length()) + ".jpg";
                        //create a temporary directory within the cache folder
                        File dir = Utils.getAlbumStorageDir("wall-splash");
                        //create the file
                        File file = new File(dir, fileName);
                        if (!file.exists()) {
                            file.createNewFile();
                        }

                        //copy the image onto this file
                        Utils.copyInputStreamToFile(result.getResult(), file);

                        //animate the first elements
                        animateCompleteFirst(true);

                        success = true;
                    } catch (Exception ex) {
                        Log.e("un:splash", ex.toString());
                    }

                    //animate after complete
                    animateComplete(success);
                } else {
                    animateReset(true);
                }
            }
        });
    }
}

Error (Android Studio)

05-30 21:40:40.297    3608-4157/com.mikepenz.unsplash.debug E/art﹕ dlopen("/data/app/com.mikepenz.unsplash.debug-2/lib/arm/libgmscore.so", RTLD_LAZY) failed: dlopen failed: library "/data/app/com.mikepenz.unsplash.debug-2/lib/arm/libgmscore.so" not found
05-30 21:40:40.297    3608-4157/com.mikepenz.unsplash.debug E/ProviderInstaller﹕ Unable to load native code from /data/app/com.mikepenz.unsplash.debug-2/lib/arm/libgmscore.so
05-30 21:40:40.317    3608-4157/com.mikepenz.unsplash.debug E/ProviderInstaller﹕ libgmscore version mismatch (0 vs. 7571)
05-30 21:53:32.082    3608-3608/com.mikepenz.unsplash.debug I/wall-splash﹕ Directory not created

redpajama_set_name: RedPajamaStackExchange


text:
Q: Assiging a new variable to each iteration of a foreach loop Im trying to create a for each loop that will provide a different variable for each iteration of the array.
As it stands my loop will run and my variable $new will be the final value only, 17. Is there a way to get a different variable assigned to each iteration?
$a = array(1, 2, 3, 17);

foreach($a as $value) {
  echo $new = $value;
}

echo $new;

?>

A: forget the foreach loop and simply pick a random value from the array Answer provided from "http://php.net/manual/en/function.array-rand.php":
$new= $a[mt_rand(0, count($a) - 1)];
echo $new;

or
$new=array_random($a)
echo $new;


text:
Q: How to add a Table in a database that in working on host with EF code first? I have site and in is working and this site's database have many records , i want to add table in this database using EF code first, at the same time, i don't want to lose any data in my site.
Excuse me for my bad English language ;)


text:
Q: Multiple testcase in a sequence in GO Although Go language allows to run multiple test files in a sequence by using the command $go test packagename ,
is there a way to control this sequence using a textfile.
Like for eg: textfile should just contain the names of all the testcase files to be run in a sequence so that the user just modify this textfile to run the desirable testcases
like $go test textfile.txt
Is there a way of customizing in this way?

A: The go test command allows you to specify test functions to run using go test -test.run <regex>. You could, for example, write a little bash script or alias:
FILE=$1 # first argument
cat $FILE | while read regex; do # read file one line at a time
    go test -test.run "$regex"
done

and then you could do ./myscript.sh testFuncs.txt, for example.


text:
Q: How to setup postfix on gcloud? I trying to setup a multiple domain server in gcloud instance, following this tutorial https://vorkbaard.nl/installing-a-mailserver-on-debian-8-part-3-mta-postfix/ , I modify /etc/postfix/master.cf :
smtp        inet  n       -       y       -       -       smtpd

to
597        inet  n       -       y       -       -       smtpd

when I telnet domain 597 I get succefully a connection, but trying to send an email from mailx or from the telnet client I get an error as if postfix still use 25 port:
Aug 24 19:26:08 localhost postfix/smtp[1404]: connect to alt2.gmail-smtp-in.l.google.com[2607:f8b0:400c:c0f::1b]:25: Network is unreachable

So where I need to change the port to use to postfix work in google computer instance ? Telnet outside google network works ok!
thanks!
[edit]
After more debugs and test sending email to the same email send and recibe, from round cube, and from thunderbird, so I think the problem its the outside traffic from the port 25 and I dont know why postfix use 25 port if the master.cf stmp port is set to 597
mail.log debug sending from roundcube
Aug 25 00:58:59 localhost dovecot: imap(sender@domain.com): Debug: maildir++: root=/var/mail/vmail/inova.cloud/info, index=, indexpvt=, control=, inbox=/var/mail/vmail/inova.cloud/info, alt=
Aug 25 00:58:59 localhost dovecot: imap(sender@domain.com): Logged out in=50 out=511
Aug 25 00:59:22 localhost postfix/qmgr[952]: 494C582008: from=<sender@domain.com>, size=524, nrcpt=1 (queue active)
Aug 25 00:59:22 localhost postfix/qmgr[952]: 4F95180D0A: from=<nano@server.c.majestic-lodge-173213.internal>, size=461, nrcpt=1 (queue active)
Aug 25 00:59:22 localhost postfix/error[1435]: 494C582008: to=<destination@domain>, relay=none, delay=4617, delays=4617/0.06/0/0.01, dsn=4.4.1, status=deferred (delivery temporarily suspended: connect t$
Aug 25 00:59:22 localhost postfix/error[1436]: 4F95180D0A: to=<destination@domain>, relay=none, delay=80226, delays=80226/0.03/0/0.01, dsn=4.4.1, status=deferred (delivery temporarily suspended: connect$
Aug 25 00:59:59 localhost dovecot: imap-login: Debug: SSL: elliptic curve secp384r1 will be used for ECDH and ECDHE key exchanges
Aug 25 00:59:59 localhost dovecot: imap-login: Debug: SSL: elliptic curve secp384r1 will be used for ECDH and ECDHE key exchanges
Aug 25 00:59:59 localhost dovecot: auth: Debug: auth client connected (pid=1442)
Aug 25 00:59:59 localhost dovecot: auth: Debug: client in: AUTH#0111#011PLAIN#011service=imap#011secured#011session=0wbZdolXxJkAAAAAAAAAAAAAAAAAAAAB#011lip=::1#011rip=::1#011lport=143#011rport=39364#011resp=AGl$
Aug 25 00:59:59 localhost dovecot: auth-worker(1430): Debug: sql(sender@domain.com,::1,<0wbZdolXxJkAAAAAAAAAAAAAAAAAAAAB>): query: SELECT email as username, pwd AS password FROM addresses WHERE email = 'info@$
Aug 25 00:59:59 localhost dovecot: auth: Debug: client passdb out: OK#0111#011user=sender@domain.com
Aug 25 00:59:59 localhost dovecot: auth: Debug: master in: REQUEST#0112225078273#0111442#0111#0117898818d71c58f150c8d4f75bb936fb5#011session_pid=1443#011request_auth_token
Aug 25 00:59:59 localhost dovecot: auth-worker(1430): Debug: sql(sender@domain.com,::1,<0wbZdolXxJkAAAAAAAAAAAAAAAAAAAAB>): SELECT 5000 AS uid, 5000 as gid, email, '/var/mail/vmail/domain/info' AS home FROM$
Aug 25 00:59:59 localhost dovecot: auth: Debug: master userdb out: USER#0112225078273#011sender@domain.com#011uid=5000#011gid=5000#011email=sender@domain.com#011home=/var/mail/vmail/domain/info#011auth_token$
Aug 25 00:59:59 localhost dovecot: imap-login: Login: user=<sender@domain.com>, method=PLAIN, rip=::1, lip=::1, mpid=1443, secured, session=<0wbZdolXxJkAAAAAAAAAAAAAAAAAAAAB>
Aug 25 00:59:59 localhost dovecot: imap(sender@domain.com): Debug: Added userdb setting: plugin/email=sender@domain.com
Aug 25 00:59:59 localhost dovecot: imap(sender@domain.com): Debug: Effective uid=5000, gid=5000, home=/var/mail/vmail/inova.cloud/info
Aug 25 00:59:59 localhost dovecot: imap(sender@domain.com): Debug: Namespace inbox: type=private, prefix=, sep=, inbox=yes, hidden=no, list=yes, subscriptions=yes location=maildir:/var/mail/vmail/domain/info
Aug 25 00:59:59 localhost dovecot: imap(sender@domain.com): Debug: maildir++: root=/var/mail/vmail/domain/info, index=, indexpvt=, control=, inbox=/var/mail/vmail/domain/info, alt=
Aug 25 00:59:59 localhost dovecot: imap(sender@domain.com): Logged out in=50 out=511

From outside email it doesnt recive

A: Two important facts:

*

*GCE blocks outbound email on port 25, 465 and 587 (except for port 465 or 587 to Google Apps relay only).

*If you are not using a relay, you cannot choose the oubound port. This is because you must connect to whichever port your destination is listening to, which will be a standard (blocked) port.

As a result you must use a email relay, which you are not by the sound of it. At the bottom of the page I linked above are some options for email relays you can use. They all include postfix options.


text:
Q: Macro to group data by month I'm trying to create a macro that will group data by month: for example, if there are 3 entries for February for client A, then it will consolidate the three entries into one and sum the amounts.
I have:
A: Client name
B: Invoice number
C: Billing month
D: Currency
E: Charge amount
F: Invoice step

What I am trying to do, is group the following into a single row, with the invoice amounts added up, and replace the three rows with just the one row. These entries are for a single client (so the grouping depends on the value in column A).

EG. Client A has three entries for Jan, Client B has one, Client C has one. Then for February Client A has one, Client B has one and Client C has two.
Any macro suggestions I've seen on here haven't been helpful to me, I keep getting errors coming up so I don't know what the problem is. This is the one I tried:
Sub Group()

Dim e As Range, a as Range

Set e = Range("C6")
Set c = e.Offset(, 2)

Do
If Evaluate("=month(" & e.Address & ")") <> Evaluate("=month(" & e(2).Address & ")") Then
    e(2).Resize(2, 3).Insert
    e(2).Offset(, 2) = "=sum(" & Range(a, c.Offset(, 2)).Address & ")"
    e(2).Offset(, 2).Font.Bold = 1
    Set e = e.End(4)
    Set c = e.Offset(, 2)
Else
    Set e = e(2)
End If
Loop Until e.End(4).Row = Rows.Count

e(2).Offset(, 2) = "=sum(" & Range(c, e.Offset(, 2)).Address & ")"
e(2).Offset(, 2).Font.Bold = 1

End Sub

EDIT: Subtotals and pivot tables would not work - the raw data is pasted in (thousands of lines of entry, for 40+ clients and some have many invoices each month), the raw data is sorted using a macro, which is then pasted into other sheets. Pasting from the pivot would be more difficult.

A: I follow your image to write the code:

After the code:

Here is the code:
Sub TEST()
Dim lastrow As Long

lastrow = Range("A" & Rows.Count).End(xlUp).Row

For i = 6 To lastrow

lastrow = Range("A" & Rows.Count).End(xlUp).Row

    For j = i + 1 To lastrow

            If Range("A" & j) = Range("A" & i) And Range("C" & j) = Range("C" & i) Then

                Range("B" & i) = Range("B" & i) & "," & " " & Range("B" & j)
                Range("E" & i) = Range("E" & i).Value + Range("E" & j).Value
                Rows(j).EntireRow.Delete

            End If

    Next j

Next i

End Sub


text:
Q: Lip Reading classification on LiLiR dataset in matlab i work on lip reading but i am a newbie.
after googling, i found that one of the data set of lip reading is LiLir dataset. now i downloaded it and i want to classify them using Support vector machine (SVM). but each letter has a matrix of data which has 4800 rows and 21 until 28 columns. i do not know what is the meaning of columns. they are features, but which features?
A1_Faye_lips = load('\data set\avletters\avletters\Lips\A1_Faye-lips.mat')

A1_Faye_lips =

    vid: [4800x21 double]
    siz: [60 80 21]

>>

how can i train SVM using this 2D matrix?

A: 21 is the feature, I didn't look into the data source, so cannot tell what are those features exactly . But they are possibly the independent variables that influence the output (lip reading). Each variable is 4800*1 vector or 60*80 array.
For data training, Libsvm is a good SVM training toolbox for you.


text:
Q: list of brands not displaying in a spinner Hi in the below code I am displaying two spinner one is for displaying brand name and another for displaying model name.
I am getting the response from server like this:
{"RESULT":"SUCCESS","BRANDS":[{"BRANDID":"14","BRANDNAME":"471"},{"BRANDID":"3","BRANDNAME":"ACE"},{"BRANDID":"4","BRANDNAME":"ADLER"},{"BRANDID":"5","BRANDNAME":"ALIEN"},{"BRANDID":"6","BRANDNAME":"ARTISAN-TORO"},{"BRANDID":"7","BRANDNAME":"ASSOCIATED PACIFIC"},{"BRANDID":"8","BRANDNAME":"ASTEX"},{"BRANDID":"9","BRANDNAME":"BERNINA"},{"BRANDID":"10","BRANDNAME":"BONIS"},{"BRANDID":"11","BRANDNAME":"BROTHER"},{"BRANDID":"12","BRANDNAME":"BROTHER "},{"BRANDID":"13","BRANDNAME":"CHANDLER"},{"BRANDID":"15","BRANDNAME":"CINCINNATI"},{"BRANDID":"16","BRANDNAME":"CONSEW"},{"BRANDID":"17","BRANDNAME":"CONSEW\/SEIKO"},{"BRANDID":"18","BRANDNAME":"DENNISON"},{"BRANDID":"19","BRANDNAME":"DURKOPP ADLER"},{"BRANDID":"20","BRANDNAME":"EAGLE"},{"BRANDID":"21","BRANDNAME":"EASTMAN"},{"BRANDID":"22","BRANDNAME":"EASTMAN CARDINAL"},{"BRANDID":"23","BRANDNAME":"ECONOSEW"},{"BRANDID":"1","BRANDNAME":"usha"}]}
Model Response:
{"RESULT":"SUCCESS","MODELS":[{"MODELNAME":"150","MODELID":"2"},{"MODELNAME":"C150WS","MODELID":"3"},{"MODELNAME":"HC720A","MODELID":"4"}
Based on the brand i want to display model names.
java
public class HomeFragment extends Fragment {

    public HomeFragment(){}
    Fragment fragment = null;

    String userId,companyId;
    private String brandid = "3";
    public static List<LeadResult.Users> list;
    public static List<BrandResult.Brands> listBrands;
    public static List<ModelResult.Models> listModels;
    public static ArrayList<String> listBrands_String;
   // public static List<BrandResult.Brands> list1;
    String[] brand_name;
    Spinner spinner1;
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        ActionBar actionBar=getActivity().getActionBar();
final View rootView = inflater.inflate(R.layout.layout_ownview, container, false);
        spinner1=(Spinner)rootView.findViewById(R.id.brand1);
        mTxt_OwnView=(TextView) rootView.findViewById(R.id.txt_OwnView);
        mTxt_PublicView =(TextView) rootView.findViewById(R.id.txt_PublicView);
        mRel_Ownview=(RelativeLayout)rootView.findViewById(R.id.ownview);
        mRel_publicview =(RelativeLayout)rootView.findViewById(R.id.publicview);

        listBrands = new ArrayList<BrandResult.Brands>();

        listBrands_String = new ArrayList<String>();
        listModels = new ArrayList<ModelResult.Models>();

private void getBrands() {

        String brandjson = JSONBuilder.getJSONBrand();
        String brandurl = URLBuilder.getBrandUrl();

        Log.d("url","" + brandurl);
        SendToServerTaskBrand taskBrand = new SendToServerTaskBrand(getActivity());
        taskBrand.execute(brandurl, brandjson);
        Log.d("brandjson", "" + brandjson);

    }

    private void setBrand(String brandjson)
    {

        ObjectMapper objectMapper_brand = new ObjectMapper();

        try

         {
            BrandResult brandresult_object = objectMapper_brand.readValue(brandjson, BrandResult.class);

            String Brand_result = brandresult_object.getRESULT();
            Log.d("Brand_result","" + Brand_result);

            if(Brand_result.equals("SUCCESS"))
            {
                listBrands =brandresult_object.getBRANDS();
                spinner_fn();

                Log.i("listbrands", " " + listBrands);

                // startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));

            }

            else
            {
                Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        // return eNames;

    }

    public class SendToServerTaskBrand extends AsyncTask<String, String, String>
    {

        private Context mContext = null;
        private ProgressDialog mProgressDialog;

        public SendToServerTaskBrand(Context context)
        {
            mContext = context;
        }

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
        }

        @Override
        protected String doInBackground(String... params)
        {
            String Burl = params[0];
            String Bjson = params[1];
            String Bresult = UrlRequester.post(mContext, Burl, Bjson);

            return Bresult;
        }

        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            setBrand(result);
            if (mProgressDialog.isShowing())
                mProgressDialog.dismiss();

        }
    }

    private void getModels() {

        String model_url = URLBuilder.getModelUrl();
        String model_json = JSONBuilder.getJSONModel(brandid);

        Log.d("model_json", "" + model_json);
        SendToServerTaskModel taskModel = new SendToServerTaskModel(getActivity());
        taskModel.execute(model_url, model_json);

    }

    private void setModel(String json)
    {

        ObjectMapper objectMapperModel = new ObjectMapper();

        try
        {
           ModelResult modelresult_object = objectMapperModel.readValue(json, ModelResult.class);

            String model_result = modelresult_object.getRESULT();
            Log.d("model_result","" + model_result);

            if (model_result.equals("SUCCESS"))
            {
                listModels =modelresult_object.getMODELS();

                Log.i("listmodels", " " + listModels);

                // startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));

            }

            else
            {
                Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        // return eNames;

    }

    public class SendToServerTaskModel extends AsyncTask<String, String, String>
    {

        private Context mContext = null;
        private ProgressDialog mProgressDialog;

        public SendToServerTaskModel(Context context)
        {
            mContext = context;
        }

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
        }

        @Override
        protected String doInBackground(String... params)
        {
            String url = params[0];
            String json = params[1];
            String result = UrlRequester.post(mContext, url, json);

            return result;
        }

        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            setModel(result);
            if (mProgressDialog.isShowing())
                mProgressDialog.dismiss();

        }
    }

    private void spinner_fn() {

        for(int i = 0; i < listBrands.size(); i++){

            listBrands_String.add(listBrands.get(i).toString());
            Log.d("string is",""+ listBrands_String);
        }

        //ArrayAdapter<String> dataAdapter = ArrayAdapter.createFromResource(getActivity().getApplicationContext()
         //       ,android.R.layout.simple_spinner_item,listBrands_String);

        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext()
               ,android.R.layout.simple_spinner_item, listBrands_String);

       // ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.category_array, android.R.layout.simple_spinner_item);

        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner1.setAdapter(dataAdapter);

        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int position, long id) {

                Log.e("Position new",""+ listBrands_String.get(position));

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

            }

        });

    }


text:
Q: Returning a Clojure PersistentVector from a Spring Boot RestController I am trying to return a Clojure PersistentVector from a Spring Boot RestController method:
@GetMapping("example")
public PersistentVector someVector() {
    return PersistentVector.create(42, "hello");
}

However, it appears Spring Boot is treating the PersistentVector as a function (it is a subtype of Runnable and Callable):
clojure.lang.ArityException: Wrong number of args (0) passed to: PersistentVector

at clojure.lang.AFn.throwArity(AFn.java:429) ~[clojure-1.9.0.jar:na]
at clojure.lang.AFn.invoke(AFn.java:28) ~[clojure-1.9.0.jar:na]
at clojure.lang.AFn.call(AFn.java:18) ~[clojure-1.9.0.jar:na]

at org.springframework.web.context.request.async.WebAsyncManager.lambda$startCallableProcessing$4(WebAsyncManager.java:323) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]

at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_181]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_181]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_181]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_181]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_181]

How do I tell Spring Boot to treat the PersistentVector as a List instead (it is also a subtype of List)?

A: The confusion between list and function can be solved by explicitly calling .iterator() on the vector:
@GetMapping("example")
public Iterator someVector() {
    // ~~~~~~~~
    return PersistentVector.create(42, "hello").iterator();
}                                           // ~~~~~~~~~~~

Maybe not the cleanest solution, but hey, it gets the job done!

A: PersistentVector implements transitively Iterable and List.
@GetMapping("example")
public List someVector() {
    return PersistentVector.create(42, "hello");
}

Implicitly down-casting the return value should do the trick as well.


text:
Q: Indexing a multidimensional Numpy array with an array of indices Let us say I have a Numpy array a with shape (10, 10, 4, 5, 3, 3), and two lists of indices, b and c, of shape (1000, 6) and (1000, 5) respectively, which represent indices and partial indices for the array. I want to use the indices to access the array, producing arrays of shape (1000,) and (1000, 3), respectively.
I know of a few ways to do this, but they're all unwieldy and rather un-pythonic, for example converting the indices to tuples or indexing each axis separately.
a = np.random.random((10, 10, 4, 5, 3, 3))
b = np.random.randint(3, size=(1000, 6))
c = np.random.randint(3, size=(1000, 5))

# method one

tuple_index_b = [tuple(row) for row in b]
tuple_index_c = [tuple(row) for row in c]

output_b = np.array([a[row] for row in tuple_index_b])
output_c = np.array([a[row] for row in tuple_index_c])

# method two

output_b = a[b[:, 0], b[:, 1], b[:, 2], b[:, 3], b[:, 4], b[:, 5]]
output_c = a[c[:, 0], c[:, 1], c[:, 2], c[:, 3], c[:, 4]]

Obviously, neither of these methods is very elegant or very easy to extend to higher dimensions. The first is also very slow, with two list comprehensions, and the second requires you to write out each axis separately. The intuitive syntax, a[b] returns an array of shape (1000, 6, 10, 4, 5, 3, 3) for some reason, likely related to broadcasting.
So, is there a way to do this in Numpy that doesn't involve so much manual labor/time?
Edit: Not really a duplicate, since this question deals with a list of multidimensional indices, and not just a single index, and has produced some useful new methods.

A: You can convert the index to a tuple where each column is a separate element and then use __getitem__, assuming the indices are always the first few dimensions:
a.__getitem__(tuple(b.T))

Or simply:
a[tuple(b.T)]

(a.__getitem__(tuple(b.T)) == output_b).all()
# True

(a.__getitem__(tuple(c.T)) == output_c).all()
# True

(a[tuple(b.T)] == output_b).all()
# True

(a[tuple(c.T)] == output_c).all()
# True

A: Method three:
output_b = a[map(np.ravel, b.T)]
output_c = a[map(np.ravel, c.T)]


text:
Q: How do I delete a view? I have created a view using the command below in mongoSH:
db.createView('tasksWithIsDelayed','tasks',[{ $project : {"isDelayed": false}}])

how do I delete it?

A: To remove a view, use the db.collection.drop() method on the view.
db.tasksWithIsDelayed.drop()

Removes a collection or view from the database. The method also removes any indexes associated with the dropped collection. The method provides a wrapper around the drop command.


text:
Q: SQL Server Sargable Query I ran a test of a sargable and non-sargable query in Enterprise Manager and was surprised by the Execution Plan.  They both used a Clustered Index Scan.  I was expecting the sargable query to use a Seek.
I used this table:
CREATE TABLE [dbo].[TestSargable](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Created] [datetime] NOT NULL)
GO

ALTER TABLE [dbo].[TestSargable] ADD  CONSTRAINT [PK_TestSargable] PRIMARY KEY CLUSTERED  ([ID] ASC)
GO

Sargable Query:
SELECT [ID]
      ,[Created]
  FROM [dbo].[TestSargable]
 WHERE [Created] > '2014-02-28 23:59:59'
   AND [Created] < '2014-04-01 00:00:00'

Non Sargable Query:
SELECT [ID]
      ,[Created]
  FROM [dbo].[TestSargable]
 WHERE datediff(MM, [Created], '2014-03-01') = 0

When I viewed the actual execution plan they both used a Clustered Index Scan.
Am I missing something here or is the first query non-sargable also?
This is running on my dev box using SQLExpress 11.0.2100.

A: You don't have any suitable index to seek into.
CREATE INDEX IX ON [dbo].[TestSargable]([Created])

Then you see an index range seek on the sargable version and scan for the other.

The clustered index key gets added to the non clustered index as a row locator so the index is able to cover both columns in the SELECT without any need for lookups.


text:
Q: How to use a callback I'm looking to use a callback on this script - the third callback onSlideChangeStart(swiper) http://idangero.us/swiper/api/#.V9CMp5grJlY but I've never used a callback and am at a loss where to start.
So basically I want to add/remove a class to an element elsewhere on the page where the other element as a class equal to a datatag on the swiper slide. Any tips on how to start this?
my current working js is:
//swiper script for featured director spots
//initialize swiper when document ready
var mySwiper = new Swiper ('.swiper-container', {
    // Optional parameters
    direction: 'horizontal',
    loop: true,

    keyboardControl: true,
    mousewheelControl: true,

    pagination: '.swiper-pagination',
    /*paginationElement: 'span',*/
    paginationClickable: true,

    paginationBulletRender: function (index, className) {
  return '';
    }

})

I know how to add/remove/toggle a class but not sure how to get it to fire using the callback. Please advise.
So basically I need to know how to add the callback - maybe inside the callback have a bit add more code here or similar.
Thank you.

A: Should be something like:
    mySwiper.on('onSlideChangeStart', function () {
       // do your stuff here
    });
    // do a console log on mySwiper to see what exactly is being passed
    console.log(mySwiper);


text:
Q: Create array of associative arrays I want to create an array of associative arrays in a while loop. In each iteration of the while loop I want to add a new element in the array. How I can do that? After that I want to pass this array in a foreach and print the data. I have this part of code for now but obviously something is wrong with that.
while($row2 = mysql_fetch_array($result))
{
    $myarray = array("id"=>$theid, "name"=>name($id), "text"=>$row2['text']);
}

A: Obviously, okay, first pick it apart so there's something to learn:
while($row2 = mysql_fetch_array($result))
{
    ...
}

This part look's okay, let's look inside the loop:
$myarray = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]);

There are multiple points. Probably most important is, as that is inside a loop, you overwrite $myarray in each iteration. You want to add to an array instead. Let's do this:
$myarray = array(); # initialize the array first!
while($row2 = mysql_fetch_array($result))
{
    $myarray[] = $row2; # add the row
}

After that you can output it to proof that it basically works:
var_dump($myarray);

That shows you an array that contains all rows. You then only need to change your database query so that it only returns the fields you're interested in.
In case you can't do that with the database, you can manipulate the array as well:
$myarray = array(); # initialize the array first!
while($row2 = mysql_fetch_array($result))
{
    $myarray[] = array(
        "id"   => $theid,
        "name" => name($id),
        "text" => $row2['text']
    );
}
var_dump($myarray);

Now the result should look like you want it. To output $myarray:
foreach ($myarray as $number => $row)
{
    echo '
Number ', $number, ':
';
    foreach ($row as $k => $v)
    {
        printf("
%s

%s
\n", $k, htmlspecialchars($v));
    }
    echo '

'
}

A: If you're trying to add to $myarray in each iteration, do it like this:
$myarray[] = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]);

or like this:
array_push($myarray, array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]));

A: To add an element in the end of an array use []
Example:
$myarray[] = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]);

A: Obviously your access to $row2 looked wrong, so I assumed that here to be right
$myarray = array();
while($row2 = mysql_fetch_array($result)) {
  // append something to your array with square brackets []
  $myarray[] = array("id"=> $row2['id'], "name" => $row2['name'], "text"=>$row2['text']);

  // or to maker this even shorter you could do
  $myarray[] = $row2; // ... because it has the same array key names
}

Then later when you want to read from it:
foreach($myarray as $val) {
  echo $val['name'].' (ID: '.$val['id'].') wrote following text: '.$val['text'];
}


text:
Q: How to disable vcl styles on external dll forms in delphi I have an issue in Delphi 10.1 Berlin using VCL Styles and an external DLL.
I'm using a Nitgen DLL to enroll fingerprints in my application.  The process is handled by a COM object in NBSPCOM.dll.
When I call the method to enroll, the form from the DLL appears odd.  It shows the Form background, images and controls are wrong, etc.
If I compile the application in XE8, the problem vanishes and all works fine.
I can't find the class of the DLL forms to try a VCL Styles hook.
Some screenshots of the form:
Original form

Wrong Form

A: When you uses the VCL Styles the native winapi controls (Static, Button, RebarWindow32, ...) are styled using a WH_CBT Hook, My guess is which the dll is using a static or Button winapi control where the background of the image is drawn. To overcome this you can disable the styling of these controls using the Vcl.Themes.TStyleManager.SystemHooks property like so
TStyleManager.SystemHooks := [];


text:
Q: Please help me with "a query body must end with a select clause or a group clause" in C# I have a listbox and a datagridview
Those MLB team list is from xml file I imported and what I have to do is
When I click the team on the list box it has to bring the player's name and hitting rate in the datagridview like the picture below

Here is my code:
public partial class Form1 : Form
{

    XElement BaseballXML = XElement.Load(@"C:\Users\Shinjo_PC\Desktop\EGR1400\Labs\Lab8\Baseball.xml");

public partial class Form1 : Form
{

    XElement BaseballXML = XElement.Load(@"C:\Users\Shinjo_PC\Desktop\EGR1400\Labs\Lab8\Baseball.xml");

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //pull all team from the list
        var ListTeams = from Baseball in BaseballXML.Descendants("player")
                    let team = Baseball.Element("team")
                    orderby team.Value
                    select team.Value;

        foreach (string teamname in ListTeams)
        {
            if (!lstTeams.Items.Contains(teamname))
            {
                lstTeams.Items.Add(teamname);
            }
        }
    }

    private void lstTeams_SelectedIndexChanged(object sender, EventArgs e)
    {

        var AverageQuery = from Players in BaseballXML.Descendants("player")
                        where Players.Element("team").Value == lstTeams.SelectedValue.ToString()
                        let atBats = double.Parse(Players.Element("atBats").Value)
                        let hits = double.Parse(Players.Element("hits").Value)
                        select new { hits, atBats };

        var myQuery = from bestbatter in BaseballXML.Descendants("player")
        dgvBaseball.DataSource = myQuery.ToList();
        dgvBaseball.Columns[0].HeaderText = "Player";
        dgvBaseball.Columns[1].HeaderText = "Batting Average";
            }
        }
    }
}

I'm getting error at dgvBaseball.DataSource = myQuery.ToList();
What do I do wrong?

A: Well, the error message is as clear as it gets - your query is incomplete - it's missing the select or group by clause.
You need to add a select clause to this query:
var myQuery = from bestbatter in BaseballXML.Descendants("player")
              select bestbatter // This is the part you are missing....


text:
Q: Getting current request page size I need to get current page request size which could be set by an input field named limit. I can get this when it's newly set using getParam('limit') on current request object. But later it seems its value is stored somewhere in the session so I'll miss it. I read about getPageSize() but I don't think it would be helpful here.
What is the best suitable way to get current page size limit?

A: You can use the following code to get limit on any page:
<?php $toolbar = new Mage_Catalog_Block_Product_List_Toolbar; ?>
<?php echo $toolbar->getLimit(); ?>

Hope this helps!


text:
Q: Do rails has loading fixture function like django-extensions? I want to load some dummy data for test local development. How can I make it like django-script or django's fixture?

A: In Rails you can run rake db:seed to seed the database. The command uses  db/seeds.rb under the hood - this is the file you need to edit. It can be used both to seed production (e.g. create pre-defined categories in an e-commerce store) and development (e.g. create some products for testing purposes only).
I recommend that you separate production and development seeds like this:
create a directory db/seeds and change db/seeds.rb to:
case
when Rails.env.production? then load 'db/seeds/production.rb'
when Rails.env.development? then load 'db/seeds/development.rb'
end

Then put the database initialization code in both db/seeds/production.rb and db/seeds/development.rb. You can normally use your models from both these files.


text:
Q: A question on infinite abelian group Let $G$ be an infinite abelian group such that every proper non-trivial subgroup of $G$ is infinite cyclic ; then is $G$ cyclic ?  ( The only characterization I know for infinite abelian groups to be cyclic is that every non-trivial subgroup has finite index . But I am not getting anywhere with the above statement . Please help . Thanks in advance )
NOTE : Here is what I have thought for finitely generated infinite abelian ; if $G$ is infinite and finitely generated , then $G \cong \mathbb Z_{n_1} \times ... \times \mathbb Z_{n_k} \times \mathbb Z^r$ , where $r \ne 0$ and $n_1|n_2|...|n_k ; n_1>1$ ; now if $k=0$ then for $r=1$ , $G$ is cyclic ; if $k=0 ; r>1$ then  since for $\mathbb Z^r$ has a non-cyclic infinite non-trivial subgroup (a copy of ) $\mathbb Z \times 2\mathbb Z$ violating the hypothesis . So then let $k \ne 0$ ; then a copy of $\mathbb Z_{n_1} \times ... \times \mathbb Z_{n_k} \times 2\mathbb Z$ is contained in $G$ which is non-trivial , infinite and non-cyclic   , violating the hypothesis again . So the only possibility is $G \cong \mathbb Z$ i.e. $G$ is cyclic ; am I correct here ?

A: The answer is yes. Here is an elementary argument.
Suppose firstly that for each $n\in\mathbb N$ we have $nG=G$. Since $G$ is clearly torsion free, it follows that $G$ is a $\mathbb Q$-vector space, immediately violating the hypothesis.
Thus for some $n\in\mathbb N$ we have $nG<G$, so by hypothesis $nG\cong\mathbb Z$. However $G\cong nG$ since it is torsion free: the map $G\rightarrow G$, $x\mapsto nx$ is injective and has image $nG$.
The group $\mathbb Z\!\left [\frac12\right]$ is not a counterexample: there are plenty of proper non-cyclic  subgroups, for example $3\mathbb Z\!\left [\frac12\right]$.


text:
Q: Which file is more suggestable to use jsx or js file in react application and why? In React, there is two ways to use the react file. one is JSX and another is js file. my doubt is why react created new extension to develop the react application event though js file format is getting support by it.

A: You can use js extensions for JSX components if you want. But actually JSX is not JS standard. I think thats why they created a new extension. Being strict, JSX is not JS.
Some eslint rules, like airbnt ruleset, force to you to use .jsx extension for React components, and .js extensions for JS 'plain' code.
Here there is a interesing thread discussing about that:
https://github.com/airbnb/javascript/pull/985


text:
Q: How do I get the parameters out of the Maybe wrapper correctly? I want to get the Maybe parameters out of the Maybe wrapper
A wrapper that contains one or more approximation results
data CalculatedPoints =
    Linear {xPoints :: [Maybe Double], yPoints :: [Maybe Double] }
    | Segment {xPoints :: [Maybe Double], yPoints :: [Maybe Double]}
    deriving Show

Trying to get values
main = do
  resultPoints <- parseInput
  case resultPoints of
    [Nothing, Nothing] -> putStrLn "Calculation failed. Perhaps you did not specify a method."
    [lpoints, Nothing] -> do
      putStrLn "Linear Aproxiation"
      let (xl, yl) = fromMaybe (Nothing, Nothing) lpoints -- THIS
--      prettyPoints xl yl
      print $ xl
    [Nothing, spoints] -> do
      putStrLn "Segment Aproxiation"
      print spoints
    [lpoints, spoints] -> do
      putStrLn "Linear Aproxiation"
      print lpoints
      putStrLn "Segment Aproxiation"
      print spoints

I get this error
warning: [-Wdeferred-type-errors]
    • Couldn't match type 'CalculatedPoints' with '(Maybe a, Maybe a1)
       Expected: Maybe (Maybe a, Maybe a1)         Actual: Maybe CalculatedPoints     • In the second argument of 'fromMaybe', namely 'lpoints'
      In the expression: fromMaybe (Nothing, Nothing) lpoints       In a pattern binding:
         (xl, yl) = fromMaybe (Nothing, Nothing) lpoint

P.S
I decided that parseInput was important for the context, so it turns out that calculatePoints is also necessary, so I included them
calculatePoints :: Interval -> Double -> Points -> Bool -> Bool -> [Maybe CalculatedPoints]
calculatePoints interval step points True True =
  [ Just (linearApproximation interval step points),
    Just (segmentApproximation interval step points)
  ]
calculatePoints interval step points True False = [Just (linearApproximation interval step points), Nothing]
calculatePoints interval step points False True = [Nothing, Just (segmentApproximation interval step points)]
calculatePoints _ _ _ False False = [Nothing, Nothing]

parseInput :: IO [Maybe CalculatedPoints]
parseInput = do
  input <- cmdArgs inputOptions
  points <- case file input of
                  "" -> getPointsNoFile []
                  path -> getPointsFile path

  return $ calculatePoints (left input, right input) 0.95 points (lm input) (sm input)

A: Notice that fromMaybe needs a default value of the same type. Below, your code commented with the mistake
main = do
  resultPoints <- parseInput -- This has type [Maybe CalculatedPoints]
  case resultPoints of
    -- This is the case where input is a list with two Nothing's . Looks good :)
    [Nothing, Nothing] -> putStrLn "Calculation failed. Perhaps you did not specify a method."
    -- This case is missleading. First, You can match directly (Just calcpoints)
    -- because the case where lpoints is Nothing, has being match before.
    -- so there is no need to have an irrefutable pattern (i.e. a variable ignoring the shape)
    -- Nevertheless, the error is below, not here
    [lpoints, Nothing] -> do
      putStrLn "Linear Aproxiation"
      --             |- This has type a -> Maybe a -> a (sumary: you provide a default value for Nothing, otherwise extract whatever is within Just)
      --             |          |- The default value has type "(Maybe a, Maybe a)" => a tuple of maybes
      --             |          |                 |- This has value (Maybe CalculatedPoints)
      let (xl, yl) = fromMaybe (Nothing, Nothing) lpoints -- THIS
      --  |- Also this has type tuple of maybes. Therefore GHC is complaining
      --     "you want me to extract a tuple but the value you provide is Maybe CalculatedPoints
      --      How in the heck I get a tuple from that??"
      prettyPoints xl yl
      print $ xl
.
.
.

Now, If you want to type check your code, It should be something like below. Notice that It isn't a very good / idiomatic haskell code.
main = do
  resultPoints <- parseInput
  case resultPoints of
    [Nothing, Nothing] -> putStrLn "Calculation failed. Perhaps you did not specify a method."
    [lpoints, Nothing] -> do
      putStrLn "Linear Aproxiation"
      --                      |- Provide a default value of the same type as the lpoints has "inside" the Just
      let points = fromMaybe (Linear [] []) lpoints
      --  |- not sure about this... But you can work it out
      prettyPoints points??
      print $ xl

Now, If you want more idiomatic code I'd suggest
main = do
  resultPoints <- parseInput
  case resultPoints of
    [Nothing, Nothing] -> putStrLn "Calculation failed. Perhaps you did not specify a method."
    [Just (Linear xl yl), Nothing] -> do
      putStrLn "Linear Aproxiation"
      prettyPoints xl yl
      print $ xl
.
.
.

A: I think I'd just delete most of this code. Here's a much simpler main with the same behavior:
main = do
  input <- cmdArgs inputOptions
  points <- case file input of
                  "" -> getPointsNoFile []
                  path -> getPointsFile path
  let interval = (left input, right input)

  unless (lm input || sm input) (putStrLn "Calculation failed. Perhaps you did not specify a method.")
  when (lm input) $ do
      putStrLn "Linear Aproxiation" -- sic
      print (linearApproximation interval 0.95 points)
  when (sm input) $ do
      putStrLn "Segment Aproxiation"
      print (segmentApproximation interval 0.95 points)

No Maybe needed; no CalculatedPoints needed (...probably. unless linearApproximation and segmentApproximation are weirder than their names sound); no fragile guaranteed-length-two list needed; and less code repetition between cases. There is still a little bit of repetition between the linear and segment printing code; if you really want, you could abstract those a little bit.
data ApproximationMethod = AM
    { name :: String
    , approx :: Interval -> Double -> Points -> Points
    , active :: InputOptions -> Bool
    }

allMethods :: [ApproximationMethod]
allMethods = [AM "Linear" linearApproximation lm, AM "Segment" segmentApproximation sm]

main = do
    {- ... -}
    for_ allMethods $ \am -> when (active am input) $ do
        putStrLn $ name am ++ " Aproxiation"
        print (approx am interval 0.95 points)

But for this little repeated code, that seems like overkill.


text:
Q: Where does the .xlsx file creates when creating using axlsx gem in ruby Where does the .xlsx file creates when creating using axlsx gem in ruby.

A: This is the example taken from the AXSLX homepage:
Axlsx::Package.new do |p|
  p.workbook.add_worksheet(:name => "Pie Chart") do |sheet|
    sheet.add_row ["Simple Pie Chart"]
    %w(first second third).each { |label| sheet.add_row [label, rand(24)+1] }
    sheet.add_chart(Axlsx::Pie3DChart, :start_at => [0,5], :end_at => [10, 20], :title => "example 3: Pie Chart") do |chart|
      chart.add_series :data => sheet["B2:B4"], :labels => sheet["A2:A4"],  :colors => ['FF0000', '00FF00', '0000FF']
    end
  end
  p.serialize('simple.xlsx')
end

Do file is created from the serialize() call. The filename you specifiy there is relative to the working directory. This you can find with Dir.pwd


text:
Q: Elastic rest high level api RolloverRequest I am trying to use RolloverRequest to automatically rollover a time based index.
My index format is log-000001, log-000002 etc. and alias is log
If i'm using REST API, then I do not have to supply the new index name as rollover happens automatically. But I do not see a way of getting the same using high level rest api
RolloverRequest request = new RolloverRequest(aliasName, newIndexname);

Even though documentation says that newIndexName is optional, there is no constructor which takes only one param, there is no default constructor either.
My question is, is there a way to pass just alias name to RolloverRequest for automatic rollover? If not, is there something like that planned or is the documentation misleading?

A: I got it solved. What was missing was an index template. A rollover will not copy the existing mapping from the index -- so it is lost that way. If you create an index template which matches the alias, then new index will also have the same mapping as that of old rolled over index

A: According to below link
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.7/java-rest-high-rollover-index.html

The alias (first argument) that points to the index to rollover, and the name of the new index in case the rollover operation is performed. The new index argument is optional, and can be set to null

So you can use RolloverRequest as follows:
RolloverRequest request = new RolloverRequest("alias", null);


text:
Q: Java - class expected error I have the following code:
import javax.sqing.JOptionPane;
public class DebugTwo4
{
    public static void main(String[] args)
    {
         string costString;
         double cost;
         final double TAX = 0.06;
         costString = JOptionPane.showInputDialog("Enter price of item you are buying", "Purchases", JOptionPane.INFORMATION_MESSAGE);
         cost = double.parsecost (coststring);
         JOptionPane.showMessageDialog(null,"With " + TAX * 100 + "% tax, purchase is $" + (cost - cost * TAX));
    }
}

I am getting the following errors:
DebugTwo4.java:11: error: class expected
    cost = double.parsecost (coststring);

DebugTwo4.java:11: error: ';' expected
    cost = double.parsecost (coststring);

Please help!

A: Not sure what parsecost is supposed to do since I don't see a definition for it anywhere, but from what I understand could you not change this line:
cost = double.parsecost (coststring);

To something like this:
cost = Double.parseDouble(coststring);


text:
Q: How to detect GraphQL endpoint using Python I am trying to detect a graphql endpoint using Python language. I am an absolute beginner , but i have tried to make a code.
Can you please suggest changes and better ways to do it?
CODE:
import requests,urllib,urllib.request
import string
consoleDict = [
    "",
    "/graphql",
    "/graphql/console",
    "graphql.php",
    "graphiql",
    "explorer",
    "altair",
    "/playground"
          ]
for endpoint in consoleDict:
    ep = ' http://159.100.248.211 '
    response = requests.get(ep)
    if response.status_code in [200,403]:
        print("It is a GraphQL endpoint",endpoint)

Thank you :)

A: Even with gql, you need the schema to ask for anything. If you don't know it, you could use introspection query:
{
  __schema {
    types {
      name
    }
  }
}

Some endpoints might have this disabled, but if you don't know the schema it is a good starting point.
Try with something like this:
import json
import requests
from urllib import parse

paths = [
    "",
    "/graphql",
    "/graphql/console",
    "graphql.php",
    "graphiql",
    "explorer",
    "altair",
    "/playground"
]

query = """{
  __schema {
    types {
      name
    }
  }
}
"""

for path in paths:
    hostname = 'http://159.100.248.211'
    endpoint = parse.urljoin(hostname, path)
    try:
        print(f"Attempt: {endpoint}")
        response = requests.post(endpoint, json={'query': query}, timeout=0.1)
    except Exception:
        print("No GraphQL endpoint found")
    else:
        if response.status_code == 200:
            json_data = json.loads(response.text)
            if json_data.get('data'):
                print("It is a GraphQL endpoint",endpoint)

Let mw know if this works


text:
Q: How can I create a commit that rolls back another one? For simplicity, let's create a repository with two commits only:
mkdir somedir
cd somedir
git init
echo hello > somefile
git add somefile
git commit -m 'first'
echo world >> somefile
git commit -am 'second'

For clarity, at this point git log --oneline returns
fd5b1ce (HEAD -> master) second
f621ab9 first

What I want to get to is the following
xxxxxxx (HEAD -> master) third
fd5b1ce second
f621ab9 first

with somefile in third having the same content as somefile in first.
I could certainly do git cherry-pick master~ (here master is fd5b1ce) and resolve the conflict totally in favour of first, but maybe there's a cleaner approach?

A:
commit that rolls back another one?

That seems a good fit for git revert
git revert <second commit>

But that apply to all files from second commit (being reverted)

with somefile in third having the same content as somefile in first.

If you need to revert only one file, use git restore.
git restore -SW -s=<first commit> -- somefile


text:
Q: unit test to assert that Objects in a TreeMap are in the correct order? I am trying to write a Junit test to assert that Objects in my TreeMap are in the correct order.
How can I do so?
I am trying to do the following:
assertEquals(treeMapFromMethod.get(0), ValueThatShouldBeFirstEntryInTreeMap);

But I am getting the error:
"java.lang.ClassCastException: java.lang.Integer cannot be cast to MyObJect"

This error relates to the Line above.
How can I fix this/ is there a better way to test this?

A: If you use Hamcrest you can do this easily with the contains matcher:
TreeMap<String, Integer> map = new TreeMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);

Assert.assertThat(map.keySet(), Matchers.contains("one", "three", "two"));

The contains matcher checks, if the given collection has the same length and contains the given items in the same order.


text:
Q: Does this character counting program include the newline character? #include <stdio.h>

/* count characters in input; 2nd version */
main()
{
    double nc;

    for (nc = 0; getchar() != EOF; ++nc)
        ;

    printf("%.0f\n", nc);
}

When I compile and run the program and type in a character (example: abcd), hit enter, then hit the escape character CTRL+Z, it says 5. Is that because of the "hidden" newline character or does it count the EOF command? Because when I type the EOF command alone it stays as 0.

A: Yes.
getchar waits for you to enter "something"; and Enter is 'something' (that is, it has a defined character value; other keys, Shift for example, may not).
By that same token, the key combo Ctrl+Z would be "something" as well -- the value 26 on most systems -- but the standard input/output library you are using treats this particular code as a special command: EOF. On my OS, Mac OSX, that would be Ctrl+D (for reasons unknown to me, other than "historically, Ctrl+D is used to signal EOF on Unix-like systems").
The 'newline character' is by no means "hidden" or "invisible", it's just another number that gets read and stored into a variable or string if you instruct it to do so. The reason you cannot see it is because putchar and other text printing functions do something else than "display the associated character": it moves the cursor to the next line. That also is part of the standard functionality, and a good thing it is too. After all you wouldn't want to press Space to "move to the next line". (In fact it's such a common function of this code that most fonts don't even bother to have a displayable item for it.)
See also What does getchar() exactly do? for more background information.


text:
Q: THREE.js - Change property of one, all object change I have an issue. I put properties in my spheres array as opacity/visible etc..
When (in MouseDown event) I want change only one sphere property, but all of them change. I don't understand why...
I describe you my part of code.
for (var i = 0; i < data.nodes.length; i++)
        {
         //coordinates of spheres and others properties
         spheres[i].material.transparent=true;
         spheres[i].material.opacity=0.2;
         scene.add(spheres[i]);
         force.start();
         }
         spheres[anyone].material.opacity=0.8;

sorry, but my English is not very good.
Thank you in advance!

A: I suspect it is due to all the spheres using the same material instance, therefore changing one will change them all.
Adding unique materials to each of your spheres will probably overcome your problem.


text:
Q: Check if element is x pixels away from being visible I found this function to check if an element is visible on the screen:
function isScrolledIntoView(elem){
  var $elem = $(elem);
  var $window = $(window);

  var docViewTop = $window.scrollTop();
  var docViewBottom = docViewTop + $window.height();

  var elemTop = $elem.offset().top;
  var elemBottom = elemTop + $elem.height();

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

How can this be modified so that it will return true if an element is x pixels (e.g. 500 px) away from being visible on screen? (With the element being below the screen).

A: Assuming this function works the way you want it to, just add to docViewBottom
var x = 500; // or whatever buffer you find works best
var docViewBottom = docViewTop + $window.height() + x;


text:
Q: Converting Matrix Definition to Zero-Indexed Notation - Numpy I am trying to construct a numpy array (a 2-dimensional numpy array - i.e. a matrix) from a paper that uses a non-standard indexing to construct the matrix. I.e. the top left element is q1,2. instead of q0,0.
Define the n x (n-2) matrix Q by its elements qi,j for i = i,...,n and j = 2, ... , n-1 given by
qj-1,j=h-1j-1, qj,j = h-1j-1 - h-1j and qj+1,j=hjj-1. (I have posted this in Latex form here: http://www.texpaste.com/n/8vwds4fx)
I have tried to implement in python like this:
# n = u_s.size
# n = 299 for this example
n = 299
Q = np.zeros((n,n-2))

for i in range(0,n+1):
    for j in range(2,n):
        Q[j-1,j] = 1.0/h[j-1]
        Q[j,j] = -1.0/h[j-1] - 1.0/h[j]
        Q[j+1,j] = 1.0/h[j]

But I always get the error:
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-54-c07a3b1c81bb> in <module>()
      1 for i in range(1,n+1):
      2     for j in range(2,n-1):
----> 3         Q[j-1,j] = 1.0/h[j-1]
      4         Q[j,j] = -1.0/h[j-1] - 1.0/h[j]
      5         Q[j+1,j] = 1.0/h[j]

IndexError: index 297 is out of bounds for axis 1 with size 297

I initially thought I could decrement both i and j in my for loop to keep edge cases safe, as a quick way to move to zero-indexed notation, but this hasn't worked. I also tried incrementing and modifying the range().
Is there a way to convert this definition to one that python can handle? Is this a common issue?

A: Simplifying the problem to make the assignment pattern obvious:
In [228]: h=np.arange(10,15)
In [229]: Q=np.zeros((5,5),int)
In [230]: for j in range(1,5):
     ...:     Q[j-1:j+2,j] = h[j-1:j+2]

In [231]: Q
Out[231]:
array([[ 0, 10,  0,  0,  0],
       [ 0, 11, 11,  0,  0],
       [ 0, 12, 12, 12,  0],
       [ 0,  0, 13, 13, 13],
       [ 0,  0,  0, 14, 14]])

Assignment to the partial first and last columns may need tweaking.  Here's the equivalent built from diagonals:
In [232]: np.diag(h,0)+np.diag(h[:-1],1)+np.diag(h[1:],-1)
Out[232]:
array([[10, 10,  0,  0,  0],
       [11, 11, 11,  0,  0],
       [ 0, 12, 12, 12,  0],
       [ 0,  0, 13, 13, 13],
       [ 0,  0,  0, 14, 14]])

With the h[j-1], h[j] indexing this diagonal assignment probably needs tweaking, but it should be a useful starting point.

Selecting h values more like what you use (skipping the 1/h for now):
In [238]: Q=np.zeros((5,5),int)
In [239]: for j in range(1,4):
     ...:     Q[j-1:j+2,j] =[h[j-1],h[j-1]+h[j], h[j]]
     ...:
In [240]: Q
Out[240]:
array([[ 0, 10,  0,  0,  0],
       [ 0, 21, 11,  0,  0],
       [ 0, 11, 23, 12,  0],
       [ 0,  0, 12, 25,  0],
       [ 0,  0,  0, 13,  0]])

I'm skipping the two partial end columns for now.  The first slicing approach allowed me to be a bit sloppy, since it's ok to slice 'off the end'.  The end columns, if set, will require their own expressions.
In [241]: j=0; Q[j:j+2,j] =[h[j], h[j]]
In [242]: j=4; Q[j-1:j+1,j] =[h[j-1],h[j-1]+h[j]]
In [243]: Q
Out[243]:
array([[10, 10,  0,  0,  0],
       [10, 21, 11,  0,  0],
       [ 0, 11, 23, 12,  0],
       [ 0,  0, 12, 25, 13],
       [ 0,  0,  0, 13, 27]])

The relevant diagonal pieces are still evident:
In [244]: h[1:]+h[:-1]
Out[244]: array([21, 23, 25, 27])

A: The equation doesn't contain any value for i.  It is referring only to j.  The Q should be a matrix of dimension n+2 x n+2.  For j = 1, it refers to Q[0,1], Q[1,1] and Q[2,1].  for j =n, it refers to Q[n-1,n], Q[n,n] and Q[n+1,n].  So, Q should have indices from 0 to n+1 which n+2
I don't think, you require the i loop.  You can achieve your results only with j loop from 1 to n, but Q should be from 0 to n+1


text:
Q: How to validate a link showing 500 error in Selenium? I am trying to validate the links of a website using server response code and page title, the server response found through the code shown below is 200 and page title is also same for all the pages.
the code is as follows:
if(url == null || url.isEmpty())
{
System.out.println("URL is either not configured for anchor tag or it is
empty");
objExcelFile.writeExcel(filePath,"skipped_links",url);

        }

        else   if(!url.startsWith(homePage)){

            System.out.println("URL belongs to another domain, skipping it.");
            objExcelFile.writeExcel(filePath,"skipped_links",url);

        }
        else{
        try {
            huc = (HttpURLConnection)(new URL(url).openConnection());

            huc.setRequestMethod("HEAD");

            huc.connect();

            respCode = huc.getResponseCode();

            if(respCode != 200){
                System.out.println(url+" is a broken link");
                String Actualtitle = driver.getTitle();
                System.out.println(Actualtitle);
                System.out.println(respCode);

                objExcelFile.writeExcel(filePath,"broken_links",url);

            }
            else{
                 String Actualtitle = driver.getTitle();
                 System.out.println(Actualtitle);
               if (Actualtitle.contentEquals(unexpectedTitle)){
                   System.out.println(url+ " is a broken link");
                 objExcelFile.writeExcel(filePath,"broken_links",url);
               } else {
                   System.out.println(url+ " is a valid link");
                   System.out.println(respCode);

                 objExcelFile.writeExcel(filePath,"valid_links",url);
               }

            }

        } catch (MalformedURLException e) {

            e.printStackTrace();
        }

The header is intact but the link is showing 500 error below the header. The issue is that even though page is showing 500 error, I am getting the server response code as 200, hence I am not able to make out whether this link is broken or not
This is the screenshot of the issue for the page I am validating :
enter image description here

A: Once you induce connect() as in :
huc.connect();

You can write as many for() loops to check any condition of the Response Code invoking getResponseCode()  method as below :
if (huc.getResponseCode() == 200)
{
    System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}

if (huc.getResponseCode() == 500)
{
    System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}

if (huc.getResponseCode() == 404)
{
    System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}

if (huc.getResponseCode() == 402)
{
    System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}

if (huc.getResponseCode() == httpUrlConnect.HTTP_NOT_FOUND)
{
    System.out.println(
            linkURL + " - " + huc.getResponseMessage() + " - " + huc.HTTP_NOT_FOUND);
}

} catch (IOException e)
{
    System.out.println(e.getMessage());
}


text:
Q: Expect script called from bash script not returning control when completed I am calling the expect script from bash script inside for loop using multithreading in it. The expect script does ssh login and call python script using nohup command for restarting host.
But, after completing the restart, the control not returned to the bash script.
Shell script code:
for host in ${hosts[@]};
do
  ./b.exp $id $pswd $host &
done
wait
echo "Completed"

Expect script code:
set timeout -1
spawn ssh <server login>
send "nohup /loc/c.py $host\r"
send -- "exit\r"
expect eof

I am expecting after all the hosts restart completion, the script should print "Completed".
But, it is not printing anything and I need to manually exit the execution.
Could someone please tell what wrong I am doing here?

A: nohup doesn't detach the terminal, you want to send
 nohup /loc/c.py $host &

where the & to run the job in the background is the significant change.
(Properly speaking $host should be quoted, too, but if you are sure it contains a single token without whitespace or wildcard characters, this should not matter. Similarly "${hosts[@]}" should have double quotes, but again, under the given conditions, this should be fine without quotes.)


text:
Q: Should I reset $wp_query? I am not totally new on WordPress but the query thing is a bit confusing to me. I searched the web and read a lot of articles, but I couldn't find what I needed. Maybe it could help a lot of people who have WordPress skills like me.
I want to create a shortcode and I need to loop through a custom post type called events.
function leweb_get_suggested_events() {

    // Query
    global $wp_query;

    // Arguments
    $args = array(
        'post_type' => 'events',
    );

    ob_start();

    $query = new WP_Query( $args );

    if( $query->have_posts() ) {
        echo '
';
        while( $query->have_posts() ) {
            $query->the_post();
            echo '
' . get_the_title() . '
';
        }
        echo '
';
    }

    $output = ob_get_clean();
    return $output;

}
add_shortcode( 'leweb_suggested_events', 'leweb_get_suggested_events' );

The query is right and its working. But should I reset something?
I call the global $wp_query to get in the main loop. This is what I found out on reading some articles.
Then I start my own loop with $query = new WP_Query($args);
So I have two loops right? The main loop and my own loop.
Should I reset them both or just one of them, or is it fine like above?

A:
The query is right and its working. But should I reset something?

Yes!

Should I reset them both or just one of them, or is it fine like above?

Neither!
Your WP_Query object is self contained in $query, so there's no reason to touch the $wp_query global variable, why would you? $wp_query represents the main query, so leave it alone.
What you need to reset, is the current post. Notice $query->the_post() sets the current post, you need to undo that after the loop ends:
    if( $query->have_posts() ) {
        while( $query->have_posts() ) {
            $query->the_post();
            ....
        }
        wp_reset_postdata();
    }

A Word on wp_reset_query()
The wp_reset_query() function is something you might see in your research, but avoid this. It's intended to clean up after query_posts, which is a function you should never use.
If you ever find yourself needing to use query_posts, or wp_reset_query in your client work, something has gone terribly wrong. Scrub these from your memory, scream when you see them in code, and refactor them with extreme predjudice.
Shortcodes and Blocks
Have you considered turning this into a GB block instead of a shortcode? Just create a block that's rendered in PHP, there's no need to learn React or advanced JS


text:
Q: How to update multiple records of the column in MSSQL? I want to update a column in a table, by increment its value by 1.
Here I attach the code I tried
declare @count int
, @num int
, @Seed VARCHAR(10) = 'PR0001'
, @IncrementedValue int = 0
, @Code varchar(10)

set @count = (select Count(*) from psa.ProductDemo)
while @num <= @count
begin

    update psa.ProductDemo
    set Code='PR' + right('0000' + cast(@IncrementedValue as varchar(10)),4)
    where Code != null

    set @IncrementedValue = @IncrementedValue + 1

    set @num = @num + 1

end

select *
from psa.ProductDemo

output
1-)
457B995D-CF6E-4126-A006-A8E45D36A246    PR0002   Toothed Fruit Mill NULL    2018-01-06 00:00:00.000 NULL    8435    NULL    2018-11-02 12:26:20.923 NULL    NULL    NULL

2-)
B5F46B95-EA8D-4988-9536-45757E371B14    PR0002  Accessories for Disintegrator   NULL    2018-01-10 00:00:00.000 NULL    8479    NULL    2018-11-02 12:26:20.923 NULL    NULL    NULL

A: You don't want to use a loop/CURSOR here, it'll be awfully slow. A far better approach would be to use ROW_NUMBER() and a CTE.
WITH CTE AS(
    SELECT Code,
           ROW_NUMBER() OVER (ORDER BY {ORDER BY COLUMN}) AS RN
    FROM psa.ProductDemo
    WHERE Code IS NOT NULL -- != NULL won't work
    )
UPDATE CTE
SET Code = 'PR' + RIGHT('0000' + CONVERT(varchar(4),RN),4);

Note the section in braces ({}), which needs attention from you. Also, note the comment about code != NULL. {expression} (=/!=/>/</etc) NULL will always return Unknown (thus never be true). When comparing NULL you always need to use IS (NOT) NULL.

A: You never initially set @num, so it is NULL. NULL + 1 = NULL, and NULL <= [somenumber] = UNKNOWN, so you never actually update anything. The solution would be to set @num the same way you do with @IncrementedValue.
By the way, you can also do this set based with a ROW_NUMBER(). If your code is working, you will update the same rows multiple times (ending up with identical codes), because every loop you update code for the records where Code != null (which should be IS (NOT?) NULL).


text:
Q: Hide and show particular form items on checked and unchecked selectbox? I am using the below given code to hide and show particular form items, but this doesn't work kindly let me know what I am missing in my code?
HTML:
<input id="id_code_col" type="checkbox" name="code_col"></input>

SCRIPT:
$(document).ready(function(){
var selectBox = jQuery('#id_code_col');
selectBox.change(function () {
    if ($(this).val() == '1') {
      $('#id_FullColumn').show();
      $('#id_FirstColumn').hide();
      $('#id_SecondColumn').hide();

    }
    else {
      $('#id_FullColumn').hide();
      $('#id_FirstColumn').show();
      $('#id_SecondColumn').show();
    }
});
});

N.B: I can not add or remove anything from html. What ever I have to do is to do it with script. Kindly help!

A: You can use .is() along with :checked selector to check whether your checkbox is checked or not, so try to use:
if ($(this).is(':checked')) {

or pure javascript using:
if(this.checked)

instead of:
if ($(this).val() == '1') {

A: selectBox.change(function () {
    if ($(this).is(':checked')) {
      $('#id_FullColumn').show();
      $('#id_FirstColumn').hide();
      $('#id_SecondColumn').hide();

    }
    else {
      $('#id_FullColumn').hide();
      $('#id_FirstColumn').show();
      $('#id_SecondColumn').show();
    }
});

A: do like this:
if(this.checked)
{
// checked
}

else
{
// unchecked
}

for your case:
   $(document).ready(function(){
    var selectBox = jQuery('#id_code_col');
    selectBox.change(function () {
        if (this.checked) {
          $('#id_FullColumn').show();
          $('#id_FirstColumn').hide();
          $('#id_SecondColumn').hide();

        }
        else {
          $('#id_FullColumn').hide();
          $('#id_FirstColumn').show();
          $('#id_SecondColumn').show();
        }
    });
    });

A: Change this
 if ($(this).val() == '1') {

to this
 if (this.checked) {

Because you don't have to check for the value to 1, as your checkbox doesn't have any value set to 1.
So you have to check for the state of that  checkbox with checked method.

A: $(document).ready(function () {
            var selectBox = jQuery('#id_code_col');
            selectBox.change(function () {
                if (this.checked) {
                    alert("checked");
                }
                else {
                    alert("unchecked");
                }
            });
        });

A:           $(function(){
                $('#id_code_col').change(function(){
                  if($(this.checked)){
                   alert('checked');
                    }else{
                     alert('unchecked');
                  }
                 });
           });


text:
Q: Editing IPTABLES nat rule in cron job I am sitting here with an issue: I need to switch the source interface for iptables' NAT rule at a given time. I want to basically do soemthing like this - caution: concept code:
#!/bin/bash
if [ it is 11.30pm ]; then
    iptables CHANGE FIRST RULE IN FORWARD CHAIN AND MAKE ORIGINAL -o wlan0 INTO -o ppp0
fi

A same script needs to run at 8AM to change that backwards - wlan0 to ppp0. I am setting up my current nat with an init.d script:
#!/bin/bash

### BEGIN INIT INFO
# Provides:          subnet
# Required-Start:    ifplugd
# Required-Stop:     $ifplugd
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Brings up the NAT system
# Description:       Initializes the NAT routing (SUBnet)
### END INIT INFO

# This is rather simple, as we have the script already...
[ "$1" != "" || "$1" != "start" ] && exit 0;

echo -n .
/sbin/iptables -A FORWARD -o wlan0 -i eth0 -s 192.168.200.0/24 -m conntrack --ctstate  NEW -j ACCEPT

echo -n .
/sbin/iptables -A FORWARD -m conntrack -ctstate ESTABLISHED,RELATED -j ACCEPT

echo -n .
/sbin/iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE

echo
echo "[ OK! ] NAT is now initialized with wlan0->eth0."

This works nicely during boot, but I want the source interface to change, so I have continious internet.
At some point, the ppp0 device might not be present, so the script would also need to check for its presence, and then switch. I will be using a udev rule - most probably - to run sakis3g --connect once the device is connected.
Does anyone have any idea how to realize that? I am new to cronjobs, and I cant wrap my head really aorund IPTABLES, I am glad I got to put that init.d script together :)

A: iptables doesn't control on which interface the packet is going out. It simply allows the packet to go out that interface and changes its source address.
Adding rules for both interfaces should be enough for NAT to work on both interfaces.


text:
Q: How to write while loop condition The program asks for password and you enter it, else you get 3 attempts and if you fail 3 times it locks (in theory).
Questions:

*

*How should I write the while loop, now it just says "Line can't be resolved to a variable" and I don't know how to solve this.

*The subtraction of attempts also doesn't work. How should I write it?
Here's the code:
import java.util.Scanner;

public class Application {
    public static void main(String[] args) {

        while(line != correctPass) {

            String correctPass = "Java";

            System.out.println("Enter the password");
            Scanner input = new Scanner(System.in);
            String line = input.nextLine();

            if(line.equals(correctPass)) {
                System.out.println("Wellcome back sir!");
                break;
            }
            else {
                int num = 3;
                System.out.println("Wrong password, please try again! "  + num + " attempts left!");
                num = num - 1;
                    if(num == 0) {
                        System.out.println("System Locked!");
                        break;
                    }
            }
        }
    }
}

A: line is used before it is declared. Try putting the declaration at the top as String line = null.
Also, because you are setting the num = 3 in the loop, it never gets decremented. It needs to be set to 3 outside of the loop.
I would seriously suggest checking out this tutorial.
There are some other issues too, you may want to check out the difference between something != somethingElse and !something.equals(somethingElse).

A: The variables line and correctPass is declared inside the loop, hence the condition statement will not have access to those variables, it should be declared and initialized outside the loop.
It could be something like this:
public class Application {
    public static void main(String[] args) {
        String correctPass = "Java";
        Scanner input = new Scanner(System.in);
        int num = 3;

        System.out.println("Enter the password");

        String line;
        while (num != 0 && !(line = input.nextLine()).equals(correctPass)) {

            System.out.println("Wrong password, please try again! "  + num + " attempts left!");
            num = num - 1;
            System.out.println("Enter the password");
        }

        if (num == 0) {
            System.out.println("System Locked!");
        } else {
            System.out.println("Wellcome back sir!");
        }
    }
}

A: I would prefer to use do while which is the actual logic of do while that you're trying to achieve in a while.
import java.util.Scanner;

public class Application {

    public static void main(String[] args) {

        String    correctPass = "Java";
        int          attempts = 3;
        boolean authenticated = false;

        Scanner         input = new Scanner(System.in);

        do {
            System.out.println("Enter the password");
            String   userPass = input.nextLine();
            if( userPass.equals(correctPass) ){
                System.out.println("Welcome back sir!");
                authenticated = true;
            } else {
                System.out.println("Wrong password, please try again! "  + attempts + " attempts left!");
                attempts = attempts - 1;
                if(attempts == 0) {
                    System.out.println("System Locked!");
                    break;
                }
            }
        } while(! authenticated);

        input.close();
    }
}

To point the mistakes in your code,
1) You need to use .equals() to compare a String
2) The original password should be declared before the loop
3) You're re-initialising num variable for every loop (so definitely you won't be locked at any situation ever), so it should also be declared before the loop.

A: You need to declare line outside the while loop - variables don't exist (and can't be referenced) before they are declared.
You use both correctPass and line in the while loop condition, but they aren't created until 1 and 3 lines later, respectively.
 while(line != correctPass) {
    String correctPass = "Java";

    System.out.println("Enter the password");
    Scanner input = new Scanner(System.in);
    String line = input.nextLine();

You need to reformat it to look more like this:
String correctPass = "Java";
int num = 3;
Scanner input = new Scanner(System.in);
System.out.println("Enter the password");
String line = input.nextLine();

while(!line.equals(correctPass)) {
       num = num - 1;
       if(num == 0) {
            System.out.println("System Locked!");
            break;
        }
       System.out.println("Wrong password, please try again! "  + num + " attempts left!");
       line = input.nextLine();
}

Why:
There's no need to recreate correctPass each time the while loop runs, since its the same every time.
Similarly, its silly to recreate the scanner each time, since it isn't changing.
And, as pointed out in comments, if you define num each time you loop it will never reach zero and therefore never lock, since it is redefined as 3 each time.
.equals is needed to compare strings. This is why if you're curious.

A: *

*You the String variable is initialised AFTER your while statement, so line does not exist at the moment your first while condition is evaluated


text:
Q: PDO MySQL SELECT with multiple criteria within an IF statement I am a newbie and wish to learn the following;
I wish to query MySQL with PHP (my PDO connection is $dbo);
I have a the variables;

*

*$form_category //an integer

*$form_subcategory //an integer

*$form_subcategory2 //text

*$fname //the file name

*$form_class // 'create' is the class in this example

*$form_location //directory where the pdf is stored

My attempt at the query is;
///start query ///

  $quer2 = $dbo->prepare("SELECT form_id,form_description
    FROM form_detail
    WHERE form_name < :form_name AND form_category = :form_category AND form_subcategory = :form_subcategory AND form_subcategory2 = :form_subcategory2");
        $quer2 ->bindParam(':form_id', $form_id);
    $quer2 ->bindParam(':form_name', $fname);
    $quer2 ->bindParam(':form_category', $catid);
    $quer2 ->bindParam(':form_subcategory', $subcatid);
    $quer2 ->bindParam(':form_subcategory2', $subcat2);
    $quer2 ->bindParam(':form_class', $form_class);
    $quer2 ->bindParam(':form_cerfa', $form_cerfa);
    $quer2 ->bindParam(':form_description', $form_description);
    $quer2 ->execute();

   ///End new query ///

I wish to output the 'form_reference' and 'form_description' from the variables above as well as the form name($fname) and display it in a table with href on the filename for example;
echo "".$fname."
";

A: Do it this way  ,
$quer2 ->execute();
if ($sp->execute())  // Verify that result exist
{

        $result=$quer2->fetch(PDO::FETCH_OBJ);
        $result->closeCursor();

//   Now , Access Form id and description in this way

    echo "Form id : $result->form_id";
    echo "Form Description : $result->form_description" ;
}

Another thing ,
$quer2 ->bindParam(':form_id', $form_id);
If It's an int modify it like this ,
 $quer2 ->bindParam(':form_id', $form_id , PDO::PARAM_INT);
And if string then PDO::PARAM_STR .
It's a good practice and gives you added security.


text:
Q: Applescript: how to create a folder only if a certain condition is met - Script Tweaking I need help tweaking the following script that I made. My goal is when item 1a and/or 4d is chosen their respective .ai file will be duplicated to the root folder of the front most finder window opened. When item 2b and/or 3c is selected, it will look at the front most finder window opened for a folder named "TargetFolder". If "TargetFolder" exist then duplicate 2b.ai and/or 3c.ai to this folder. ELSE, create folder "TargetFolder" then duplicate 2b.ai and/or 3c.ai to folder "TargetFolder".
property TargetFolder : "TargetFolder"

tell application "Finder"
    tell application "Finder" to set the this_folder to (folder of the front window) as alias

    try
        set mylist to (choose from list {"1a", "2b", "3c", "4d"} with multiple selections allowed)
    end try

    --This should be applied ONLY if item 2b and/or 3c is chosen
    if not (exists folder TargetFolder of this_folder) then
        make new folder at this_folder with properties {name:TargetFolder}
    end if

    try
        if mylist contains "1a" then
            duplicate file "1a.ai" of folder "Source Folder" of folder "Desktop" of folder "user" of folder "Users" of startup disk to this_folder
        end if
        if mylist contains "2b" then
            duplicate file "2b.ai" of folder "Source Folder" of folder "Desktop" of folder "user" of folder "Users" of startup disk to folder "TargetFolder" of folder this_folder
        end if
        if mylist contains "3c" then
            duplicate file "3c.ai" of folder "Source Folder" of folder "Desktop" of folder "user" of folder "Users" of startup disk to folder "TargetFolder" of folder this_folder
        end if
if mylist contains "4d" then
            duplicate file "4d.ai" of folder "Source Folder" of folder "Desktop" of folder "user" of folder "Users" of startup disk to this_folder
        end if
    end try
end tell

Thank you so much in advance! Have a great one:-)

A: The following code:

*

*Ensures the existence of a specific target folder, but only if the 2nd and/or the 3rd item list items are among the items chosen by the user.

*

*That is, if the target folder doesn't already exist, it is created.

*Processes all chosen items in a loop afterward.
property TargetFolderName : "TargetFolder"

tell application "Finder"

    # Define input list.
    set inputList to {"1", "2", "3", "4"}

    # Prompt user for a potentially multiple-item selection from the list.
    set chosenList to choose from list inputList with multiple selections allowed
    # Exit, if nothing was chosen.
    if chosenList is false then return

    # Get the active folder from Finder's front window.
    set this_folder to (folder of the front window) as alias

    # Test if the 2nd item from the input list is among the selected items,
    # and only then create / ensure the existence of the target folder.
    set targetFolder to missing value
    if chosenList contains item 2 of inputList ¬
        or ¬
        chosenList contains item 3 of inputList then

        # See if the target folder already exists there.
        try
            set targetFolder to folder TargetFolderName of this_folder
        end try
        # If it doesn't exist yet, create it now.
        # Note: This could fail.
        if targetFolder is missing value then
            set targetFolder to make new folder at this_folder with properties {name:TargetFolderName}
        end if

    end if

    # Process all chosen items in a loop.
    # Note that the loop variable receives a *reference* to each list item.
    repeat with chosenItemRef in chosenList

        # Resolve the list-item *reference* to get the actual *value*.
        set chosenItem to contents of chosenItemRef

        # Get the source file matching the value at hand:
        set sourceFile to alias ("Macintosh HD:Users:user:Desktop:Source Files:" & chosenItem & ".ai")

        # Now test the value and take action accordingly.
        if chosenItem is item 2 of inputList ¬
            or chosenItem is item 3 of inputList then # 2nd or 3rd item: copy to targetFolder
            # Note: `with replacing` blindly replaces an existing target file.
            duplicate sourceFile to targetFolder with replacing
        else # all others: copy to this_folder
            duplicate sourceFile to this_folder with replacing
        end if

    end repeat

end tell


text:
Q: When to use multiple column families in HBase? I am new to HBase and currently implementing an application using this data store. To be honest I have very bad time using it. However, as a recommendation in HBase docs, it is preferred to use 1-3 column family. Currently I am using only one. Can someone give me an example when to use multiple column families, please mention some use cases and explain what are the benefits of down that.
Thank a lot

A: In Hbase one region is assiocated with one column family, so a least one HFile in the FS. More column families means more files, and when you'll query a row, the region server will have to grap data in multiple places, and this will slow your system.
Here is my use case: I use only one column family for my real/legacy/usefull data, and an other for my computed/external/cached/stored-outsite/flatted data. This is usefull if you want to delete/refresh/recompute the data in this temporary CF.


text:
Q: OpenCV, trying to get maximum and minium of multiple contours So I am trying to get Max top and lowest points in multiple contours.
It works when I want to find a the top and bottompoint for the biggest contour:
c = max(contours, key=cv.contourArea)
extTop = tuple(contours[-1][contours[-1][:, :, 1].argmin()][0])
extBot = tuple(contours[-1][contours[-1][:, :, 1].argmax()][0])

Now I try to get the top and bottom point of all the contours together but it doesnt work:
extTop = tuple(contours[contours[:, :, 1].argmin()][0])
extBot = tuple(contours[contours[:, :, 1].argmax()][0])

it gives:
extTop = tuple(contours[contours[:, :, 1].argmin()][0])

TypeError: tuple indices must be integers or slices, not tuple

Anyone knows a solution? I am prety new to coding so it might be a stupid question, but I have been trying for more than a day now.
Edit:
tried this first, also didnt work:
c = max(contours, key=cv.contourArea)
extTop = tuple(contours[-1][contours[-1][:, :, 1].argmin()][0])
extBot = tuple(contours[-1][contours[-1][:, :, 1].argmax()][0])

A: In order to get the top and bottom point of each contour, you need to iterate through the tuple containing all the contours.
In the following, we pick one contour c from the collection of contours. Draw the top and bottom most point:
for c in contours:
  top_point = tuple(c[c[:,:,1].argmin()][0])
  bottom_point = tuple(c[c[:,:,1].argmax()][0])
  img = cv2.circle(img, top_point, 6, (255, 255, 0), -1)
  img = cv2.circle(img, bottom_point, 6, (0, 255, 255), -1)

UPDATE:
The following snippet finds the top-most and bottom-most (Y-coordinate) among ALL contours in the image:
# initialize an array
cc = np.array([[0, 0]], dtype=int)

# iterate through every contour
for i, c in enumerate(contours):
    # reshape array storing contour boundary points
    c_modified = c.reshape(len(contours[i]), 2)
    # concatenate with initialized array
    cc = np.concatenate((cc, c_modified), axis = 0)

# avoiding first element in the initialized array
new_cc = cc[1:]

new_cc now contains the boundary coordinates of ALL contours.
Use np.max() and np.min() functions to get desired values:
bottom_most = np.max(new_cc[:,1])
top_most = np.min(new_cc[:,1])

A: Edit: Change this:
extTop = tuple(contours[-1][contours[-1][:, :, 1].argmin()][0])
extBot = tuple(contours[-1][contours[-1][:, :, 1].argmax()][0])

to:
extTop = tuple(c[c[:, :, 1].argmin()][0])
extBot = tuple(c[c[:, :, 1].argmax()][0])