答:
Three-ish problems.

(1) Compare the following two:

```<code>df[['Y']].as_matrix().shape # (801, 1), yours
df['Y'].as_matrix().shape   # (801,), better
</code>```

np.fft.fft says if axis is not provided, the last axis is used. In your code, the FFT of an 801 by 1 array is evaluated along the last dimension, i.e., a 1-point FFT—totally not what you wanted.

Solution: remove one pair of brackets.

(2) With this in place, the output of np.fft.fft is complex, as expected. Instead of taking its real-only component, use it’s absolute value.

(3) Furthermore, it appears that Pandas plot has some problems plotting the output of np.fft.fftfreq because its output goes from [0 ... 0.5 -0.5 ... 0]. Simple solution: use np.fft.fftshift.

Solutions to #2–3:

```<code>df['spectrum'] = np.abs(np.fft.fftshift(np.fft.fft(df['Y'])))
df['freq'] = np.fft.fftshift(np.fft.fftfreq(len(df.index), 1))
</code>```

(Alternative solution to #3: use np.fft.rfft and rfftfreq, since your input data is real.)

Final code:

```<code>import pandas as pd
import numpy as np

df = pd.read_csv('dat.csv', sep=',')
df.plot(x='X', y='Y')

df['spectrum'] = np.abs(np.fft.fftshift(np.fft.fft(df['Y'])))
df['freq'] = np.fft.fftshift(np.fft.fftfreq(len(df.index), 1))
df.plot(x='freq', y='spectrum')
</code>```

Result:

Suggestion: better than np.abs is to use db (decibels). I.e., db = lambda x: 20 * np.log10(np.abs(x)). Alternatively, if that’s not your thing, just plot the y-axis on a log-scale.

Observation: you should be able to remove the high-frequency noisy by low-pass filtering the data, with a cutoff frequency of 0.25 normalized Hz. (Let me know if you have trouble with that.) If I collected this kind of data, I’d worry that my anti-aliasing filter before the ADC wasn’t working—one shouldn’t ever see so much noise right at the Nyquist frequency. If you are getting a lot of aliasing, who knows what the original signal is.

Title: Unexpected Fourier Transform result in Python Numpy

Body:
I am having a problem plotting the fourier transform of a data series (Y = intensity, X =  wavelength). The goal is to remove the sinusoidal oscillation but applying a notch filter to the fourier transform of the data, followed by another fourier transform.

Here's the original data series:

df = pd.read_csv(file, sep='\t', skiprows=7)
df.plot(x='X', y='Y')

And after doing the fourier transform:

df['spectrum'] = np.fft.fft(df[['Y']]).real
df['freq'] = np.fft.fftfreq(len(df.index), 1)
df.plot(x='freq', y='spectrum')

Problem: Why did it plot nothing? Was the FFT done incorrectly?

Data

X   Y
500 383.800049
501 -407.599976
502 435
503 -446.8
504 442.800049
505 -419.399963
506 425.200073
507 -423.599976
508 387.400024
509 -438.199951
510 473.599976
511 -446.399963
512 392.599976
513 -393
514 414.599976
515 -392.199951
516 469.599976
517 -359.8
518 544.6
519 -365.399963
520 535.2001
521 -361.399963
522 527.4
523 -389.399963
524 556.6
525 -399
526 534.800049
527 -360.8
528 689.2001
529 -206.399963
530 904.2001
531 51
532 1166.00012
533 230.200073
534 1338.4
535 254.200073
536 1192.6
537 149
538 925.7999
539 -119.599976
540 745.800049
541 -329.399963
542 602.2001
543 -344
544 469.599976
545 -453.599976
546 384.800049
547 -485.599976
548 334.599976
549 -506
550 305.800049
551 -525.199951
552 412.400024
553 -419
554 404.599976
555 -466.199951
556 466.400024
557 -437.399963
558 478.400024
559 -389
560 478.599976
561 -391.199951
562 461.200073
563 -366
564 481.599976
565 -414.399963
566 525.800049
567 -379.8
568 495.200073
569 -368.599976
570 518.800049
571 -388
572 485
573 -412.599976
574 519.4
575 -383
576 656.2001
577 -334
578 609.800049
579 -304.399963
580 563.800049
581 -352.199951
582 567.2001
583 -372.399963
584 463.400024
585 -362.399963
586 516.2001
587 -309.199951
588 548.4
589 -340.8
590 627
591 -352.199951
592 686.2001
593 -302.599976
594 736.4
595 -301.399963
596 716.800049
597 -337.399963
598 642.2001
599 -332.599976
600 646.800049
601 -316.399963
602 733.800049
603 -274.199951
604 715.800049
605 -325.8
606 683.6
607 -352.8
608 581
609 -352.399963
610 611.2001
611 -360.8
612 555.800049
613 -348.199951
614 583.4
615 -416.8
616 539.4
617 -337.199951
618 607.4
619 -310.8
620 542.800049
621 -300.8
622 534.4
623 -295.399963
624 603.6
625 -348
626 599.800049
627 -252.199951
628 576.800049
629 -309
630 703.4
631 -300.399963
632 621.800049
633 -345.199951
634 586.2001
635 -314.8
636 615.2001
637 -352.399963
638 623.800049
639 -281.399963
640 636.2001
641 -367
642 546
643 -295
644 595.4
645 -342.399963
646 554.6
647 -358.399963
648 567.4
649 -379
650 581.2001
651 -383.8
652 497.400024
653 -343.399963
654 588
655 -379
656 524.6
657 -365.8
658 506.200073
659 -413.8
660 554.800049
661 -391.8
662 541.800049
663 -409.199951
664 573
665 -390.399963
666 535
667 -373.8
668 513.2001
669 -376
670 538.4
671 -391
672 566.2001
673 -424.199951
674 493.200073
675 -471.199951
676 408.800049
677 -454
678 289
679 -612
680 252.200073
681 -413.8
682 465.800049
683 -251.399963
684 708.2001
685 -134.599976
686 860.2001
687 -56.4000244
688 907.7999
689 23.2000732
690 935.2001
691 9.599976
692 960.0001
693 201.599976
694 1355.6
695 78.4000244
696 1265.79993
697 0.200073242
698 1283.6
699 -11
700 1103.20007
701 -50.4000244
702 1067.00012
703 -35
704 1080.79993
705 -67.5999756
706 1025.6
707 -155
708 945.4
709 -129.399963
710 835.800049
711 -230.599976
712 722.800049
713 -267.199951
714 743.2001
715 -281.199951
716 675
717 -278.599976
718 612.800049
719 -283.399963
720 687
721 -296.199951
722 626.6
723 -292.599976
724 674.800049
725 -264
726 663.800049
727 -272.199951
728 644.6
729 -266
730 608.4
731 -293
732 660.2001
733 -291.599976
734 690.4
735 -274.399963
736 646.2001
737 -233
738 645.800049
739 -206.599976
740 641.4
741 -222.599976
742 671.6
743 -282.199951
744 664.6
745 -207.399963
746 689
747 -277.8
748 662
749 -236.199951
750 710.4
751 -198.399963
752 747.2001
753 -227.599976
754 704
755 -278.199951
756 731
757 -237
758 698.4
759 -284
760 613
761 -289.8
762 638.4
763 -297.599976
764 696.800049
765 -245.799988
766 628.2001
767 -218.399963
768 657
769 -276.8
770 680.4
771 -256
772 656.800049
773 -305.399963
774 613.800049
775 -354.399963
776 755.2001
777 -282.199951
778 778.4
779 -267.199951
780 691.800049
781 -261.399963
782 732.4
783 -287.8
784 690.2001
785 -292
786 711.2001
787 -262.199951
788 751.800049
789 -286.8
790 680.800049
791 -273
792 688.800049
793 -256.199951
794 713.6
795 -293.199951
796 679.800049
797 -324.8
798 607
799 -345.199951
800 548.4
801 -339.8
802 550.4
803 -359.399963
804 557.2001
805 -326.399963
806 536
807 -409.599976
808 462.400024
809 -453
810 466.800049
811 -450.599976
812 531
813 -384.8
814 585
815 -291.399963
816 608.6
817 -380.199951
818 530.4
819 -387.199951
820 539.4
821 -327
822 597.2001
823 -321.599976
824 284.200073
825 -586
826 211.800049
827 -509
828 220.200073
829 -586
830 186.200073
831 -577.399963
832 222.200073
833 -538.8
834 200.200073
835 -598.199951
836 196.599976
837 -571.8
838 148.599976
839 -612.399963
840 193.400024
841 -589.399963
842 206.200073
843 -593
844 144.599976
845 -572.399963
846 141.400024
847 -598
848 156.200073
849 -604.8
850 160.800049
851 -562
852 87.5999756
853 -649
854 84.5999756
855 -649
856 166.400024
857 -537.6
858 207
859 -549.8
860 213.599976
861 -543.6
862 193
863 -555.199951
864 234.800049
865 -563.6
866 221.599976
867 -503
868 196.599976
869 -570.8
870 224.200073
871 -556.8
872 193.400024
873 -545.399963
874 163.599976
875 -584.399963
876 598
877 -432.399963
878 497.599976
879 -440.8
880 410.200073
881 -513.399963
882 389.400024
883 -519
884 324
885 -554.8
886 273.800049
887 -529.8
888 255.400024
889 -615
890 219.599976
891 -537.399963
892 194.599976
893 -464
894 517.4
895 -380.199951
896 498.400024
897 -469.199951
898 425.400024
899 -394.199951
900 467.200073
901 -453.399963
902 522.6
903 -383.8
904 557
905 -365.399963
906 526.6
907 -342.8
908 544.4
909 -367.8
910 534.4
911 -429
912 565
913 -383.599976
914 483.599976
915 -371.199951
916 562
917 -374.199951
918 521
919 -517.8
920 425.200073
921 -469.599976
922 492.800049
923 -467.399963
924 409.200073
925 -455.199951
926 384.800049
927 -481.199951
928 408.200073
929 -449.8
930 503
931 -429.599976
932 540.2001
933 -432.8
934 476.800049
935 -420
936 428.599976
937 -547.399963
938 124.200073
939 -620.399963
940 130.599976
941 -583.8
942 113.400024
943 -617.399963
944 141
945 -606.399963
946 107
947 -640
948 98.4000244
949 -604.8
950 120.400024
951 -585
952 260.800049
953 -503
954 261.800049
955 -537
956 248.800049
957 -536.199951
958 211.800049
959 -500.8
960 255.400024
961 -501.399963
962 238.599976
963 -529
964 254.800049
965 -506.599976
966 226.400024
967 -476.599976
968 224.200073
969 -504.399963
970 141
971 -608.199951
972 146.800049
973 -600.399963
974 161
975 -579.399963
976 274
977 -519.6
978 297.400024
979 -542.8
980 256
981 -520.8
982 280.599976
983 -544.8
984 284.200073
985 -522
986 277.599976
987 -492.199951
988 277
989 -511.599976
990 246.599976
991 -537.399963
992 301.800049
993 -474.8
994 268.599976
995 -503
996 253.200073
997 -506.8
998 265.599976
999 -495.399963
1000    234.599976
1001    -519.399963
1002    246.200073
1003    -489
1004    306
1005    -533.6
1006    296
1007    -502.199951
1008    293.800049
1009    -494.199951
1010    304
1011    -461.199951
1012    279.200073
1013    -526.199951
1014    279.200073
1015    -473.8
1016    293.599976
1017    -460
1018    307.400024
1019    -520.6
1020    337.200073
1021    -503.599976
1022    284
1023    -516.8
1024    326.400024
1025    -479.8
1026    337.200073
1027    -503
1028    329.800049
1029    -467.599976
1030    322.800049
1031    -499.8
1032    351
1033    -490.199951
1034    354
1035    -474
1036    343.800049
1037    -472.8
1038    356.400024
1039    -457.8
1040    364
1041    -465.599976
1042    434
1043    -438.399963
1044    418.800049
1045    -412
1046    412.400024
1047    -455.399963
1048    452.200073
1049    -457.8
1050    394.200073
1051    -427
1052    422.599976
1053    -333.8
1054    561
1055    -351.199951
1056    503
1057    -470.199951
1058    508
1059    -448.599976
1060    484.800049
1061    -392.199951
1062    499.200073
1063    -424.599976
1064    473
1065    -417.599976
1066    518.800049
1067    -389.199951
1068    539.6
1069    -420.399963
1070    475.599976
1071    -385
1072    515.2001
1073    -388.199951
1074    521.4
1075    -414.599976
1076    462.800049
1077    -398.199951
1078    468.400024
1079    -468.599976
1080    427.400024
1081    -481.199951
1082    284.400024
1083    -608.199951
1084    175
1085    -627.8
1086    135
1087    -659.199951
1088    136.400024
1089    -623.199951
1090    143.599976
1091    -600
1092    147.800049
1093    -599.6
1094    113
1095    -614.8
1096    141.599976
1097    -642.6
1098    157.400024
1099    -611.399963
1100    147.200073
1101    -610.199951
1102    164.200073
1103    -637.8
1104    146.800049
1105    -581.8
1106    125.800049
1107    -629.6
1108    167
1109    -569
1110    94.20007
1111    -604.6
1112    142.400024
1113    -602.199951
1114    116
1115    -606.8
1116    142.400024
1117    -580
1118    117.200073
1119    -596.399963
1120    145.599976
1121    -620.6
1122    110.599976
1123    -625.8
1124    89.80005
1125    -619
1126    139
1127    -583.199951
1128    146.800049
1129    -593
1130    140.599976
1131    -597.6
1132    148
1133    -650
1134    118.800049
1135    -596.199951
1136    352.400024
1137    -444.199951
1138    381.400024
1139    -492.8
1140    334.400024
1141    -497.399963
1142    347
1143    -484.399963
1144    330.400024
1145    -483.599976
1146    357.599976
1147    -523.199951
1148    315.200073
1149    -503.399963
1150    345.800049
1151    -487.199951
1152    355.400024
1153    -456.599976
1154    370
1155    -497.199951
1156    379.800049
1157    -458.399963
1158    409.400024
1159    -503.599976
1160    320.400024
1161    -459
1162    397.200073
1163    -486.599976
1164    354.599976
1165    -439.8
1166    418.200073
1167    -454.199951
1168    334.599976
1169    -436
1170    341.400024
1171    -469.599976
1172    406.200073
1173    -489.8
1174    384.200073
1175    -479.199951
1176    373.400024
1177    -446
1178    401.800049
1179    -455.599976
1180    344
1181    -471.599976
1182    386.400024
1183    -465.8
1184    363.400024
1185    -480
1186    410.599976
1187    -462.199951
1188    450
1189    -452.8
1190    351.800049
1191    -484.8
1192    393.400024
1193    -439.399963
1194    397
1195    -471.8
1196    426.599976
1197    -381.199951
1198    418.400024
1199    -418
1200    426.800049
1201    -447
1202    366.800049
1203    -431.8
1204    443.400024
1205    -460.8
1206    440.400024
1207    -416.199951
1208    409.599976
1209    -397.199951
1210    427.400024
1211    -394.599976
1212    495.599976
1213    -408.8
1214    470.400024
1215    -421.8
1216    517.800049
1217    -442.399963
1218    527.2001
1219    -399.199951
1220    544.2001
1221    -354
1222    535.4
1223    -358.399963
1224    527.6
1225    -374
1226    599
1227    -392
1228    590.4
1229    -327.8
1230    602.6
1231    -353.199951
1232    650.2001
1233    -369.599976
1234    642
1235    -359
1236    725.800049
1237    -296.599976
1238    734.4
1239    -223.199951
1240    766.4
1241    -287.8
1242    752.2001
1243    -277.199951
1244    828.4
1245    -233.199951
1246    809
1247    -198
1248    773
1249    -228.799988
1250    803.800049
1251    -278
1252    767
1253    -238
1254    859.800049
1255    -238.399963
1256    740.4
1257    -269.599976
1258    742.6
1259    -297.199951
1260    714.800049
1261    -344
1262    616.2001
1263    -342.8
1264    654.2001
1265    -365.199951
1266    660.4
1267    -372.199951
1268    669.2001
1269    -299.599976
1270    667.2001
1271    -345
1272    637
1273    -357.8
1274    646.800049
1275    -381.399963
1276    652.800049
1277    -378.199951
1278    622.4
1279    -347.199951
1280    647.6
1281    -361.599976
1282    646.800049
1283    -371.399963
1284    601.4
1285    -360.199951
1286    630.4
1287    -289.599976
1288    619
1289    -304.199951
1290    672
1291    -368
1292    591.4
1293    -375.399963
1294    590.4
1295    -442
1296    578
1297    -424.199951
1298    626.800049
1299    -384.8
1300    616.6

Body:
Three-ish problems.

(1) Compare the following two:

df[['Y']].as_matrix().shape # (801, 1), yours
df['Y'].as_matrix().shape   # (801,), better

np.fft.fft says if axis is not provided, the last axis is used. In your code, the FFT of an 801 by 1 array is evaluated along the last dimension, i.e., a 1-point FFT—totally not what you wanted.

Solution: remove one pair of brackets.

(2) With this in place, the output of np.fft.fft is complex, as expected. Instead of taking its real-only component, use it’s absolute value.

(3) Furthermore, it appears that Pandas plot has some problems plotting the output of np.fft.fftfreq because its output goes from [0 ... 0.5 -0.5 ... 0]. Simple solution: use np.fft.fftshift.

Solutions to #2–3:

df['spectrum'] = np.abs(np.fft.fftshift(np.fft.fft(df['Y'])))
df['freq'] = np.fft.fftshift(np.fft.fftfreq(len(df.index), 1))

(Alternative solution to #3: use np.fft.rfft and rfftfreq, since your input data is real.)

Final code:

import pandas as pd
import numpy as np

df = pd.read_csv('dat.csv', sep=',')
df.plot(x='X', y='Y')

df['spectrum'] = np.abs(np.fft.fftshift(np.fft.fft(df['Y'])))
df['freq'] = np.fft.fftshift(np.fft.fftfreq(len(df.index), 1))
df.plot(x='freq', y='spectrum')

Result:

Suggestion: better than np.abs is to use db (decibels). I.e., db = lambda x: 20 * np.log10(np.abs(x)). Alternatively, if that’s not your thing, just plot the y-axis on a log-scale.

Observation: you should be able to remove the high-frequency noisy by low-pass filtering the data, with a cutoff frequency of 0.25 normalized Hz. (Let me know if you have trouble with that.) If I collected this kind of data, I’d worry that my anti-aliasing filter before the ADC wasn’t working—one shouldn’t ever see so much noise right at the Nyquist frequency. If you are getting a lot of aliasing, who knows what the original signal is.


来源: stackexchange

问:
`CI` return wrong value
I have no idea why my CI return wrong value from phpMyAdmin
Model :

```<code>    <?php

class Post extends CI_Model
{
function __construct()
{
    parent::__construct();

}
function getallpost()
{
    return $this->db->get('post');

}

}
?>
</code>```

And

Controller :

```<code>    <?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Postc extends CI_Controller {
    function index()
    {
    $this->load->model('post');
    $posts=$this->post->getallpost();
    echo '```';
    print_r($posts);

    }
}
?>
```

enter image description here

答:
You code is not giving you any error, it is doing exactly what you are asking it to do. Perhaps you need to be specific about the information you want to get. You see in your model

```<code>function getallpost()
{
 return $this->db->get('post');
}
</code>```

The above function will return you an object. If you want to get an array you need to write

```<code>return $this->db->get('post')->result_array();
</code>```

And make sure you have some data in your post table to print For learning more about query database you should read Codeigniter's Query Builder Class

ContentLicense: CC BY-SA 3.0

Title: `CI` return wrong value

Body:
I have no idea why my CI return wrong value from phpMyAdmin
Model :

    <?php

class Post extends CI_Model
{
function __construct()
{
    parent::__construct();

}
function getallpost()
{
    return $this->db->get('post');

}

}
?>

And

Controller :

    <?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Postc extends CI_Controller {
    function index()
    {
    $this->load->model('post');
    $posts=$this->post->getallpost();
    echo '
';
    print_r($posts);

    }
}
?>

enter image description here

Body:
You code is not giving you any error, it is doing exactly what you are asking it to do. Perhaps you need to be specific about the information you want to get. You see in your model

function getallpost()
{
 return $this->db->get('post');
}

The above function will return you an object. If you want to get an array you need to write

return $this->db->get('post')->result_array();

And make sure you have some data in your post table to print For learning more about query database you should read Codeigniter's Query Builder Class


问:
How can i hide the status bar in the browser?
I have a simple question, how can I hide a link in the status bar in my browser.

I've tried with this:

```<code><a href="http://www.sell.com/?referrer=225"
   onMouseOver="window.status='http://www.sell.com';
               return true" onMouseOut="window.status=''">Click here</a>
</code>```

(Taken from a tutorial)
But it doesn't work, if somebody would help me, I would be very happy! ;-)

答:
Since you are asking to do this in order to hide affiliation links, there may be a better way.

It makes far more sense to loop through all your links, say, under a broad $("a.out") selector, then get and store their real href into element storage, replace it with a dummy one (and the title attribute if you have to).

You then attach a click event handler that stops the default event, reads back the original href and sets it as the location.href, effectively disguising the links to all that have js enabled.

Eg code in mootools:

```<code>(function() {
    var links = document.getElements("a.out");

    links.each(function(el) {
        // save original
        el.store("href", el.get("href"));
        // replace it.
        el.set("href", el.get("data-link"));

        el.addEvents({
            click: function(e) {
                e.stop();
                // console.log(e);

                document.location.href = this.retrieve("href");
            },
            contextmenu: function(e) {
                e.stop();
                // do something on right click so we dont get caught
                alert("hi");
            }
        });
    });
})();
</code>```

Which works fine on this markup:

```<code><a href="http://www.energyhelpline.com/energy/rg_home.aspx?aid=107" rel="nofollow" class="out" title="Enegry savings" data-link="http://www.energyhelpline.com/">Swap Energy Provider</a><br />

<a href="http://www.moneysupermarket.com/link.asp?Source=MSE&Section=utils" rel="nofollow" class="out" title="Money supermarket" data-link="http://www.moneysupermarket.com/">Money Supermarket</a>
</code>```

With data-link containing what we SHOW to end users instead.

Body:
I have a simple question, how can I hide a link in the status bar in my browser.

I've tried with this:

Click here

(Taken from a tutorial)
But it doesn't work, if somebody would help me, I would be very happy! ;-)

Body:
Since you are asking to do this in order to hide affiliation links, there may be a better way.

It makes far more sense to loop through all your links, say, under a broad $("a.out") selector, then get and store their real href into element storage, replace it with a dummy one (and the title attribute if you have to).

You then attach a click event handler that stops the default event, reads back the original href and sets it as the location.href, effectively disguising the links to all that have js enabled.

Eg code in mootools:

(function() {
    var links = document.getElements("a.out");

    links.each(function(el) {
        // save original
        el.store("href", el.get("href"));
        // replace it.
        el.set("href", el.get("data-link"));

        el.addEvents({
            click: function(e) {
                e.stop();
                // console.log(e);

                document.location.href = this.retrieve("href");
            },
            contextmenu: function(e) {
                e.stop();
                // do something on right click so we dont get caught
                alert("hi");
            }
        });
    });
})();

Which works fine on this markup:

<a href="http://www.energyhelpline.com/energy/rg_home.aspx?aid=107" rel="nofollow" class="out" title="Enegry savings" data-link="http://www.energyhelpline.com/">Swap Energy Provider</a><br />

<a href="http://www.moneysupermarket.com/link.asp?Source=MSE&Section=utils" rel="nofollow" class="out" title="Money supermarket" data-link="http://www.moneysupermarket.com/">Money Supermarket</a>

With data-link containing what we SHOW to end users instead.

ContentLicense: CC BY-SA 4.0


问:
How to modify service url paramer in angularjs
I'm trying to modify the city parameter by searching for a city parameter, but I don't think it's possible to modify an angular service that way. So how would I be able to modify the service parameter in the controller? Any help would be amazing!

HTML:

```<code><section ng-controller="MainController">

    <form action="" class="form-inline well well-sm clearfix" >
  <span class="glyphicon glyphicon-search"></span>
  <input type="text" placeholder="Search..." class="form-control" ng-model="city" />
  <button class="btn btn-warning pull-right" ng-click="search()"><strong>Search</strong></button>
</form>
    <h1>{{fiveDay.city.name}}</h1>
    <div ng-repeat="day in fiveDay.list" class="forecast">
        <div class="day">
            <div class="weekday">
                <p>{{ day.dt*1000 | date}}</p>
                <!-- <p>{{ parseJsonDate(day.dt)}}</p> -->
            </div>
            <div class="weather"><img ng-src="http://openweathermap.org/img/w/{{day.weather[0].icon}}.png"/></div>
            <div class="temp">{{day.weather[0].description}}</div>
            <div class="temp">Max {{ day.main.temp_max }}°</div>
            <div class="temp">Min {{ day.main.temp_min }}°</div>
        </div>
    </div>
</section>
</code>```

JS:

```<code>var app = angular.module('App', []);
app.controller('MainController', ['$scope', 'forecast', function($scope,    forecast) {
forecast.city="orlando";
  forecast.success(function(data) {
        $scope.fiveDay = data;
     });
  }]);
app.factory('forecast', ['$http', function($http) {
var city = "orlando";
var key="a1f2d85f6babd3bf7afd83350bc5f2a6";
  return $http.get('http://api.openweathermap.org/data/2.5/forecast?q='+city+'&APPID='+key+'&units=metric&cnt=5')
    .success(function(data) {
      return data;
    })
    .error(function(err) {
      return err;
    });
}]);
</code>```

答:
City is a variable part in your forecast factory so need to pass it as an argument in function will be the recommended for you

Try this

```<code>var app = angular.module('App', []);
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) {
    var city = "orlando";
    forecast.getWeatner(city).success(function(data) {
        $scope.fiveDay = data;
    });
}]);
app.factory('forecast', ['$http', function($http) {
    var key = "a1f2d85f6babd3bf7afd83350bc5f2a6";
    return {
        getWeatner: function(city) {
            return $http.get('http://api.openweathermap.org/data/2.5/forecast?q=' + city + '&APPID=' + key + '&units=metric&cnt=5');
        }
    }
}]);
</code>```

Body:
I'm trying to modify the city parameter by searching for a city parameter, but I don't think it's possible to modify an angular service that way. So how would I be able to modify the service parameter in the controller? Any help would be amazing!

HTML:

    <form action="" class="form-inline well well-sm clearfix" >

  <input type="text" placeholder="Search..." class="form-control" ng-model="city" />
  <button class="btn btn-warning pull-right" ng-click="search()">Search</button>
</form>

{{fiveDay.city.name}}

{{ day.dt*1000 | date}}

{{day.weather[0].description}}

Max {{ day.main.temp_max }}°

Min {{ day.main.temp_min }}°

JS:

var app = angular.module('App', []);
app.controller('MainController', ['$scope', 'forecast', function($scope,    forecast) {
forecast.city="orlando";
  forecast.success(function(data) {
        $scope.fiveDay = data;
     });
  }]);
app.factory('forecast', ['$http', function($http) {
var city = "orlando";
var key="a1f2d85f6babd3bf7afd83350bc5f2a6";
  return $http.get('http://api.openweathermap.org/data/2.5/forecast?q='+city+'&APPID='+key+'&units=metric&cnt=5')
    .success(function(data) {
      return data;
    })
    .error(function(err) {
      return err;
    });
}]);

Body:
City is a variable part in your forecast factory so need to pass it as an argument in function will be the recommended for you

Try this

var app = angular.module('App', []);
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) {
    var city = "orlando";
    forecast.getWeatner(city).success(function(data) {
        $scope.fiveDay = data;
    });
}]);
app.factory('forecast', ['$http', function($http) {
    var key = "a1f2d85f6babd3bf7afd83350bc5f2a6";
    return {
        getWeatner: function(city) {
            return $http.get('http://api.openweathermap.org/data/2.5/forecast?q=' + city + '&APPID=' + key + '&units=metric&cnt=5');
        }
    }
}]);


问:
How does int(x[,base]) work?
The output for the following code is:

```<code>int("12", 5)
O/P: 7

int("0", 5)
O/P: 0

int("10", 2)
O/P: 2
</code>```

I cannot make sense of this. From the Python documentation it says: The "[, base]" part is optional i.e it might take one or two arguments.

The first argument should necessarily be a string which has an int value within the quotes.

答:
This fact can be explained as follows:

Suppose our function call is int("12",5), which means (12) is in base 5 and we are requesting for it to be converted into decimal no. i.e., into a base 10 number.

So, the simple rule is

```<code>(12)base 5 = 1*(5 ^ 1) + 2*(5 ^ 0)
           = 5 + 2
           = 7
</code>```

Similar conversions can be done from any other base.

Title: How does int(x[,base]) work?

Body:
The output for the following code is:

int("12", 5)
O/P: 7

int("0", 5)
O/P: 0

int("10", 2)
O/P: 2

I cannot make sense of this. From the Python documentation it says: The "[, base]" part is optional i.e it might take one or two arguments.

The first argument should necessarily be a string which has an int value within the quotes.

Body:
This fact can be explained as follows:

Suppose our function call is int("12",5), which means (12) is in base 5 and we are requesting for it to be converted into decimal no. i.e., into a base 10 number.

So, the simple rule is

(12)base 5 = 1*(5 ^ 1) + 2*(5 ^ 0)
           = 5 + 2
           = 7

Similar conversions can be done from any other base.


问:
Adding regex to detect a word that repeats 3 characters?
I have searched and searched but I cannot find anything quite exactly like what I need. I have a code:

```<code>$repeater = "pompom";

    if (preg_match('/([a-zA-Z])\1{3}/', $repeater)) {
    echo "Yes, $repeater does repeat 3 characters.<br>";
}
else {
    echo "No, $repeater does not repeat 3 characters.<br>";
}
</code>```

(I can barely understand regex as it is... so just ignore my current regex.. it's just a mixture of randomness I began to type.)

Anyhow, I need the regex code to return

true for words like

pompom

grugru

mopmop

cancan

etc...

and return false for words like

coocoo

daadaa

allall

giigii

etc.

The regex must detect and return true for any word that has 3 different characters that repeat more than once in that word.

This must work for words that have characters that are not necessarily in sequence with one another. I have found solutions to that. Words such as "cooo" or "pooool" is not what I need to apply this regex for. Note: This must return True only for words that have 3 or more different letters in the word and are repeated more than once. Such as, pompom..

This should return false for words like coocoo because there are only 2 different letters in the word.

Again, please ignore my current regex it was just what I had when I decided to ask for some help. I've tried probably 200 different methods, all wrong of course :].

Any help would be nice, maybe we can figure this out together I just need some ideas to bounce off of.

答:
The following regex will perform as requested:

```<code>^((.)(?!\2)(.)(?!\2)(?!\3).)\1$
</code>```

https://regex101.com/r/eHKzWB/3

Body:
I have searched and searched but I cannot find anything quite exactly like what I need. I have a code:

$repeater = "pompom";

    if (preg_match('/([a-zA-Z])\1{3}/', $repeater)) {
    echo "Yes, $repeater does repeat 3 characters.
";
}
else {
    echo "No, $repeater does not repeat 3 characters.
";
}

(I can barely understand regex as it is... so just ignore my current regex.. it's just a mixture of randomness I began to type.)

Anyhow, I need the regex code to return

true for words like

pompom

grugru

mopmop

cancan

etc...

and return false for words like

coocoo

daadaa

allall

giigii

etc.

The regex must detect and return true for any word that has 3 different characters that repeat more than once in that word.

This must work for words that have characters that are not necessarily in sequence with one another. I have found solutions to that. Words such as "cooo" or "pooool" is not what I need to apply this regex for. Note: This must return True only for words that have 3 or more different letters in the word and are repeated more than once. Such as, pompom..

This should return false for words like coocoo because there are only 2 different letters in the word.

Again, please ignore my current regex it was just what I had when I decided to ask for some help. I've tried probably 200 different methods, all wrong of course :].

Any help would be nice, maybe we can figure this out together I just need some ideas to bounce off of.

Body:
The following regex will perform as requested:

^((.)(?!\2)(.)(?!\2)(?!\3).)\1$

https://regex101.com/r/eHKzWB/3


问:
How to stay on same page after click "submit" button, and keep the date I entered in JavaScript

After clicking "submit", stay on this page.

Input data, like "computer number" and "profit", stay inside those blank square.

A word "Submitted", appear in the center of this page.

The following is my code,
Please help, thank you!

<title></title>

  <form name="my form"
onsubmit="return validateForm()">

    Computer Number:

    <input type="text" name="Computer" required>

How much is your profit?

<input id="id1" name = "id1" required>
  <button  type = "button" onclick="myFunction()">Check My Answer</button>
    <button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>

  <input type="submit" value="Submit">

</form>

```

答:
In validateForm() I have added else logic which is used for displaying the submitted message and stops the form from being redirected.

Things to do.

Add logic according to your requirement how to submit the form through XMLHttpRequest way. For more see  Sending forms through JavaScript

  <title></title>

  <form name="my form" onsubmit="return validateForm()">

    Computer Number:

    <input type="text" name="Computer" required>

How much is your profit?

      <input id="id1" name="id1" required>
      <button type="button" onclick="myFunction()">Check My Answer</button>
      <button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>

    <input type="submit" value="Submit">

  </form>

```

Body:
In validateForm() I have added else logic which is used for displaying the submitted message and stops the form from being redirected.

Things to do.

Add logic according to your requirement how to submit the form through XMLHttpRequest way. For more see  Sending forms through JavaScript

<html>

<head>
  <title></title>
</head>

<body>

  <form name="my form" onsubmit="return validateForm()">

    Computer Number:<br>
    <input type="text" name="Computer" required><br>

    <p>How much is your profit?

      <input id="id1" name="id1" required>
      <button type="button" onclick="myFunction()">Check My Answer</button>
      <button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
    </p>

    <p id="Q1"></p>

    <script>
      var errosCount = 0;

      function myFunction() {
        var x, text;
        x = document.getElementById("id1").value;

        if (isNaN(x) || x != 100) {
          text = "Incorrect";
          document.getElementById("Q1").style.color = "red";
          errosCount++;
        } else {
          text = "Correct";
          document.getElementById("Q1").style.color = "green";
        }
        document.getElementById("Q1").innerHTML = text;
        if (errosCount === 3) {
          errosCount = 0;
          document.getElementById('btn1').style.display = 'block';
          document.getElementById("Q1").innerHTML = '';
        } else {
          document.getElementById('btn1').style.display = 'none';
        }
      }

      function Solution() {
        text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100";
        document.getElementById("Q1").style.color = "red";
        document.getElementById("Q1").innerHTML = text;
      }
    </script>

    <input type="submit" value="Submit">
    <span id="success"></span>

  </form>

  <script>
    function validateForm() {
      var q = document.forms["my form"]["Computer"].value;
      if (q == "") {
        alert("Computer Number is Missing!");
        return false;
      }
      var w = document.forms["my form"]["id1"].value;
      if (w != "100") {
        alert("Question 1 is Incorrect!");
        return false;
      } else {
        /* ajax logic here and on success message this message is followed*/
        document.getElementById('success').innerHTML = "<b>Submitted</b>"
        return false; /*stops the form from being submitted normal way*/
      }

    }
  </script>

</body>

</html>


问:
How does one install the kube-dns addon for minikube?
Can someone please detail the steps necessary to install the kube-dns addon?  I've downloaded the nearly 400MB git repo in the previous link and run make as instructed but get Nothing to be done for 'all'.

The docs aren't clear what form add-ons exist in, and how to install them.  The "Administrators guide" link there takes me to this unhelpful page.

I've tried https://stackoverflow.com/a/42315074/4978821, but got an error validating data message.  Even if this worked, it seems like it'd be an unofficial and awkward solution.

Answers like this are also too vague:  https://stackoverflow.com/a/36105547/4978821.

I'd be happy to create a pull request to improve the documentation, once I have a solution.

Updated to clarify my issue:

As mentioned by Aaron, the dns addon is enabled in minikube by default.  Running minikube addons list shows that it is enabled.  However, if I get into a bash shell for a running pod, like such kubectl exec -it node-controller-poqsl bash and try to reach my mongo service using ping, for example, it resolves to a public URL, rather than the kubernetes service IP.

答:
The kube-dns addon should be enabled by default in minikube.  You can run kubectl get po -n kube-system to check if the pod the addon-manager launches is there.  If you don't see the pod listed, make sure that the addon is enabled in minikube by running minikube addons list and verifying that kube-dns is enabled

Edit:
For me kubectl get po -n kube-system is a valid command, here is the output:

```<code>$ kubectl get po -n kube-system
NAME                          READY     STATUS    RESTARTS   AGE
kube-addon-manager-minikube   1/1       Running   2          5d
kube-dns-v20-7ddvt            3/3       Running   6          5d
kubernetes-dashboard-rn54g    1/1       Running   2          5d
</code>```

You can see from this that the kube-dns pods are running correctly.  Can you verify that your kube-dns pods are in the Running state?

Body:
The kube-dns addon should be enabled by default in minikube.  You can run kubectl get po -n kube-system to check if the pod the addon-manager launches is there.  If you don't see the pod listed, make sure that the addon is enabled in minikube by running minikube addons list and verifying that kube-dns is enabled

Edit:
For me kubectl get po -n kube-system is a valid command, here is the output:

$ kubectl get po -n kube-system
NAME                          READY     STATUS    RESTARTS   AGE
kube-addon-manager-minikube   1/1       Running   2          5d
kube-dns-v20-7ddvt            3/3       Running   6          5d
kubernetes-dashboard-rn54g    1/1       Running   2          5d

You can see from this that the kube-dns pods are running correctly.  Can you verify that your kube-dns pods are in the Running state?


问:
Increment and bitwise shift operator precedence?
Increment suffix and prefix are both of higher operator precedence than bitwise left shift, but the following prints out different results.

```<code>int testValue = 1;
std::cout << ++testValue; //prints 2
//saw it as std::cout << (++testValue);

testValue = 1;
std::cout << testValue++; //prints 1
//thought it was std::cout << (testValue++);
</code>```

Why does increment suffix as shown in the second example print 1 before incrmenting? I thought it was bound more tightly to testValue like in the increment prefix case, so I thought it'd be incremented first before being printed with std::cout.

答:
You misunderstand what testValue++ does.

It increments testValue but its evaluation is before the increment is made.

The line

```<code>std::cout << testValue++;
</code>```

is equivalent to

```<code>std::cout << testValue;
testValue = testValue + 1;
</code>```

Body:
Increment suffix and prefix are both of higher operator precedence than bitwise left shift, but the following prints out different results.

int testValue = 1;
std::cout << ++testValue; //prints 2
//saw it as std::cout << (++testValue);

testValue = 1;
std::cout << testValue++; //prints 1
//thought it was std::cout << (testValue++);

Why does increment suffix as shown in the second example print 1 before incrmenting? I thought it was bound more tightly to testValue like in the increment prefix case, so I thought it'd be incremented first before being printed with std::cout.

Body:
You misunderstand what testValue++ does.

It increments testValue but its evaluation is before the increment is made.

The line

std::cout << testValue++;

is equivalent to

std::cout << testValue;
testValue = testValue + 1;


问:
apache2 won't start cause ssl : "Failed to configure encrypted (?) private key"
I just created a ssl certificate shown here : http://www.tecchannel.de/a/owncloud-9-unter-ubuntu-server-16-04-lts-installieren,3277807,2

now if I start apache I get no error but with service apache2 status I get a error , error log :

```<code>[Fri Mar 31 14:55:59.639400 2017] [ssl:error] [pid 21071] AH02579: Init: Private key not found
[Fri Mar 31 14:55:59.639479 2017] [ssl:error] [pid 21071] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Fri Mar 31 14:55:59.639494 2017] [ssl:error] [pid 21071] SSL Library Error: error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error
[Fri Mar 31 14:55:59.639504 2017] [ssl:error] [pid 21071] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Fri Mar 31 14:55:59.639515 2017] [ssl:error] [pid 21071] SSL Library Error: error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error (Type=RSA)
[Fri Mar 31 14:55:59.639526 2017] [ssl:error] [pid 21071] SSL Library Error: error:04093004:rsa routines:OLD_RSA_PRIV_DECODE:RSA lib
[Fri Mar 31 14:55:59.639536 2017] [ssl:error] [pid 21071] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Fri Mar 31 14:55:59.639547 2017] [ssl:error] [pid 21071] SSL Library Error: error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error (Type=PKCS8_PRIV_KEY_INFO)
[Fri Mar 31 14:55:59.639553 2017] [ssl:emerg] [pid 21071] AH02311: Fatal error initialising mod_ssl, exiting. See /var/log/apache2/error.log for more information
[Fri Mar 31 14:55:59.639558 2017] [ssl:emerg] [pid 21071] AH02564: Failed to configure encrypted (?) private key localhost:443:0, check /etc/apache2/ssl/apache.crt
AH00016: Configuration Failed
</code>```

but whats wrong ? the file in /etc/apache2/ssl/apache.crt exists of course ... and why "Private key not found" ? apache.key exists too.

any help ? :(

答:
I think you should recheck your configuration steps.. After creating the .key file you have to give proper permission so that it should readable and writable by root.

Follow the below link which may solve your problem.

https://www.howtoforge.com/how-to-set-up-an-ssl-vhost-under-apache2-on-ubuntu-9.10-debian-lenny

Body:
I just created a ssl certificate shown here : http://www.tecchannel.de/a/owncloud-9-unter-ubuntu-server-16-04-lts-installieren,3277807,2

now if I start apache I get no error but with service apache2 status I get a error , error log :

[Fri Mar 31 14:55:59.639400 2017] [ssl:error] [pid 21071] AH02579: Init: Private key not found
[Fri Mar 31 14:55:59.639479 2017] [ssl:error] [pid 21071] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Fri Mar 31 14:55:59.639494 2017] [ssl:error] [pid 21071] SSL Library Error: error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error
[Fri Mar 31 14:55:59.639504 2017] [ssl:error] [pid 21071] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Fri Mar 31 14:55:59.639515 2017] [ssl:error] [pid 21071] SSL Library Error: error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error (Type=RSA)
[Fri Mar 31 14:55:59.639526 2017] [ssl:error] [pid 21071] SSL Library Error: error:04093004:rsa routines:OLD_RSA_PRIV_DECODE:RSA lib
[Fri Mar 31 14:55:59.639536 2017] [ssl:error] [pid 21071] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Fri Mar 31 14:55:59.639547 2017] [ssl:error] [pid 21071] SSL Library Error: error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error (Type=PKCS8_PRIV_KEY_INFO)
[Fri Mar 31 14:55:59.639553 2017] [ssl:emerg] [pid 21071] AH02311: Fatal error initialising mod_ssl, exiting. See /var/log/apache2/error.log for more information
[Fri Mar 31 14:55:59.639558 2017] [ssl:emerg] [pid 21071] AH02564: Failed to configure encrypted (?) private key localhost:443:0, check /etc/apache2/ssl/apache.crt
AH00016: Configuration Failed

but whats wrong ? the file in /etc/apache2/ssl/apache.crt exists of course ... and why "Private key not found" ? apache.key exists too.

any help ? :(


问:
filtering data frame based on column (item_id) value which have all digits?
following is a sample data frame in R -

```<code>date                  item_id           price
2010-09-15            0034              4546
2010-09-15            ABXC              4325
2010-09-15            12AB              3545
2010-09-15            ZF9C              4354
2010-09-15            Z923              7854
2010-09-15            923F              780
</code>```

desired output-

```<code>date                  item_id           price
2010-09-15            ABXC              4325
2010-09-15            12AB              3545
2010-09-15            ZF9C              4354
2010-09-15            Z923              7854
2010-09-15            923F              780
</code>```

i tried so far -

```<code>outlier_seq<-c('0','1','2','3','4','5','6','7','8','9')
df1<-sample_df[!grepl(paste(outlier_seq, collapse = "|"), sample$item_id),]
</code>```

but this is removing all the item_id consists number. instead of that just I want to filter out those records, whose item_id consist of all number. any help on this?

thanks

答:
Or we can use tidyverse, by matching patterns that start (^) with one or more non-numeric ([^0-9]+) character with str_detect to return a logical vector to filter the rows

```<code>library(dplyr)
library(stringr)
mydf %>%
    filter(str_detect(item_id, "^[^0-9]+"))
#        date item_id price
#1 2010-09-15    ABXC  4325
#2 2010-09-15    ZF9C  4354
#3 2010-09-15  ZF9C23  7854
</code>```

Update

For the updated question in OP's post, we can look for pattern that have one or more numbers ([0-9]+) from start (^) to end ($) of string, negate (!) the logical vector to reverse the TRUE/FALSE to FALSE/TRUE and filter

```<code>mydf %>%
       filter(!str_detect(item_id, "^[0-9]+$"))
#        date item_id price
#1 2010-09-15    ABXC  4325
#2 2010-09-15    12AB  3545
#3 2010-09-15    ZF9C  4354
#4 2010-09-15  ZF9C23  7854
</code>```

Update2

Based on OP's concern that it is filtering out "07R2", tested it by adding another row with that value

```<code>mydf %>%
     filter(!str_detect(item_id, "^[0-9]+$"))
 #        date item_id price
 #1 2010-09-15    ABXC  4325
 #2 2010-09-15    12AB  3545
 #3 2010-09-15    ZF9C  4354
 #4 2010-09-15  ZF9C23  7854
 #5 2010-09-15    07R2  7934
</code>```

Update3

Based on the new dataset by OP

```<code>mydf %>%
     filter(!str_detect(item_id, "^[0-9]+$"))
#        date item_id price
#1 2010-09-15    ABXC  4325
#2 2010-09-15    12AB  3545
#3 2010-09-15    ZF9C  4354
#4 2010-09-15    Z923  7854
#5 2010-09-15    923F   780
</code>```

Even if the column is factor it works

```<code>mydf %>%
      filter(!str_detect(factor(item_id), "^[0-9]+$"))
#        date item_id price
#1 2010-09-15    ABXC  4325
#2 2010-09-15    12AB  3545
#3 2010-09-15    ZF9C  4354
#4 2010-09-15    Z923  7854
#5 2010-09-15    923F   780
</code>```

data

```<code>#data from last update
mydf <- structure(list(date = c("2010-09-15", "2010-09-15", "2010-09-15",
"2010-09-15", "2010-09-15", "2010-09-15"), item_id = c("0034",
"ABXC", "12AB", "ZF9C", "Z923", "923F"), price = c(4546L, 4325L,
3545L, 4354L, 7854L, 780L)), .Names = c("date", "item_id", "price"
 ), class = "data.frame", row.names = c(NA, -6L))
</code>```

Body:
following is a sample data frame in R -

date                  item_id           price
2010-09-15            0034              4546
2010-09-15            ABXC              4325
2010-09-15            12AB              3545
2010-09-15            ZF9C              4354
2010-09-15            Z923              7854
2010-09-15            923F              780

desired output-

date                  item_id           price
2010-09-15            ABXC              4325
2010-09-15            12AB              3545
2010-09-15            ZF9C              4354
2010-09-15            Z923              7854
2010-09-15            923F              780

i tried so far -

outlier_seq<-c('0','1','2','3','4','5','6','7','8','9')
df1<-sample_df[!grepl(paste(outlier_seq, collapse = "|"), sample$item_id),]

but this is removing all the item_id consists number. instead of that just I want to filter out those records, whose item_id consist of all number. any help on this?

thanks

Body:
Or we can use tidyverse, by matching patterns that start (^) with one or more non-numeric ([^0-9]+) character with str_detect to return a logical vector to filter the rows

library(dplyr)
library(stringr)
mydf %>%
    filter(str_detect(item_id, "^[^0-9]+"))
#        date item_id price
#1 2010-09-15    ABXC  4325
#2 2010-09-15    ZF9C  4354
#3 2010-09-15  ZF9C23  7854

Update

For the updated question in OP's post, we can look for pattern that have one or more numbers ([0-9]+) from start (^) to end ($) of string, negate (!) the logical vector to reverse the TRUE/FALSE to FALSE/TRUE and filter

mydf %>%
       filter(!str_detect(item_id, "^[0-9]+$"))
#        date item_id price
#1 2010-09-15    ABXC  4325
#2 2010-09-15    12AB  3545
#3 2010-09-15    ZF9C  4354
#4 2010-09-15  ZF9C23  7854

Update2

Based on OP's concern that it is filtering out "07R2", tested it by adding another row with that value

mydf %>%
     filter(!str_detect(item_id, "^[0-9]+$"))
 #        date item_id price
 #1 2010-09-15    ABXC  4325
 #2 2010-09-15    12AB  3545
 #3 2010-09-15    ZF9C  4354
 #4 2010-09-15  ZF9C23  7854
 #5 2010-09-15    07R2  7934

Update3

Based on the new dataset by OP

mydf %>%
     filter(!str_detect(item_id, "^[0-9]+$"))
#        date item_id price
#1 2010-09-15    ABXC  4325
#2 2010-09-15    12AB  3545
#3 2010-09-15    ZF9C  4354
#4 2010-09-15    Z923  7854
#5 2010-09-15    923F   780

Even if the column is factor it works

mydf %>%
      filter(!str_detect(factor(item_id), "^[0-9]+$"))
#        date item_id price
#1 2010-09-15    ABXC  4325
#2 2010-09-15    12AB  3545
#3 2010-09-15    ZF9C  4354
#4 2010-09-15    Z923  7854
#5 2010-09-15    923F   780

data

#data from last update
mydf <- structure(list(date = c("2010-09-15", "2010-09-15", "2010-09-15",
"2010-09-15", "2010-09-15", "2010-09-15"), item_id = c("0034",
"ABXC", "12AB", "ZF9C", "Z923", "923F"), price = c(4546L, 4325L,
3545L, 4354L, 7854L, 780L)), .Names = c("date", "item_id", "price"
 ), class = "data.frame", row.names = c(NA, -6L))


问:
How should I use IoC DI with this repository pattern?
I am using the repository pattern found in the answer to this SO question:

Advantage of creating a generic repository vs. specific repository for each object?

Namely, each repository inherits from an abstract base class that contains generic methods like add, delete, etc. and also implements a specific repository interface for any methods that are unique to that repository/entity.

ie.

```<code>public class CompanyRepository : Repository<Company>, ICompanyRepository {
...
}
</code>```

In my business layer I am using Structure Map to get an instance of the repository, but I am unsure how to use it.

```<code> // Structure Map initialisation
 ObjectFactory.Initialize(
 x =>
 {
      x.For<ICompanyRepository>().Use<CompanyRepository>();
 });
</code>```

resolving an instance:

```<code>return ObjectFactory.GetInstance<ICompanyRepository>();
</code>```

However the instance I get is an interface and not the whole repository implementation. I don't have access to the methods on the base class (Repository<Company>). What is the usual way to do this?

答:
The key here is to think of Repository<> solely as an implementation detail. You won't be accessing any methods on it directly; instead, you will expose all methods, including Insert and Delete, on the interface:

```<code>public interface ICustomerRepository
{
    // ...Customer-specific queries...

    void Insert(Customer customer);

    void Delete(Customer customer);
}
</code>```

When you implement the interface in CustomerRepository, you simply have to pass the Insert and Delete calls through to the protected methods of Repository<> as discussed in the original question.

The StructureMap registration you state in the question is exactly what I would expect. The purpose of Repository<> then is to aid in the implementation of entity-specific interfaces. Keep in mind that the interfaces will always contain the repository's full public API and that should point you in the right direction.

ContentLicense: CC BY-SA 2.5

Body:
I am using the repository pattern found in the answer to this SO question:

Advantage of creating a generic repository vs. specific repository for each object?

Namely, each repository inherits from an abstract base class that contains generic methods like add, delete, etc. and also implements a specific repository interface for any methods that are unique to that repository/entity.

ie.

public class CompanyRepository : Repository<Company>, ICompanyRepository {
...
}

In my business layer I am using Structure Map to get an instance of the repository, but I am unsure how to use it.

 // Structure Map initialisation
 ObjectFactory.Initialize(
 x =>
 {
      x.For<ICompanyRepository>().Use<CompanyRepository>();
 });

resolving an instance:

return ObjectFactory.GetInstance<ICompanyRepository>();

However the instance I get is an interface and not the whole repository implementation. I don't have access to the methods on the base class (Repository<Company>). What is the usual way to do this?

Body:
The key here is to think of Repository<> solely as an implementation detail. You won't be accessing any methods on it directly; instead, you will expose all methods, including Insert and Delete, on the interface:

public interface ICustomerRepository
{
    // ...Customer-specific queries...

    void Insert(Customer customer);

    void Delete(Customer customer);
}

When you implement the interface in CustomerRepository, you simply have to pass the Insert and Delete calls through to the protected methods of Repository<> as discussed in the original question.

The StructureMap registration you state in the question is exactly what I would expect. The purpose of Repository<> then is to aid in the implementation of entity-specific interfaces. Keep in mind that the interfaces will always contain the repository's full public API and that should point you in the right direction.


问:
Create Table Error: no primary or candidate keys in the referenced table that match the referencing column list in the foreign key
```<code>CREATE TABLE [Role]
(
     Role_Name nvarchar(20) NOT NULL,
     Bssn nvarchar(20) NOT NULL,

     CONSTRAINT Pk_Role_Role_Name
         PRIMARY KEY(Bssn, Role_Name),
     CONSTRAINT Fk_Role_Bssn
         FOREIGN KEY(Bssn) REFERENCES Bandmembers(Ssn)
             ON DELETE CASCADE ON UPDATE CASCADE
)

CREATE TABLE Has
(
    Role_Name nvarchar(20)NOT NULL,
    Bssn nvarchar(20) NOT NULL,

    CONSTRAINT Pk_Role_Id_Ssn_Id
        PRIMARY KEY(Bssn, Role_Name),
    CONSTRAINT Pk_Works_0N_Role_Name
        FOREIGN KEY(Bssn) REFERENCES Bandmembers(Ssn)
            ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT Pk_Works_On_Bssn
        FOREIGN KEY (Role_Name) REFERENCES role(Role_Name)
            ON DELETE CASCADE ON UPDATE CASCADE
)
</code>```

Error :

Msg 1776, Level 16, State 0, Line 1

  There are no primary or candidate keys in the referenced table 'Role' that match the referencing column list in the foreign key 'Pk_Works_On_Role'.

Msg 1750, Level 16, State 0, Line 1

  Could not create constraint. See previous errors.

答:
The table Has's foreign key is same with a references table's primary key.</p>

```<code>CONSTRAINT Pk_Works_On_Bssn FOREIGN KEY (Bssn, Role_Name) REFERENCES [Role](Bssn, Role_Name)ON DELETE CASCADE ON UPDATE CASCADE
</code>```

Body:
CREATE TABLE [Role]
(
     Role_Name nvarchar(20) NOT NULL,
     Bssn nvarchar(20) NOT NULL,

     CONSTRAINT Pk_Role_Role_Name
         PRIMARY KEY(Bssn, Role_Name),
     CONSTRAINT Fk_Role_Bssn
         FOREIGN KEY(Bssn) REFERENCES Bandmembers(Ssn)
             ON DELETE CASCADE ON UPDATE CASCADE
)

CREATE TABLE Has
(
    Role_Name nvarchar(20)NOT NULL,
    Bssn nvarchar(20) NOT NULL,

    CONSTRAINT Pk_Role_Id_Ssn_Id
        PRIMARY KEY(Bssn, Role_Name),
    CONSTRAINT Pk_Works_0N_Role_Name
        FOREIGN KEY(Bssn) REFERENCES Bandmembers(Ssn)
            ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT Pk_Works_On_Bssn
        FOREIGN KEY (Role_Name) REFERENCES role(Role_Name)
            ON DELETE CASCADE ON UPDATE CASCADE
)

Error :

Msg 1776, Level 16, State 0, Line 1

  There are no primary or candidate keys in the referenced table 'Role' that match the referencing column list in the foreign key 'Pk_Works_On_Role'.

Msg 1750, Level 16, State 0, Line 1

  Could not create constraint. See previous errors.

Body:
The table Has's foreign key is same with a references table's primary key.

CONSTRAINT Pk_Works_On_Bssn FOREIGN KEY (Bssn, Role_Name) REFERENCES [Role](Bssn, Role_Name)ON DELETE CASCADE ON UPDATE CASCADE


问:
Change set of Image resource on Button click in fragment
I have there sets of drawable in int array. Is it possible to change the image resource of the image view in the fragment on button click? for example i have there a method onclicklistener for button benefit_babies... i want to set the image resource into the int array benefitBaby on click of the button.

InformationTab fragment

```<code>package com.example.aldrinjohn.sample;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by Aldrin John on 3/20/2017.
 */

public class InformationTab extends Fragment{
    ViewPager viewPager;
    CustomSwipeAdapter adapter;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.informationtab, container, false);
        viewPager = (ViewPager)rootView.findViewById(R.id.view_pager);
        adapter = new CustomSwipeAdapter(this.getActivity());
        viewPager.setAdapter(adapter);

        return rootView;

    }

}
</code>```

XML File:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/trivia"
        android:text="BreastFeeding Trivia"/>

    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/benefit_babies"
        android:text="Benefits to Babies"/>

    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/storing"
        android:text="Storing Breastmilk"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/pump"
            android:text="How to Pump Breastmilk"/>

        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/benefit_mother"
            android:text="Benefits to Mothers"/>

        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/tips"
            android:text="Tips and Information"/>

    </LinearLayout>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/image_view"/>

</LinearLayout>
</code>```

JAVA Code:

```<code>package com.example.aldrinjohn.sample;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.android.gms.tagmanager.Container;

/**
 * Created by Aldrin John on 3/26/2017.
 */

public class CustomSwipeAdapter extends PagerAdapter implements View.OnClickListener{
    private int[] trivia = {R.drawable.c1,R.drawable.c2,R.drawable.c3,R.drawable.c4, R.drawable.c5,R.drawable.c6};
    private int[] benefitBaby = {R.drawable.c7,R.drawable.c8,R.drawable.c9};
    private int[] benefitMother = {R.drawable.c91,R.drawable.c92};
    private int[] info = {R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5,R.drawable.a6,R.drawable.a7,
                            R.drawable.a8,R.drawable.a9,R.drawable.a91,R.drawable.a92};
    private int[] storing = {R.drawable.b1,R.drawable.b2,R.drawable.b3,R.drawable.b4};
    private Context ctx;
    private LayoutInflater layoutInflater;
    Button btnbenefitB;

    public CustomSwipeAdapter(Context ctx)
    {
        this.ctx = ctx;
    }

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

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view==(LinearLayout)object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position){
        layoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
        btnbenefitB = (Button)item_view.findViewById(R.id.benefit_babies);
        btnbenefitB.setOnClickListener(this);
        ImageView imageView = (ImageView)item_view.findViewById(R.id.image_view);
        imageView.setImageResource(trivia[position]);
        container.addView(item_view);

        return item_view;
    }
@Override
    public void destroyItem(ViewGroup container, int position, Object object){
        container.removeView((LinearLayout)object);
    }

    public int getCount(int[] x) {
        return x.length - 1;
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.benefit_babies:

                break;
        }
    }
}
</code>```

答: Hi everyone thanks for the help. I solved it by using view page adapter. Every onclick button I will change the adapter. Thank you!! </p>

Body:
I have there sets of drawable in int array. Is it possible to change the image resource of the image view in the fragment on button click? for example i have there a method onclicklistener for button benefit_babies... i want to set the image resource into the int array benefitBaby on click of the button.

InformationTab fragment

package com.example.aldrinjohn.sample;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by Aldrin John on 3/20/2017.
 */

public class InformationTab extends Fragment{
    ViewPager viewPager;
    CustomSwipeAdapter adapter;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.informationtab, container, false);
        viewPager = (ViewPager)rootView.findViewById(R.id.view_pager);
        adapter = new CustomSwipeAdapter(this.getActivity());
        viewPager.setAdapter(adapter);

        return rootView;

    }

}

XML File:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/trivia"
        android:text="BreastFeeding Trivia"/>

    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/benefit_babies"
        android:text="Benefits to Babies"/>

    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/storing"
        android:text="Storing Breastmilk"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/pump"
            android:text="How to Pump Breastmilk"/>

        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/benefit_mother"
            android:text="Benefits to Mothers"/>

        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/tips"
            android:text="Tips and Information"/>

    </LinearLayout>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/image_view"/>

</LinearLayout>

JAVA Code:

package com.example.aldrinjohn.sample;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.android.gms.tagmanager.Container;

/**
 * Created by Aldrin John on 3/26/2017.
 */

public class CustomSwipeAdapter extends PagerAdapter implements View.OnClickListener{
    private int[] trivia = {R.drawable.c1,R.drawable.c2,R.drawable.c3,R.drawable.c4, R.drawable.c5,R.drawable.c6};
    private int[] benefitBaby = {R.drawable.c7,R.drawable.c8,R.drawable.c9};
    private int[] benefitMother = {R.drawable.c91,R.drawable.c92};
    private int[] info = {R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5,R.drawable.a6,R.drawable.a7,
                            R.drawable.a8,R.drawable.a9,R.drawable.a91,R.drawable.a92};
    private int[] storing = {R.drawable.b1,R.drawable.b2,R.drawable.b3,R.drawable.b4};
    private Context ctx;
    private LayoutInflater layoutInflater;
    Button btnbenefitB;

    public CustomSwipeAdapter(Context ctx)
    {
        this.ctx = ctx;
    }

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

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view==(LinearLayout)object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position){
        layoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
        btnbenefitB = (Button)item_view.findViewById(R.id.benefit_babies);
        btnbenefitB.setOnClickListener(this);
        ImageView imageView = (ImageView)item_view.findViewById(R.id.image_view);
        imageView.setImageResource(trivia[position]);
        container.addView(item_view);

        return item_view;
    }
@Override
    public void destroyItem(ViewGroup container, int position, Object object){
        container.removeView((LinearLayout)object);
    }

    public int getCount(int[] x) {
        return x.length - 1;
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.benefit_babies:

                break;
        }
    }
}


问:
How can we test kinvey-flex-sdk's locally?
As per my understanding, the service-objects that we are registering are invoked by kinvey collections only. Is there any way to test that locally ?

I have written  below code.

var sdk = require('kinvey-flex-sdk');

const PORT = 8080;

sdk.service({ host: 'localhost', port: PORT }, function (err, flex) {

```<code> const data = flex.data;

 function authentication(request, complete, modules) {
       console.log("Inside...");
       complete().setBody("Authenticated");
 };

const widgets = data.serviceObject('widgets');

widgets.onInsert(authentication);
</code>```

});

And my doubt is authentication function is not triggered for the POST request http://localhost:8080/widgets  {}..

Can u please help me in resolving that ?

Thanks in advance..

答:
You need to pass following headers :

```<code>Content-Type:application/json
Authorization:Basic <basicAuth>
X-Kinvey-App-Metadata:{ "_id" : "<kinveyAppId>", "appsecret" : "<kinveyAppSecret>", "mastersecret" : "<kinveyMasterSecret>", "baasUrl" : "<kinveyBaseURL>" }
X-Kinvey-Original-Request-Headers:{ "x-kinvey-api-version" : "<KinveyApiVersion>", "authorization" : "Basic <basicAuth>", "x-kinvey-client-app-version" : "<KinveyClientAppVersion>"}
X-Kinvey-Username:<username>
X-Kinvey-User-Id:<userid>
</code>```

If you're working with flex function :

```<code>http://localhost:<port>/_flexFunctions/<flexFunctionName>
</code>```

Body:
As per my understanding, the service-objects that we are registering are invoked by kinvey collections only. Is there any way to test that locally ?

I have written  below code.

var sdk = require('kinvey-flex-sdk');

const PORT = 8080;

sdk.service({ host: 'localhost', port: PORT }, function (err, flex) {

 const data = flex.data;

 function authentication(request, complete, modules) {
       console.log("Inside...");
       complete().setBody("Authenticated");
 };

const widgets = data.serviceObject('widgets');

widgets.onInsert(authentication);

});

And my doubt is authentication function is not triggered for the POST request http://localhost:8080/widgets  {}..

Can u please help me in resolving that ?

Thanks in advance..

Body:
You need to pass following headers :

Content-Type:application/json
Authorization:Basic <basicAuth>
X-Kinvey-App-Metadata:{ "_id" : "<kinveyAppId>", "appsecret" : "<kinveyAppSecret>", "mastersecret" : "<kinveyMasterSecret>", "baasUrl" : "<kinveyBaseURL>" }
X-Kinvey-Original-Request-Headers:{ "x-kinvey-api-version" : "<KinveyApiVersion>", "authorization" : "Basic <basicAuth>", "x-kinvey-client-app-version" : "<KinveyClientAppVersion>"}
X-Kinvey-Username:<username>
X-Kinvey-User-Id:<userid>

If you're working with flex function :

http://localhost:<port>/_flexFunctions/<flexFunctionName>


问:
Does Session.list() method use session cache in hibernate?
Does Hibernate cache the results get from Session.list()?
What my believe is session.get() or session.load() method cache the result in the memory but session.list() doesn't as it generate lots of record that might cause memory issue but in case of get and load it will only generate single object.</p>

答:
Actually it does generate memory issues if you are not careful.

But you will hit another limit before: performance...

Everything Hibernate loads inside a transaction is stored in the context. Every time you try to load an object, it checks in the context first if it doesn't already exist. Having a lots of entities stored in the context is a huge performance hit (for complex reasons I won't detail here).

If Hibernate didn't do this, it would return many instances of the same entity, with duplicated data. If you updated them, it wouldn't be able to know which data to persist to database.

Rule of the thumb: Keep your transactions short, or evict() the entities from the context as soon as possible if you don't need them anymore.

PS: It is not called "cache"; the session is a context necessary to perform its ORM tasks correctly. There are second-level cache libraries, but it's a totally different thing.


问:
Angular controllers: confused about the '$scope' parameter
```<code><div ng-app="myApp" ng-controller="myCtrl">

 <h1>{{carname}}</h1>

</div>

<script>
 var app = angular.module('myApp', []);

 app.controller('myCtrl', function($scope) {
     $scope.carname = "Volvo";
 });
</script>
</code>```

I thought $scope is merely the name of a parameter for the anonymous function, and you can't just assign it properties (carname) without it passing an object as the argument.

So does Angular automatically create an argument called something like myCtrlScope to pass to the $scope parameter? Otherwise, I don't see any way that an actually object is being passed to $scope, which is merely a parameter.

答:
The way you wrote the controller can be written as like this also:

```<code>app.controller('myCtrl', [ "$scope", function($scope) {
   $scope.carname = "Volvo";
}]);
</code>```

The way you declared is short-hand method. The way you mentioned is not wrong but the better way to declare is the above method where we specify each of the dependencies. You can check on documentation for dependency injection for better clarification.

Body:
{{carname}}

I thought $scope is merely the name of a parameter for the anonymous function, and you can't just assign it properties (carname) without it passing an object as the argument.

So does Angular automatically create an argument called something like myCtrlScope to pass to the $scope parameter? Otherwise, I don't see any way that an actually object is being passed to $scope, which is merely a parameter.

Body:
The way you wrote the controller can be written as like this also:

app.controller('myCtrl', [ "$scope", function($scope) {
   $scope.carname = "Volvo";
}]);

The way you declared is short-hand method. The way you mentioned is not wrong but the better way to declare is the above method where we specify each of the dependencies. You can check on documentation for dependency injection for better clarification.


问:
Android - Installation failed with message: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED
I cannot run my app anymore, I have the error:

Failure [INSTALL_PARSE_FAILED_MANIFEST_MALFORMED]

I read many other questions about it here but I didn't find a solution so far, could anyone have a look at my manifest and tell me what I did wrong?

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="kalianey.com.bonnieandclit" >

<application
    android:name="Utils.KYController"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Register"
        android:label="@string/title_activity_register" >
    </activity>
    <activity
        android:name=".People"
        android:label="@string/title_activity_people" >
    </activity>
</application>
</manifest>
</code>```

EDIT: error log

```<code>Installing kalianey.com.bonnieandclit
DEVICE SHELL COMMAND: pm install -r "/data/local/tmp/kalianey.com.bonnieandclit"
pkg: /data/local/tmp/kalianey.com.bonnieandclit
Failure [INSTALL_PARSE_FAILED_MANIFEST_MALFORMED]
</code>```

EDIT 2: screenshot of the file structure

答: In my project,I have two package and I change my "android.intent.action.MAIN" to a new package,that i found this problem.Then i copy into my old package,and it gone. myabe it can help you.</p>

Body:
I cannot run my app anymore, I have the error:

Failure [INSTALL_PARSE_FAILED_MANIFEST_MALFORMED]

I read many other questions about it here but I didn't find a solution so far, could anyone have a look at my manifest and tell me what I did wrong?

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="kalianey.com.bonnieandclit" >

<application
    android:name="Utils.KYController"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Register"
        android:label="@string/title_activity_register" >
    </activity>
    <activity
        android:name=".People"
        android:label="@string/title_activity_people" >
    </activity>
</application>
</manifest>

EDIT: error log

Installing kalianey.com.bonnieandclit
DEVICE SHELL COMMAND: pm install -r "/data/local/tmp/kalianey.com.bonnieandclit"
pkg: /data/local/tmp/kalianey.com.bonnieandclit
Failure [INSTALL_PARSE_FAILED_MANIFEST_MALFORMED]

EDIT 2: screenshot of the file structure


问:
Only have Firefox extension code run once per session
I am creating a Firefox extension that requires the user to login.  Each time a new window, but not new tab is opened, the 'code' for the extension is run.  I would prefer that the code is only run one time per session.

The setup of the extension looks like this.  (let me know if I am missing anything):

in chrome manifest:
overlay    chrome://browser/content/browser.xul  chrome://my/overlay.xul

in overlay.xul:

<overlay id="socialSidebarOverlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

答:
You might want to observe (and act on) one of the possible Mozilla Observer Notifications

Either actually act on something when starting up, or in you extension check for a particular value that is reset when the browser closes [this can be tricky, as abnormal shutdowns may not reset].

See Also: Receiving Startup Notifications


问:
Pointer static method that points to no static method
I've been trying to make a pointer function that points to a method doing something like this(visual C++):

```<code>struct test
{
  int tst(int a)
  {
    return a * 4;
  }
};
// ok, this the visual C++ compiler does not accept it... (mingw accept it)

int(*tstptr)(int) = (int(*)(int))&test::tst;
</code>```

Then I've done something like this:

```<code>struct Dx
{
    int SomeMethod()
    {
        return 4;
    }
};

struct Dy
{
    static int(*pSomeMethod)();
};

int(Dy::*pSomeMethod)() = (int( Dy::*)())&Dx::SomeMethod;
</code>```

So far so good, this compiles without problems, but if I try call her:

```<code>Dy::pSomeMethod();
</code>```

The compiler returns me:

Error 1 error LNK2001: external symbol "public: static int (__stdcall
  * Dy::pSomeMethod) (void)" (? PSomeMethod@Dy@@2P6GHXZA) unresolved

which I do not understand, because  it is not suppose pSomeMethod he is not pointing at SomeMethod ?

答:
Your declaration of pSomeMethod defines a pointer to a function within class Dy that returns an int.  You want to declare it as it appears in the linker error:

```<code>int (*Dy::pSomeMethod)();
</code>```

which is a member of Dy that is a pointer to a function returning an int.

What you're trying to do won't work, since Dx::SomeMethod is a member function of Dx, which needs a this pointer.  Calling thru pSomeMethod won't have one.

When done right, you can just assign the address of the function to the pointer without using a cast.

Body:
I've been trying to make a pointer function that points to a method doing something like this(visual C++):

struct test
{
  int tst(int a)
  {
    return a * 4;
  }
};
// ok, this the visual C++ compiler does not accept it... (mingw accept it)

int(*tstptr)(int) = (int(*)(int))&test::tst;

Then I've done something like this:

struct Dx
{
    int SomeMethod()
    {
        return 4;
    }
};

struct Dy
{
    static int(*pSomeMethod)();
};

int(Dy::*pSomeMethod)() = (int( Dy::*)())&Dx::SomeMethod;

So far so good, this compiles without problems, but if I try call her:

Dy::pSomeMethod();

The compiler returns me:

Error 1 error LNK2001: external symbol "public: static int (__stdcall
  * Dy::pSomeMethod) (void)" (? PSomeMethod@Dy@@2P6GHXZA) unresolved

which I do not understand, because  it is not suppose pSomeMethod he is not pointing at SomeMethod ?

Body:
Your declaration of pSomeMethod defines a pointer to a function within class Dy that returns an int.  You want to declare it as it appears in the linker error:

int (*Dy::pSomeMethod)();

which is a member of Dy that is a pointer to a function returning an int.

What you're trying to do won't work, since Dx::SomeMethod is a member function of Dx, which needs a this pointer.  Calling thru pSomeMethod won't have one.

When done right, you can just assign the address of the function to the pointer without using a cast.


问:
UISearchController filter using two strings
I have been following the tutorial for creating a UISearchController using https://www.raywenderlich.com/113772/uisearchcontroller-tutorial

Everything is set up and working perfectly. I have two categories in my dataArray: Borough and Neighborhood. I set up my searchBar to only look into the values for Neighborhood. I created buttons for the different boroughs and what i'm hoping to achieve is when the button is pressed it will show all the possible values for that borough, but I can't seem to find anything to do this

答:
I believe what you are saying is that you want to search for a text value entered via the search bar in the Neighbourhood values and to specifically look for the Neighbourhood in a given Borough. Correct?

If that is the case, all you'd have to do is modify your search condition. If your search condition is currently something like (to borrow from the rw.com tutorial):

```<code>return row.neighbourhood.lowercaseString.containsString(searchText.lowercaseString)
</code>```

Then you'd have to modify the condition to include a check for the Borough name too - and here, we'll assume the borough variable contains the Borough name that you selected via button press:

```<code>return row.neighbourhood.lowercaseString.containsString(searchText.lowercaseString) && row.borough == borough
</code>```

That should return only array values which have the specified Neighbourhood name and are in the given Borough. If that is not what you wanted, then you might want to provide a bit more detail such as the structure of the data array, how the Neighbourhoods and Boroughs are linked, and perhaps even a screenshot of the UI so that we can see how you select a Borough in the UI.

Body:
I believe what you are saying is that you want to search for a text value entered via the search bar in the Neighbourhood values and to specifically look for the Neighbourhood in a given Borough. Correct?

If that is the case, all you'd have to do is modify your search condition. If your search condition is currently something like (to borrow from the rw.com tutorial):

return row.neighbourhood.lowercaseString.containsString(searchText.lowercaseString)

Then you'd have to modify the condition to include a check for the Borough name too - and here, we'll assume the borough variable contains the Borough name that you selected via button press:

return row.neighbourhood.lowercaseString.containsString(searchText.lowercaseString) && row.borough == borough

That should return only array values which have the specified Neighbourhood name and are in the given Borough. If that is not what you wanted, then you might want to provide a bit more detail such as the structure of the data array, how the Neighbourhoods and Boroughs are linked, and perhaps even a screenshot of the UI so that we can see how you select a Borough in the UI.


问:
Node.js encode ISO8859-1 to UTF-8
I have an application that allows users to persist strings to a database and those strings may contain emojis. The problem I have is an emoji such as  will get stored in MySQL as ðŸ˜Š

When I retrieve this string using a PHP MySQL client and render it in a web browser, it renders fine probably because the Content-Type is set to UTF-8. When I try to read the string in node.js, I get back what I think is the ISO8859-1 encoding a literal ðŸ˜Š. The charset on the table is set to latin1 and that's where I'm getting ISO8859-1 from.

What's the right way to encode the string in node.js so that I can see the emoji and not the encoding set by MySQL when I console.log the string?

答:
ðŸ˜Š is Mojibake for .  Interpreting the former as latin1, you get hex F09F988A, which is the UTF-8 hex for that Emoji.

(Note:  UTF-8 outside MySQL is equivalent to utf8mb4 inside MySQL.)

In MySQL, you must have the column/table declared with CHARACTER SET utf8mb4.  You must also state that the data being stored/fetched is encoded utf8mb4.  Note: utf8 will not suffice.

Do a SELECT HEX(col) FROM ... to see if you get that hex for that Emoji.  If that is the case and the column is currently latin1, then part of the fix is to carefully convert the column to utf8mb4.  That is, you have CHARACTER SET latin1, but have UTF-8 bytes in it; this will leave bytes alone while fixing charset.  Assuming the column is already VARCHAR(111) CHARACTER SET latin1 NOT NULL, then do this 2-step ALTER:

```<code>ALTER TABLE tbl MODIFY COLUMN col VARBINARY(111) NOT NULL;
ALTER TABLE tbl MODIFY COLUMN col VARCHAR(111) CHARACTER SET utf8mb4 NOT NULL;
</code>```

Virtually any other conversion mechanism will make a worse mess.

As for establishing the connection correctly, it goes something like this for node.js:

```<code>var connection = mysql.createConnection({ ... , charset : 'utf8mb4'});
</code>```

Title: Node.js encode ISO8859-1 to UTF-8

Body:
ðŸ˜Š is Mojibake for .  Interpreting the former as latin1, you get hex F09F988A, which is the UTF-8 hex for that Emoji.

(Note:  UTF-8 outside MySQL is equivalent to utf8mb4 inside MySQL.)

In MySQL, you must have the column/table declared with CHARACTER SET utf8mb4.  You must also state that the data being stored/fetched is encoded utf8mb4.  Note: utf8 will not suffice.

Do a SELECT HEX(col) FROM ... to see if you get that hex for that Emoji.  If that is the case and the column is currently latin1, then part of the fix is to carefully convert the column to utf8mb4.  That is, you have CHARACTER SET latin1, but have UTF-8 bytes in it; this will leave bytes alone while fixing charset.  Assuming the column is already VARCHAR(111) CHARACTER SET latin1 NOT NULL, then do this 2-step ALTER:

ALTER TABLE tbl MODIFY COLUMN col VARBINARY(111) NOT NULL;
ALTER TABLE tbl MODIFY COLUMN col VARCHAR(111) CHARACTER SET utf8mb4 NOT NULL;

Virtually any other conversion mechanism will make a worse mess.

As for establishing the connection correctly, it goes something like this for node.js:

var connection = mysql.createConnection({ ... , charset : 'utf8mb4'});


问:
How to have a Text Area in my Web application?
I want to make a blog page in my web application. I want to have a large text area to enter atleast 300 words in my blog page. it should have spell check. making bold option. It should be like the s*ame window in StackOverFlow where am entering my question now*.

How to achieve this. Any suggestions Please?

答:
I think this is the one used by Stackoverflow:

http://wmd-editor.com/


问:
Why Access path denied?
I'm trying to read a text file with File.ReadAllText and FileStream, but for some reason I get the System.UnauthorizedAccessException every time.

```<code> class consultas
{
    public consultas()
    {

    }

    private string Inativos = @"C:\Users\Mathias Cruz\Desktop\helloWorld\helloWorld\Consultas";

    public string getInativos()
    {
        try
        {
            // string path = Directory.GetCurrentDirectory();
            this.Inativos = File.ReadAllText(this.Inativos);

        }
        catch(Exception e)
        {
            throw e;

        }
        return this.Inativos;

    }
}
</code>```

Why? I have permissions in that folder, so why do I get this exception?

答:
Based on your code, you are either trying to read a Folder since you didn't specify a extension on your File Path here:

```<code>private string Inativos = @"C:\Users\Mathias Cruz\Desktop\helloWorld\helloWorld\Consultas";
</code>```

It will definitely throw a UnauthorizedAccessException error. So make sure you have the exact file path together with its extension.

Title: Why Access path denied?

Body:
I'm trying to read a text file with File.ReadAllText and FileStream, but for some reason I get the System.UnauthorizedAccessException every time.

 class consultas
{
    public consultas()
    {

    }

    private string Inativos = @"C:\Users\Mathias Cruz\Desktop\helloWorld\helloWorld\Consultas";

    public string getInativos()
    {
        try
        {
            // string path = Directory.GetCurrentDirectory();
            this.Inativos = File.ReadAllText(this.Inativos);

        }
        catch(Exception e)
        {
            throw e;

        }
        return this.Inativos;

    }
}

Why? I have permissions in that folder, so why do I get this exception?

Body:
Based on your code, you are either trying to read a Folder since you didn't specify a extension on your File Path here:

private string Inativos = @"C:\Users\Mathias Cruz\Desktop\helloWorld\helloWorld\Consultas";

It will definitely throw a UnauthorizedAccessException error. So make sure you have the exact file path together with its extension.


问:
how i can acess to elements of arraylist<class>
hi i want to know how i can access to elements of arraylist in java?
i have this class .

```<code>class flight
{
    public String start;
    public String end;
    public int timethatend ;
    public int timethatstart;
    flight ( int ts , int tf , String s , String e )
    {
        this.start = s;
        this.end =e;
        this.timethatend = tf;
        this.timethatstart = ts;
    }
}
</code>```

and i have this arraylist in my main class

```<code>ArrayList<flight>list = new ArrayList<flight>();
</code>```

now i want print the elements of arraylist i use this syntax

```<code>System.out.println(list.get(0));
</code>```

but the out put is this
flight@1f96302
what should i do?
                                                                           another question how i can change them for example i want change the time of takeoff the first flight.

答:
This is printing the object reference to your flight object. You need to add a toString() method to your Flight class and use it to print the flight info. For example:

```<code>public String toString() {
    return start + "," + timethatstart + "," + end + "," + timethatend;
}
</code>```

When you print:

```<code>System.out.println(list.get(0).toString());
</code>```

Body:
hi i want to know how i can access to elements of arraylist in java?
i have this class .

class flight
{
    public String start;
    public String end;
    public int timethatend ;
    public int timethatstart;
    flight ( int ts , int tf , String s , String e )
    {
        this.start = s;
        this.end =e;
        this.timethatend = tf;
        this.timethatstart = ts;
    }
}

and i have this arraylist in my main class

ArrayList<flight>list = new ArrayList<flight>();

now i want print the elements of arraylist i use this syntax

System.out.println(list.get(0));

but the out put is this
flight@1f96302
what should i do?
                                                                           another question how i can change them for example i want change the time of takeoff the first flight.

Body:
This is printing the object reference to your flight object. You need to add a toString() method to your Flight class and use it to print the flight info. For example:

public String toString() {
    return start + "," + timethatstart + "," + end + "," + timethatend;
}

When you print:

System.out.println(list.get(0).toString());


问:
Find all files that have set UID bit on
I'm trying to find all files with the permission "SUID" and write it to a text file, but when I run the following command, the text file is empty:

```<code>sudo find / -perm 4000 > suid.txt
</code>```

Is there a problem with my command?

答:
The correct syntax is:

```<code>sudo find / -perm -4000 > suid.txt
</code>```

or

```<code>sudo find / -perm -u+s > suid.txt
</code>```

For example:

```<code>sudo find / -perm -4000 -exec ls -l {} +
</code>```

Gives this output:

```<code>-rwsr-xr-x 1 root    root        30800 May 15  2015 /bin/fusermount
-rwsr-xr-x 1 root    root        94792 Sep  2  2015 /bin/mount
-rwsr-xr-x 1 root    root        44168 May  7  2014 /bin/ping
-rwsr-xr-x 1 root    root        44680 May  7  2014 /bin/ping6
-rwsr-xr-x 1 root    root        36936 Jan 27  2016 /bin/su
<truncated>
</code>```

The issue with your command is that it is looking for mode bits where set uid bit is set and nothing else is set.  Adding a - prefix would look for all modes where set uid is set, regardless of other bits.

From man find:

-perm mode

File's  permission  bits are exactly mode (octal or symbolic).
  Since an exact match is required, if you want to use this form for
  symbolic modes, you may have to specify a rather complex mode string.
  For example -perm g=w will only match files which have mode 0020 (that
  is, ones for which group write permission is the only permission set).
  It is more likely that you will want to use the /' or-' forms, for
  example -perm -g=w, which matches any file with group write
  permission.

-perm -mode

All  of the permission bits mode are set for the file.  Symbolic
  modes are accepted in this form, and this is usually the way in which
  would want to use them.  You must specify u',g' or `o' if you use a
  symbolic mode.

Title: Find all files that have set UID bit on

Body:
I'm trying to find all files with the permission "SUID" and write it to a text file, but when I run the following command, the text file is empty:

sudo find / -perm 4000 > suid.txt

Is there a problem with my command?

Body:
The correct syntax is:

sudo find / -perm -4000 > suid.txt

or

sudo find / -perm -u+s > suid.txt

For example:

sudo find / -perm -4000 -exec ls -l {} +

Gives this output:

-rwsr-xr-x 1 root    root        30800 May 15  2015 /bin/fusermount
-rwsr-xr-x 1 root    root        94792 Sep  2  2015 /bin/mount
-rwsr-xr-x 1 root    root        44168 May  7  2014 /bin/ping
-rwsr-xr-x 1 root    root        44680 May  7  2014 /bin/ping6
-rwsr-xr-x 1 root    root        36936 Jan 27  2016 /bin/su
<truncated>

The issue with your command is that it is looking for mode bits where set uid bit is set and nothing else is set.  Adding a - prefix would look for all modes where set uid is set, regardless of other bits.

From man find:

-perm mode

File's  permission  bits are exactly mode (octal or symbolic).
  Since an exact match is required, if you want to use this form for
  symbolic modes, you may have to specify a rather complex mode string.
  For example -perm g=w will only match files which have mode 0020 (that
  is, ones for which group write permission is the only permission set).
  It is more likely that you will want to use the /' or-' forms, for
  example -perm -g=w, which matches any file with group write
  permission.

-perm -mode

All  of the permission bits mode are set for the file.  Symbolic
  modes are accepted in this form, and this is usually the way in which
  would want to use them.  You must specify u',g' or `o' if you use a
  symbolic mode.


问:
How can I return a person's information when they have the max(age) among others in neo4j?
I am working on neo4j. My application is a Family tree. I want to return name and age for the oldest person on the family.

I used this Cypher Query to see the max age on the tree:

MATCH (n) WITH  MAX(n.age) as age return age.

Now, I want to get the n.name and n.age but I do not know how.

Could anyone help me?

答:
To solve the problem, you must sort the nodes in descending order of age and take the first position:

```<code>MATCH (n)
RETURN n.name, n.age
       ORDER BY P.age DESC // Sorting in decreasing order
       LIMIT 1             // Return the first node in the sequence
</code>```

But what if we have people of the same age? Then our query returns incomplete information.

So the solution will be to calculate the maximum age and return all the nodes in which the property age is equal to this value:

```<code>MATCH (n)
WITH MAX(n.age) as maxAge
MATCH (n) WHERE n.age = maxAge
RETURN n.name, maxAge
</code>```

By the way, it's strange that you keep the age of the person. It is advisable to keep the date of birth.  If the date of birth is not known exactly, then store the year of birth or the interval of approximate birth years.

Body:
To solve the problem, you must sort the nodes in descending order of age and take the first position:

MATCH (n)
RETURN n.name, n.age
       ORDER BY P.age DESC // Sorting in decreasing order
       LIMIT 1             // Return the first node in the sequence

But what if we have people of the same age? Then our query returns incomplete information.

So the solution will be to calculate the maximum age and return all the nodes in which the property age is equal to this value:

MATCH (n)
WITH MAX(n.age) as maxAge
MATCH (n) WHERE n.age = maxAge
RETURN n.name, maxAge

By the way, it's strange that you keep the age of the person. It is advisable to keep the date of birth.  If the date of birth is not known exactly, then store the year of birth or the interval of approximate birth years.