text:
Q: Oque está faltando? <?php
    $teste = $_POST['Nome'];
?>

<html>
    <head>
        <title>O</title>
    </head>
<body>
    <form name="f_cad" method="POST"/>
        <input type="text" name="Nome"/>
</body>
</html>

Notice: Undefined index: Nome in D:\wamp\www\cursophp\all.php on line 2
Oque está faltando? Está tudo certo.

A: O formulário precisa "abraçar" os componentes que deverão ser enviados ao servidor.
<form name="f_cad" method="POST">
   <input type="text" name="Nome" />
</form>

Para testar faça assim.
<?php
if(isset($_POST['Nome'])) {
    print "Foi recebido :: " . $_POST['Nome'];
} else {
    print "Nada foi Recebido";
}
?>

A: O código está a funcionar perfeitamente, o warning aparece porque na altura em que abres a página ainda não submeteste o form pelo que a variável $_POST['Nome'] ainda não existe.
No teste sugerido em cima, vai-te aparecer "Nada foi recebido" se ainda não submeteste o form em vez do warning que te dava e a partir do momento que o submetes, ou seja, a partir do momento em que envias uma váriavel $_POST['Nome'], ele vai-te dar o resultado na tela.
Espero que tenhas percebido


text:
Q: MySQL how to group by and select certain status from multiple rows? A credit card company has several credit cards issued to each consumer.
CREATE TABLE card (
  cardnumber int PRIMARY KEY,
  customer int,
  balance decimal(9,2),
  status varchar(10)
);

INSERT INTO card VALUES ('100', '1', 100.00, 'active');
INSERT INTO card VALUES ('101', '1', 100.00, 'expired');
INSERT INTO card VALUES ('102', '2', 100.00, 'limited');
INSERT INTO card VALUES ('103', '2', 100.00, 'locked');
INSERT INTO card VALUES ('104', '3', 100.00, 'lost');
INSERT INTO card VALUES ('105', '3', 100.00, 'closed');

A report is desired consisting of one row per cardholder, total balance on all cards, and the least restrictive status in the exact order of: 1. Active, 2. Expired, 3. Limited, 4. Locked, 5. Lost, 6. Closed.
Cardholder #1 has a card in 'active', and a card in 'expired', the report should show 'active'.
Cardholder #2 has a card in 'limited', and a card in 'locked', the report should show 'limited'.
Cardholder #3 has a card in 'lost', and a card in 'closed', the report should show 'lost'.
It appears it would be helpful to have another table for status
create table status (
  status varchar(15) primary key,
  restriction int
);

insert into status values ('active', 1);
insert into status values ('expired', 2);
insert into status values ('limited', 3);
insert into status values ('locked', 4);
insert into status values ('lost', 5);
insert into status values ('closed', 6);

How can the query show only the least restrictive status of the cardholders cards?
select c.customer, sum(c.balance), 'status?'
from card c
join status s on s.status=c.status?
group by c.customer

http://sqlfiddle.com/#!2/8d680/2
PS Table #1 'card' cannot be changed.

A: Create a derived table containing the minimum restriction for each customer and then join the minimum restriction to the status table.
select t1.*, s.status from (
    select c.customer, sum(c.balance), min(restriction) min_restriction
    from card c
    join status s on s.status=c.status
    group by c.customer
) t1 join status s on t1.min_restriction = s.restriction

http://sqlfiddle.com/#!2/8d680/3

A: You can generate the report even not to create the second table

    select customer,sum(balance),
    min(restriction),case
    when min(restriction)=1 then 'active'
    when min(restriction)=2 then 'expired'
    when min(restriction)=3 then 'limited'
    when min(restriction)=4 then 'locked'
    else 'lost'
    end stat
    from (
    select cardnumber,customer,balance,status,case
    when status='active' then 1
    when status='expired' then 2
    when status='limited' then 3
    when status='locked' then 4
    when status='lost' then 5
    else 6
    end restriction
    from card  ) c
    group by
    customer

http://sqlfiddle.com/#!2/898bd/5
MySQL has some advantages out of  RDMS standard.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Codeigniter making image upload optional in a form I have a form with three fields- one input field, one textarea and an image upload.
The form works fine for uploading image when I fill everything and select an image to upload but when I do not select an image it shows select and image. I want the form to submit even if the user does not upload an image. I am sure I had a solution yesterday for this but it stopped working today.
Controller :
        function store()
{
$this->output->enable_profiler(TRUE);

        $this->load->model('campus_m');
                    $config['upload_path'] = './uploads/';
                    $config['allowed_types'] = 'gif|jpg|png|jpeg';
                    $config['max_size'] = '100';
                    $config['max_width']  = '1024';
                    $config['max_height']  = '768';
                    $config['file_name'] = preg_replace('/[^a-z0-9]+/i','-',iconv('UTF-8','ASCII//TRANSLIT',$this->input->post('name')));
                    $config['file_name'] = trim($config['file_name'],'-').now().'.jpg';

                    $this->load->library('upload', $config);

                            $this->load->helper(array('form', 'url'));

                        $this->load->library('form_validation');

                        $this->form_validation->set_rules('goods', 'Goods', 'required');
                        $this->form_validation->set_rules('name', 'Name', 'required|max_length[12]');
                        if ($this->form_validation->run() == FALSE)
                        {
                                $this->load->view('campus_write_v');
                        }
                        else
                        {
                                    if (empty($_FILES['userfile'])) {
                    print_r($_FILES['userfile']);
                                if(!$query = $this->campus_m->create_review("Marla-overdoses1360186300.jpg")){
                                    $data['write_campus'] = 'The answer has not been stored.';
                                    $this->load->view('campus_write_v', $data);
                                    }
                                else {
                                    $data['write_campus'] = 'The answer has been stored. ';
                                    $this->load->view('campus_write_v', $data);
                                }
                                    }
                                    else{
                                         if($this->upload->do_upload()){
                                if(!$query = $this->campus_m->create_review($config['file_name'])){
                                    $data['write_campus'] = 'The answer has not been stored.';
                                    $this->load->view('campus_write_v', $data);
                                    }
                                else {
                                    $data['write_campus'] = 'The answer has been stored. ';
                                    $this->load->view('campus_write_v', $data);
                                }
                                    }
                            else
                            {
                                 $error = array('error' => $this->upload->display_errors());
                                 foreach ($error as $rows => $r) {
                                 echo $r ;
                                 }
                                    $this->load->view('campus_write_v');
                            }
                            }
                        }
                    }

A:     if(isset($_FILES))
    {

          if(empty($_FILES['file']['name']))
          {
            //logic here
          }else{
                if(//validation here )
                {
                   //logic here
                }

          }

    }


text:
Q: Hibernate 5 Sequence Generate Issue I am migrating to hibernate 5 from 3. I am seeing the sequence generator not working properly in Hibernate 5. I have sequence defined with minimum value 1000 and increment by 1. But when I am trying to create a new entity record, I am seeing a record inserted with id 951. It seems like the id was minuses 50 from actual sequence next value. In my case the ID should be 1000.
Please let me know any help.
Here is my entity and sequence:
Entity:
@Entity
@Table(name = "SOME TABLE")
public class Group {

  @Id
  @Column(name = "id")
  @SequenceGenerator(name = "name",  sequenceName ="SEQ_name" )
  @GeneratedValue(strategy = GenerationType.AUTO, generator="name")
  private Long id;

  @Pattern(regexp = "^[^\\*]*$", message = "{3011}")
  @Size(message = "{3014}")
  @NotBlank(message = "{3000}")
  @Column(name = NAME, unique = true, nullable = false)
  private String name;

Sequence:
CREATE SEQUENCE  SEQ_name MINVALUE 1000 NOMAXVALUE INCREMENT BY 1 CACHE 20 NOORDER NOCYCLE;

A: Hibernate calls SEQ_name.nextval but if the allocationSize is greater than 1, it decrements it by the allocationSize and increments it by 1.
The next (allocationSize-1)  key generation are done without communication with the database simple by increasing by 1.
As a result, if you use the default allocationSize which is 50, there are two consequences:
The sequence must have the INCREMENT BY set to the same value as  allocationSize
To align the sequence with existing key in the database, set the START WITH to
max(ID) + allocationSize
Here a small example
-- START WITH = max(ID) + allocation size
-- INCREMENT BY = allocation size
-- e.g. if 100 is the last key,
-- to start with a key 101 - set START WITH to 150
CREATE SEQUENCE hib_seq START WITH 150 INCREMENT BY 50;

select hib_seq.nextval - 50 + 1 from dual;
101
-- 49 times Hibernate performs increase by 1 - keys 102 to 150
-- new sequence generation
select hib_seq.nextval - 50 + 1 from dual;
151

Note this behaviour requires that property hibernate.id.new_generator_mappings to true as recomended

A: The sequence you defined does not start with 1000, but with 1 (minvalue 1). I also do not see where you set the mentioned sequence as the sequence used by your entity.

A: In some cases, your Oracle user will be able to select a SEQUENCE from another user whose SEQUENCE may not be correct.Therefore, you should check with your Oracle user:
select * from all_sequences t where t.SEQUENCE_NAME = 'HIB_SEQ';


text:
Q: How to draw a transparent UIToolbar or UINavigationBar in iOS7 I would like an entirely transparent UIToolbar and/or UINavigationBar. I have tried the various incantations suggested for pre- and post-iOS 5 but none seem to work any more.
How might this be accomplished in iOS 7?

A: If you want to do it through the entire app you should use the UIAppearance proxy (iOS5+):

UINavigationBar *navigationBarAppearance = [UINavigationBar appearance];
navigationBarAppearance.backgroundColor = [UIColor clearColor];
[navigationBarAppearance setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
navigationBarAppearance.shadowImage = [[UIImage alloc] init];

Docs: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAppearance_Protocol/Reference/Reference.html
Article: http://nshipster.com/uiappearance/

A: Swift 3 (iOS 10)
Transparent UIToolbar
self.toolbar.setBackgroundImage(UIImage(),
                                forToolbarPosition: .any,
                                barMetrics: .default)
self.toolbar.setShadowImage(UIImage(), forToolbarPosition: .any)

Transparent UINavigationBar
self.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.isTranslucent = true

Swift < 3
Transparent UIToolbar
self.toolbar.setBackgroundImage(UIImage(),
                                forToolbarPosition: UIBarPosition.Any,
                                barMetrics: UIBarMetrics.Default)
self.toolbar.setShadowImage(UIImage(),
                            forToolbarPosition: UIBarPosition.Any)

Transparent UINavigationBar
self.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.translucent = true

Objective-C
Transparent UIToolbar
[self.toolbar setBackgroundImage:[UIImage new]
              forToolbarPosition:UIBarPositionAny
                      barMetrics:UIBarMetricsDefault];
[self.toolbar setShadowImage:[UIImage new]
          forToolbarPosition:UIBarPositionAny];

Transparent UINavigationBar
[self.navigationBar setBackgroundImage:[UIImage new]
                         forBarMetrics:UIBarMetricsDefault];
self.navigationBar.shadowImage = [UIImage new];
self.navigationBar.translucent = YES;

Discussion
Setting translucent to YES on the navigation bar does the trick, due to a behavior discussed in the UINavigationBar documentation. I'll report here the relevant fragment:

If you set this property to YES on a navigation bar with an opaque custom background image, the navigation bar will apply a system opacity less than 1.0 to the image.

Final result

A: Try:
[navBar setBackgroundImage:[UIImage alloc] forBarMetrics:UIBarMetricsDefault];

A: @implementation MyCustomNavigationBar

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    [self setupBackground];
}

- (void)setupBackground {
    self.backgroundColor = [UIColor clearColor];
    self.tintColor = [UIColor clearColor];

    // make navigation bar overlap the content
    self.translucent = YES;
    self.opaque = NO;

    // remove the default background image by replacing it with a clear image
    [self setBackgroundImage:[self.class maskedImage] forBarMetrics:UIBarMetricsDefault];

    // remove defualt bottom shadow
    [self setShadowImage: [UIImage new]];
}

+ (UIImage *)maskedImage {
    const float colorMask[6] = {222, 255, 222, 255, 222, 255};
    UIImage *img = [UIImage imageNamed:@"nav-white-pixel-bg.jpg"];
    return [UIImage imageWithCGImage: CGImageCreateWithMaskingColors(img.CGImage, colorMask)];
}

@end

A: Something I stumbled upon is that if I created a subclassed UINavigationBar and then created an empty -(void)drawRect: method, I would get a transparent navigation bar. I only tested this in iOS 7.*, but it seemed to work!


text:
Q: Bootstrap datepicker set half day Is it possible to set half day for bootstrap datepicker
and use different color for same date?
<script type="text/javascript">
    $(document).on('page:change', function () {
        $('.datepicker').datepicker({
            format: "dd-mm-yyyy",
            todayBtn: "linked",
            multidate: true,
            todayHighlight: true,
            language: "ru",
            startDate: "today"
        });
    });
</script>


text:
Q: How to get Coldfusion 10 to work with IIS 10 in Windows 10 Windows 10 comes with IIS 10, and ColdFusion 10 doesn't seem to like it.  ColdFusion 10 installs fine, but when it comes time to create connectors (either during installation or by using the tool at C:\ColdFusion10\cfusion\runtime\bin\wsconfig.exe), it fails.  The error message I get is that it doesn't support IIS 10.

This connector is required to set up the CFIDE and jakarta virtual folders in IIS.
Any way around this?

A: An already deleted blog post from blogs.coldfusion.com (http://blogs.coldfusion.com/post.cfm/configuring-connectors-manually-for-iis-10) once stated the following

With Windows 10 out, there is a problem that most of the ColdFusion
  customers will face, configuring connectors for IIS 10. Wsconfig, the
  connector configuration tool, only supports till IIS 8.x. While the
  ColdFusion team is working on this issue and will try to provide the
  fix for it as soon as possible, there is already a KB article which
  can be referred for configuring the connectors manually. Although the
  article was originally written for CF10, it can be used for CF11 also.
  After following all the steps in the article, you need to do one more
  thing. Add index.cfm as default document for your website in IIS.
This solution is only recommended for development environments as
  through testing of the connectors with IIS 10 is still going on. So
  for production machines, you should wait for the actual release from
  Adobe.

UPDATE

Important update: Note that ColdFusion 10 and 11 have been updated to
  support Windows 10, a couple months after this blog post was first
  written. Consider applying that update rather than this manual
  configuration.

A: If you are running Windows 10 Pro, you also have the option of running a Virtual Machine in the included Hyper-V offering.  Instructions on how to enable Hyper-V are found here: http://blogs.technet.com/b/canitpro/archive/2014/10/02/step-by-step-creating-and-running-a-windows-10-vm-on-windows-8-1.aspx
Simply spin up a version of Windows required.

A: apply latest hotfix for cf 11 hotfix_019.jar. that will fix the issue above


text:
Q: RSpec/Shoulda: "should be_valid" fails, "contact.should be_valid" passes I have the following spec:
  context "no firstname present" do
    let(:contact) { build :contact, firstname: 'Mickey', lastname: '', companyname: '' }
    it "should be valid" do
      should be_valid # Does not work
      contact.should be_valid # Works
    end
  end

Why does should be_valid fails, but contact.should be_valid passes? Within the it block, should be_valid should access contact anyway?! Thanks for clarification.

A: You could use subject
context "no firstname present" do
  let(:contact) { build :contact, firstname: 'Mickey', lastname: '', companyname: '' }
  subject { contact }
  it { should be_valid }
end

Edit
I just discovered its [link] which is a great way to test the subject's attributes or test messages sent to it


text:
Q: J2ME - code signing using verisign Intermediate CA I want to sign the J2ME midlet using verisign intermediate CA. Does any one know how to do that or any one succeed with verisign code signing. Please help me with the steps.

A: You need a Verisign class 3 code signing certificate, which you can then use to sign with as normal using KeyTool
However you need to check which devices you wish to deploy to, as common as a Verisign certificate is, the root certificate is not present on all phones! unfortunately this means if you sign the application you will be unable to install on those devices where the root certificate is not present.
The most ubiquitous root certificate on the phones is the one provided by the UTI for which you will need to look into the Java verified process.

A: Thawte is better than Verisign in many ways. So buying Thawte and using it is the solution.


text:
Q: How to create a tabHost containing a ListView? In the documentation it is said that TabActivity is deprecated : enter link description here. I followed their example using the FragmentTabHost but it crashed also. So I tried to create a simple activity and adding an intent as the content of the TabSpec, but the app crashed ! So how to create a TabHost containing a ListView ?
Here is what I did :
@Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.onglet_parcelle_batiment);

        mTabHost = (TabHost)findViewById(R.id.onglets);

        mTabHost.setup();

        Bundle dataSent = getIntent().getExtras();

        bien_code = dataSent.getString("bien_code");

        afficherOngletParcelle();

        afficherOngletBatiments();

        mTabHost.setCurrentTab(0);

    }

    private void afficherOngletParcelle() {

        TabHost.TabSpec parcelle = mTabHost.newTabSpec("parcelle");
        View onglet = getLayoutInflater().inflate(R.layout.template_tab_onglets, null);
        TextView label = (TextView) onglet.findViewById(R.id.tabLabel);
        label.setText(getResources().getString(R.string.parcelle));
        parcelle.setIndicator(onglet);
        Intent i = new Intent(OngletParcelleListeBatiments.this, ParcelleActivity.class);
        i = i.putExtra("bien_code", bien_code);
        parcelle.setContent(i);
        mTabHost.addTab(parcelle);

    }

    private void afficherOngletBatiments() {

        TabHost.TabSpec batiment = mTabHost.newTabSpec("batiments");
        View onglet = getLayoutInflater().inflate(R.layout.template_tab_onglets, null);
        TextView label = (TextView) onglet.findViewById(R.id.tabLabel);
        label.setText(getResources().getString(R.string.titre_liste_batiments));
        batiment.setIndicator(onglet);
        Intent i = new Intent(OngletParcelleListeBatiments.this, ListeBatimentsActivity.class);
        i = i.putExtra("bien_code", bien_code);
        batiment.setContent(i);
        mTabHost.addTab(batiment);

    }

A: I'm glad that you asked this question because I have struggled more than 1 day trying to reach what you are trying to reach without using TabActivity. But I finally did it. I have made a tutorial for myself and I was about to post it in my blog in the future.
Here is it in details:-
1)In your XML file, add the following for the 3 tabs.
<TabHost
        android:id="@+id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:background="@android:color/white">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <!-- tab N°1 --> <!-- Inclusion of the interface -->
                <include
                    android:id="@+id/i_layout_1"
                    layout="@layout/layout_1"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
                <!-- tab N°2 --> <!-- Inclusion of the interface -->
                <include
                    android:id="@+id/i_layout_2"
                    layout="@layout/layout_2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>
                <!-- tab N°3 --> <!-- Inclusion of the interface -->
                <include
                    android:id="@+id/i_layout_3"
                    layout="@layout/layout_3"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </FrameLayout>

        </LinearLayout>
    </TabHost>

2)Create a layout for each tab you are reference in the include components. For example the "layout_1.xml".
You can add your ListView or anything else here in this layout
 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:padding="10dp">

<TextView
    android:id="@+id/my_textview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Example"
    android:textColor="@android:color/black" />

</RelativeLayout>

3)Create a custom indicator with the required specifications such as:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/business_tabs_indicator_background"
android:padding="10dp">

<TextView
    android:id="@+id/tv_indicator_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:textColor="@android:color/black"
    android:textStyle="bold" />

</RelativeLayout>

4)Create a custom selector for the tab indicator layout to handle the different states of selection, focused,..etc. For example
business_tabs_indicator_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Active tab -->
<item android:drawable="@android:color/darker_gray" android:state_focused="false" android:state_pressed="false" android:state_selected="true" />
<!-- Inactive tab -->
<item android:drawable="@android:color/white" android:state_focused="false" android:state_pressed="false" android:state_selected="false" />
<!-- Pressed tab -->
<item android:drawable="@android:color/darker_gray" android:state_pressed="true" />
<!-- Selected tab (using d-pad) -->
<item android:drawable="@android:color/darker_gray" android:state_focused="true" android:state_pressed="false" android:state_selected="true" />

</selector>

5)In your Activity or Fragment, initialize the TabHost and add the corresponding tabs as the following:
 private void initializeTabHoster(View rootview) {
    tabHost = (TabHost) rootview.findViewById(R.id.tabhost);
    //Important
    tabHost.setup();

    TabHost.TabSpec tab1 = tabHost.newTabSpec("First Tab Tag");
    TabHost.TabSpec tab2 = tabHost.newTabSpec("Second Tab Tag");
    TabHost.TabSpec tab3 = tabHost.newTabSpec("Third tab Tag");

    // Set the Tab name and Activity
    // that will be opened when particular Tab will be selected

    tab1.setIndicator(createTabIndicator("Tab1"));
    tab1.setContent(R.id.i_layout_1);

    tab2.setIndicator(createTabIndicator("Tab2"));
    tab2.setContent(R.id.i_layout_2);

    tab3.setIndicator(createTabIndicator("Tab3"));
    tab3.setContent(R.id.i_layout_3);

    /** Add the tabs  to the TabHost to display. */
    tabHost.addTab(tab1);
    tabHost.addTab(tab2);
    tabHost.addTab(tab3);
}

private View createTabIndicator(String text) {
    View view = LayoutInflater.from(getActivity()).inflate(R.layout.tab_indicator, null);
    TextView textView = (TextView) view.findViewById(R.id.tv_indicator_label);
    textView.setText(text);
    return view;
}

I hope this will help you. Feel free to ask any questions :)


text:
Q: delegate method cannot callback delegate method cannot callback
This is my .h file
@protocol ServiceAPIDelegate <NSObject>
@optional
- (void) onRequestLoginFinish:(NSDictionary*) dict;
@end

@interface ServiceAPI : NSObject
+ (id)shareAPI;
@property (nonatomic, weak) id <ServiceAPIDelegate> delegate_service;
;
@end

and this is .m file, i use ASIFORMData request and it is callback to requestFinished after get a response from server. but ater that, i want to send data to myviewcontroler use [self.delegate_service onRequestLoginFinish:result]; after this line. my program run normaly not bugs, not callback to function. I cannot see where errors are.
 - (void) requestLoginWithUserName:(NSString*) username andPassWord:(NSString*) password {
        NSString* urlString = [PublicInstance API_LOGIN];
        NSArray *keys = PARAMS_ARRAY;
        NSArray *objects = [NSArray arrayWithObjects:username, password, [@((int)En) stringValue], APPID, [PublicInstance getDevideID], DEVIDEOS, nil];
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys];
        NSString* signData = [PublicInstance signData:dict];
        [dict setObject:signData forKey:signKey];

        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlString]];
        [request addRequestHeader:@"Content-Type" value:@"application/json"];
        [request setValidatesSecureCertificate:NO];
        [request setRequestMethod:@"POST"];

        NSData *jsonDataToPost = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];

        [request appendPostData:jsonDataToPost];

        [request startAsynchronous];
        [request setDelegate:self];
    }

    - (void)requestFinished:(ASIHTTPRequest *)request
    {
        NSError* error = [request error];
        if(!error) {
            NSString* responseString = [request responseString];
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData;
[self.delegate_service onRequestLoginFinish:result];
}else{
            NSLog(@"%@", [error description]);

        }
    }

ServiceAPI *ShareServiceAPI;

- (id) init {
    if ([self init]) {
        ShareServiceAPI = [ServiceAPI shareAPI];
        ShareServiceAPI.delegate_service =self;
    }
}

- (void) requestLoginWithUserInfor:(UserInfor*) _userinfor {
    [ShareServiceAPI requestLoginWithUserName:_userinfor.username andPassWord:_userinfor.password];
}

#####################
and this is delegate method - but never callback (O^-oO)
- (void) onRequestLoginFinish:(NSDictionary *)dict {
    if ([[dict objectForKey:Key_Status] intValue] == 1) {
        NSLog(@"login successful");
    }
    else {
        NSLog(@"login fail....");
    }
}

Could anyone please help me?. Thank you for your time

A: You should always check if the delegate is nil or not and also check if the delegate responds to the selector as :
if(self.delegate_service){
  if([self.delegate_service repondsToSelector:@selector(onRequestLoginFinish:)]){
      [self.delegate_service onRequestLoginFinish:result];
  }
}

Through the way you can make your program safe and found the reason that the method is not called.


text:
Q: Error while using Double.parseDouble to an Object that has been caste as String I'm writing an infix evaluator program and I'm having trouble with this statement:
c = Double.parseDouble((String) operands.pop());

"operands" is a stack which stores the operands. The .pop() method returns an object of type T (Since the stack is an ArrayList of type T). Since Double.parseDouble requires a string as parameter, I have caste it to a string.
However, I am receiving this error:
java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String
What mistake have I made?

A: The exception is actually happening on the expression
(String) operands.pop()

You can't cast a double to a string using (String) because it is not a safe cast.
The compiler is telling you that the value given by operands.pop() is already a double!
If you want to do the cast, you will need to use the toString() method on it first.

A: Exception is indicating that pop method is returning object of java.lang.Double() so no need to cast and parse it. Even if you want to cast and parse because of some reason then use String.valueOf(operands.pop()).


text:
Q: Automatic Verilog code generation issue I am trying to make the generation of FSM state parametric or automatic.
I tried many ways and seems there is no way to generate the code I need.
Can someone help please?
The Code which I need to generate is part of FSM state machine, for the ST_DATA_CHECK state:
always @(posedge ui_clk_sync_rst or posedge ui_clk)
  begin
    if (rst) begin
      s_app_cmd           <= 3'b111;
      s_app_en            <= 1'b0;
end
end else begin
        case (ddr3_state)
          ST_INIT :
….
          ST_DATA_CHECK :   // This part of the code, needs to make parameteric
              if (~dwfifo_ef[0]) begin
                s_data_write_active[0] <= 1'b1 ;
              end else if (~dwfifo_ef[1]) begin
                s_data_write_active[1] <= 1'b1 ;
              end else if (~dwfifo_ef[2]) begin
                s_data_write_active[2] <= 1'b1 ;
              end else if (~d_rfifo_ef[0]) begin
                s_data_read_active[0] <= 1'b1 ;
              end else if (~d_rfifo_ef[1]) begin
                s_data_read_active[1] <= 1'b1 ;
              end
          ST_WRITE :
               …
endcase

Please notice that for example dwfifo_ef[0] and dwfifo_ef[1] bits can be 0 at the same time, so that's why I need to use priority encoder here.
Any help/idea/suggestion is welcomed about how I can make the code parametric.
Thanks
Hayk

A: You want a for loop with a break statement:
ST_DATA_CHECK :
              for (int i=0;i<$bits(dwfifi_ef);i++)
              if (~dwfifo_ef[i]) begin
                s_data_write_active[i] <= 1'b1 ;
                break;
              end

A: @dave_59 has just about solved your problem, but as you say "in my if statement there are 2 signals s_data_write_active and s_data_read_active", how about trying something like this?
ST_DATA_CHECK :
              if (|dwfifo_ef == 1'b1)
                for (int i=0;i<$bits(dwfifi_ef);i++)
                  if (~dwfifo_ef[i]) begin
                    s_data_write_active[i] <= 1'b1 ;
                    break;
                  end
              else
                for (int i=0;i<$bits(d_rfifo);i++)
                  if (~d_rfifo[i]) begin
                    s_data_read_active[i] <= 1'b1 ;
                    break;
                end

(I have not tried to compile, simulate or synthsise this, hence my phrase something like.)


text:
Q: load jquery problem inside loaded file I have the folowing script; The problem is that i can use the jquery scripts inside the loaded file
index.html

 <title>Ajax with jQuery Example</title>

ajax/test.html
test alert

The problem he will give no alert when i click on the loaded file

A: Try changing the following line:
$("A").click(function(){
     alert("test inside loaded file");
   });

to
$("A").live('click',function(){
     alert("test inside loaded file");
   });

By using the Live() method you bind to all  tags now and in the future, using .click() only binds to the matching elements that currently exist.

A: You'll need to use live() to attach the event to all elements which match the current selector, now and in the future, instead of click().
http://api.jquery.com/live/

A: use
$("A").live("click", function(){
     alert("test inside loaded file");
});


text:
Q: Laravel cannot find public dir I worked on a team and then clone the laravel/php codes from our repository. When I serve the laravel on localhost, it cannot find all the file inside the public directory and throw an error on the terminal:
[404]: GET /public/css/style.css - No such file or directory

Many answers to similar issues advise me to change the codes in the blade.php file. The problem is that I can't edit the blade.php because it works fine on other team members even though we have the same ubuntu, PHP, and laravel version and .env file.
What I have tried:

*

*Run composer install and composer update

*Try different browsers such as firefox and chromium-based browsers

*Run php artisan storage:link

*Restart apache2

*Run npm install and npm run dev
I think there is some package or something missing.
List of paths I get from dd($__data):
"path" => "/project-directory/project-name/app"
"path.base" => "/project-directory/project-name"
"path.lang" => "/project-directory/project-name/resources/lang"
"path.config" => "/project-directory/project-name/config"
"path.public" => "/project-directory/project-name/public"
"path.storage" => "/project-directory/project-name/storage"
"path.database" => "/project-directory/project-name/database"
"path.resources" => "/project-directory/project-name/resources"
"path.bootstrap" => "/project-directory/project-name/bootstrap"

A: Have you tried?
php artisan storage:link

A: You need first run
php artisan storage:link

For more details check https://laravel.com/docs/8.x/filesystem
Then you must be check your .env values.
Is correctly APP_URL=
Also in your exception is strange
/public/.../...

Reason is wrong configuration.
First check your .env values like
APP_URL=...
FILESYSTEM_DRIVER=public

then check config/filesystems.php


text:
Q: Yii2 : Memory Error My project is running fine on localhost. But if I uploaded it to my domain, it shows an error while opening a form (which contains a wbraganca dynamic form in it). The error is as follows -
PHP Fatal Error – yii\base\ErrorException

Allowed memory size of 67108864 bytes exhausted (tried to allocate 81 bytes)


text:
Q: How do I parse a JSON string where the objects are wrapped in another json array
Possible Duplicate:
I have a nested data structure / JSON, how can I access a specific value?

I have an oddly formatted JSON string that looks like this and I'm trying to access the properties but not sure how to because of how its a bunch of json arrays within objects.
This stringified value of the variable data
  console.debug(JSON.stringify(data));

looks like this
[
{
    "note": [
        {
            "type": "2",
            "cid": "36",
            "icon": "cbb4153684de41ca61c0acc7124613b3.png",
            "created_at": "1359163643"
        }
    ],
    "count": 1
}
]

For example if I want the count int i tried
 var count = parseInt(data.count);

But that just results in NaN

A: data[0].count
Just like a normal array.


text:
Q: uploading PDF files with codeigniter Hi I'm very new to stackoverflow and codeigniter so I apologize if I'm breaking any rules or etiquette with this question (I did a search of the related questions and didn't see anything that related directly to my question).
I'm trying to upload a PDF file, and I'm using the following code (codeigniter version 1.7.2):
    function test(){
        $this->load->library('upload');
        $config['upload_path'] = './assets/certificates/';
        $config['allowed_types'] = 'pdf';
        $config['max_size']    = '1000000';
        $config['file_name'] = "test";

        $this->upload->initialize($config);
        $certificateflag = $this->upload->do_upload("certificate");
        if ($this->upload->do_upload("certificate"))
            error_reporting(E_ALL);
        else{
            echo "<pre>"; Print_r($this->upload->data()); echo "</pre>";
        }
}

I don't get any errors, and it appears that the file gets uploaded, but it doesn't appear in the directory, and I can't find it anywhere on the server.  The output from the above gives me the path of where the file should be,but it's not there.
I'm using almost the exact block of code in another part for jpg files that I upload to the same directory and that works fine.
Any help/ideas are greatly appreciated.

A: at first as I see you are calling method do_upload twice, I think you need to delete one of them. after do_upload call try to call $this->upload->display_errors() method it can give you some errors. recheck the field name it should be "certificate" and check the chmod of './assets/certificates/' it should be 777.
hope this helps.


text:
Q: Lost free space in external hard drive after a crash when copying a file I'm using Linux. I was copying a huge file into my external hard drive (NTFS) when my computer crashed. After booting up again, I realized the free space on my external hard drive has dramatically decreased. I calculated the size of the folders on my external hard drive, but the used space was much greater than the size of everything that I could see in File Manager.
In these situation, I usually would make a backup everything and format my external storage, but that's not an option here.
How can I delete the corrupted file on my external hard drive?

A: I ran chkdsk in a Windows machine. It solved my problem.
ntfsfix or fsck did not help at all.


text:
Q: Writing a nested object to a module using fs does not show the nested contents (nodejs) I have an array of objects serving as a db in a file called transactions.js:
transactions.js
module.exports = {
transactions:
    [
       { "transactionID": "5520152942", "merchantName": "Thoughtstorm", "transactionAmt": 73, "transactionDt": "diam", "accountID": "0227761952", "customerID": "9174549049", "tags": [{ "tagId": "9174549049", "tagName": "Grocery" }, { "tagId": "2343432423", "tagName": "Dabfeed" }] },
       ....
    ]

In another file (mockServer.js) I require the data from transactions.js and mutate the data there as part of an API (e.g. POST, PUT, DELETE). I'm trying to update my transaction.js file every time one of those actions are performed. To do this, I've tried using fs as follows:
mockServer.js
const transactions = require('./assets/transaction');
const fs = require('fs');

// change the required transactions data

fs.writeFile('test.js', transactions.transactions, function (err, data) {
    console.log('transactions updated');
    console.log(data.toString());
});

When I run this I get in my file:
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

How would I be able to get the updated values of my transactions data into my file?
Thanks!


text:
Q: apollo-client - can I adjust apolloLinks dynamically after apollo-client instantiation? How can I update the token during runtime in an instantiated apollo-client instance?
const middleware = new ApolloLink((operation, forward) => {
    operation.setContext({
        headers: new HttpHeaders().set('Authorization', 'Bearer ' + token || null)});
        return forward(operation);
    });

apollo.createNamed(id, {
    link: from([logoutLink, middleware, http]),
    cache: new InMemoryCache(),
});

The apollo instance has a link property, which itself is a ApolloLink instance, which has the concat method.
apollo.getclient().link.concat()

But calling that concat returns a new ApolloLink instance. Is there a way to update the client instance with this new ApolloLink?

A: You don't need to create a new ApolloLink -- you pass a function to ApolloLink's constructor that's ran each time a request is made, so just handle that logic inside the function:
const middleware = new ApolloLink((operation, forward) => {
  const headers = new HttpHeaders()
  const token = getTokenFromWherever()
  headers.set('Authorization', 'Bearer ' + token)
  operation.setContext({ header })
})


text:
Q: How to install / uninstall single msi from wix custom bootstrapper bundle containing multiple MSIs like add/remove feature of Setup project? I have 2 msi in wix bundle I am using custom bootstrapper of wix 3.7. My Install,uninstall, and cancel command works perfectly. When I am trying to give functionality of add/remove msi from bundle using:
 this.ModifyCommand = new DelegateCommand(() => this.model.PlanAction(LaunchAction.Modify), () => this.state == InstallState.Present);

It's not working as expected. I am using below code to detect package
    protected void DetectPackageComplete(object sender,DetectPackageCompleteEventArgs e)
    {
        //System.Diagnostics.Debugger.Launch();

        if (e.PackageId.Equals("Setup1.msi", StringComparison.Ordinal))
        {
            this.State = e.State == PackageState.Present ? InstallState.Present : InstallState.NotPresent;
            this.model.LogMessage("Setup1.msi"+this.State.ToString());
        }

        if (e.PackageId.Equals("Setup2.msi", StringComparison.Ordinal))
        {
            this.State = e.State == PackageState.Present ? InstallState.Present : InstallState.NotPresent;
            this.model.LogMessage("Setup2.msi" + this.State.ToString());
        }
    }

After fresh install my UI shows options of Add/remove, remove, repair, reinstall for next installation by using I can uninstall single msi from my bundle but next time it not detect remaining package.
If I unstall setup2.msi it shows add/remove screen but modify button is disable and If I uninstall setup1.msi it ask for fresh installation.

A: Finally I resolve this issue I don't know whether it is right or wrong but for the time I have implemented it and it is working fine for me.
here is the code
add following event in manged BA
    private void PlanPackageBegin(object sender, PlanPackageBeginEventArgs e)
    {

        if (e.PackageId.Equals("Setup1.msi", StringComparison.Ordinal))
        {
            this.model.LogMessage("PlanPackageBegin Setup1 : " + e.State);

            string IsSetup1= this.model.BootstrapperApplication.Engine.StringVariables["chkSetup1"];

            if (IsSetup1== "True")
            {
                e.State = RequestState.Present;
            }
            else
            {
                e.State = RequestState.Absent;
            }

            this.model.LogMessage("PlanPackageBegin Setup1 : " + e.State);

        }

        if (e.PackageId.Equals("Setup2.msi", StringComparison.Ordinal))
        {
            this.model.LogMessage("PlanPackageBegin Setup2 : " + e.State);

            string IsSetup2= this.model.BootstrapperApplication.Engine.StringVariables["chkSetup2"];

            if (IsSetup2== "True")
            {
                e.State = RequestState.Present;
            }
            else
            {
                e.State = RequestState.Absent;
            }

            this.model.LogMessage("PlanPackageBegin Setup2 : " + e.State);
        }
      }

Add below line to WireUpEventHandlers() function
   this.model.BootstrapperApplication.PlanPackageBegin +=this.PlanPackageBegin;

here chkSetup1 and chkSetup2 values are setting to True or False from custom UI made for feature tree and SetBurnVariable function.
I hope it will help some one.

A: Finally I resolve this issue I don't know whether it is right or wrong but for the time I have implemented it and it is working fine for me.
here is the code following event in manged BA
    private void PlanPackageBegin(object sender, PlanPackageBeginEventArgs e)
    {

        if (e.PackageId.Equals("Setup1.msi", StringComparison.Ordinal))
        {
            this.model.LogMessage("PlanPackageBegin Setup1 : " + e.State);

            string IsSetup1= this.model.BootstrapperApplication.Engine.StringVariables["chkSetup1"];

            if (IsSetup1== "True")
            {
                e.State = RequestState.Present;
            }
            else
            {
                e.State = RequestState.Absent;
            }

            this.model.LogMessage("PlanPackageBegin Setup1 : " + e.State);

        }

        if (e.PackageId.Equals("Setup2.msi", StringComparison.Ordinal))
        {
            this.model.LogMessage("PlanPackageBegin Setup2 : " + e.State);

            string IsSetup2= this.model.BootstrapperApplication.Engine.StringVariables["chkSetup2"];

            if (IsSetup2== "True")
            {
                e.State = RequestState.Present;
            }
            else
            {
                e.State = RequestState.Absent;
            }

            this.model.LogMessage("PlanPackageBegin Setup2 : " + e.State);
        }
      }

Add below line to WireUpEventHandlers() function
   this.model.BootstrapperApplication.PlanPackageBegin +=this.PlanPackageBegin;

here chkSetup1 and chkSetup2 values are setting to True or False from custom UI made for feature tree and SetBurnVariable function.
I hope it will help some one.


text:
Q: Showing how many rows are grouped into the same field The query below shows a list of all "zip"s in a MySQL table.  It groups rows that have the same "zip".
How could I create a new variable that shows how many rows share each "zip"?
$query2 = "select zip from submission
GROUP BY zip
order by zip asc";

A: Add COUNT(*) to your select list:
SELECT zip, COUNT(*) FROM submission GROUP BY zip ORDER BY zip ASC


text:
Q: Why wouldn't VACUUM ANALYZE clear all dead tuples? We run a "manual" VACUUM ANALYZE VERBOSE on some of our larger tables after we do major DELETE/INSERT changes to them. This seems to work without issue although sometimes a table's VACUUM job will run for hours (see this post for similar issues and reasoning).
On doing more research I found that we have large tables with a large number of dead tuples even after running VACUUM. For example, here are some of the stats produced from the query in this response.
-[ RECORD 50 ]--+---------------------------
relname         | example_a
last_vacuum     | 2014-09-23 01:43
last_autovacuum | 2014-08-01 01:19
n_tup           |    199,169,568
dead_tup        |    111,048,906
av_threshold    |     39,833,964
expect_av       | *
-[ RECORD 51 ]--+---------------------------
relname         | example_b
last_vacuum     | 2014-09-23 01:48
last_autovacuum | 2014-08-30 12:40
n_tup           |    216,596,624
dead_tup        |    117,224,220
av_threshold    |     43,319,375
expect_av       | *
-[ RECORD 52 ]--+---------------------------
relname         | example_c
last_vacuum     | 2014-09-23 01:55
last_autovacuum | 2014-09-23 18:25
n_tup           |    309,831,136
dead_tup        |    125,047,233
av_threshold    |     61,966,277
expect_av       | *

The last field states that these (and most tables) would meet the threshold for autovacuum. However, having just run VACUUM ANALYZE VEBOSE on each of those tables, shouldn't the dead tuple count be 0 (or close to 0, not 125M of 300M)?
The documentation states:

VACUUM reclaims storage occupied by dead tuples.

Does this mean our VACUUM is not working?

UPDATE
Per request in repsonse here are some logs from the VERBOSE jobs:
INFO:  vacuuming "public.example_1"
INFO:  scanned index "idx_example_1_on_gp_id_and_dd_id" to remove 378386 row versions
DETAIL:  CPU 1.83s/3.42u sec elapsed 23.01 sec.
INFO:  scanned index "index_example_1_on_q_id" to remove 378386 row versions
DETAIL:  CPU 2.10s/3.91u sec elapsed 18.92 sec.
INFO:  "example_1": removed 378386 row versions in 7085 pages
DETAIL:  CPU 0.09s/0.05u sec elapsed 0.19 sec.
INFO:  index "idx_example_1_on_gp_id_and_dd_id" now contains 30347438 row versions in 291065 pages
DETAIL:  378386 index row versions were removed.
165587 index pages have been deleted, 164287 are currently reusable.
CPU 0.00s/0.00u sec elapsed 0.00 sec.
INFO:  index "index_example_1_on_q_id" now contains 30347438 row versions in 333287 pages
DETAIL:  378386 index row versions were removed.
152773 index pages have been deleted, 152757 are currently reusable.
CPU 0.00s/0.00u sec elapsed 0.00 sec.
INFO:  "example_1": found 1773 removable, 401984 nonremovable row versions in 14438 out of 1493006 pages
DETAIL:  0 dead row versions cannot be removed yet.
There were 10567 unused item pointers.
0 pages are entirely empty.
CPU 4.26s/7.51u sec elapsed 46.10 sec.
INFO:  vacuuming "pg_toast.pg_toast_17917"
INFO:  index "pg_toast_17917_index" now contains 0 row versions in 1 pages
DETAIL:  0 index row versions were removed.
0 index pages have been deleted, 0 are currently reusable.
CPU 0.00s/0.00u sec elapsed 0.00 sec.
INFO:  "pg_toast_17917": found 0 removable, 0 nonremovable row versions in 0 out of 0 pages
DETAIL:  0 dead row versions cannot be removed yet.
There were 0 unused item pointers.
0 pages are entirely empty.
CPU 0.00s/0.00u sec elapsed 0.00 sec.
INFO:  analyzing "public.example_1"
INFO:  "example_1": scanned 30000 of 1493006 pages, containing 611502 live rows and 0 dead rows; 30000 rows in sample, 40563141 estimated total rows

This table now shows 0 dead tuples in the stats. Most of the tables are much lower dead tuples this morning so either our VACUUM or autovacuum is working.
We do have a handful of tables that output nothing and yet still show dead tuples:
-[ RECORD 49 ]--+---------------------------
relname         | example_2
last_vacuum     | 2014-09-23 02:23
last_autovacuum | 2014-09-02 14:30
n_tup           |    117,914,944
dead_tup        |     34,507,388
av_threshold    |     23,583,039
expect_av       | *

A couple times I have seen in the logs where the indexes will get checked over and over again. This seems to correspond to long-running VACUUM jobs. Any idea why? Is this just working around record locking (I don't think any writes were happening during this jobs run.)
INFO:  vacuuming "public.example_2"
...
INFO:  scanned index "index_example_2_on_gsg_id_and_dd_id" to remove 2795959 row versions
DETAIL:  CPU 3.88s/16.54u sec elapsed 23.09 sec.
INFO:  scanned index "index_example_2_on_q_id" to remove 2795959 row versions
DETAIL:  CPU 6.74s/21.13u sec elapsed 84.64 sec.
INFO:  "example_2": removed 2795959 row versions in 48214 pages
DETAIL:  CPU 0.71s/0.32u sec elapsed 33.65 sec.
INFO:  scanned index "index_example_2_on_gsg_id_and_dd_id" to remove 2591011 row versions
DETAIL:  CPU 2.84s/16.11u sec elapsed 19.28 sec.
INFO:  scanned index "index_example_2_on_q_id" to remove 2591011 row versions
DETAIL:  CPU 5.46s/22.70u sec elapsed 130.57 sec.
INFO:  "example_2": removed 2591011 row versions in 45539 pages
DETAIL:  CPU 0.67s/0.38u sec elapsed 15.16 sec.
INFO:  index "index_example_2_on_gsg_id_and_dd_id" now contains 123807784 row versions in 1560915 pages
DETAIL:  108836958 index row versions were removed.
1100790 index pages have been deleted, 718471 are currently reusable.
CPU 0.00s/0.00u sec elapsed 0.25 sec.
INFO:  index "index_example_2_on_q_id" now contains 123807784 row versions in 1886087 pages
DETAIL:  110336259 index row versions were removed.
1058063 index pages have been deleted, 266983 are currently reusable.
CPU 0.00s/0.00u sec elapsed 0.07 sec.
INFO:  "example_2": found 124808 removable, 1355901 nonremovable row versions in 2086343 out of 6966379 pages
DETAIL:  0 dead row versions cannot be removed yet.
There were 7858495 unused item pointers.
0 pages are entirely empty.
CPU 595.49s/2130.13u sec elapsed 5656.34 sec.
INFO:  vacuuming "pg_toast.pg_toast_18079"
INFO:  index "pg_toast_18079_index" now contains 0 row versions in 1 pages
DETAIL:  0 index row versions were removed.
0 index pages have been deleted, 0 are currently reusable.
CPU 0.00s/0.00u sec elapsed 0.00 sec.
INFO:  "pg_toast_18079": found 0 removable, 0 nonremovable row versions in 0 out of 0 pages
DETAIL:  0 dead row versions cannot be removed yet.
There were 0 unused item pointers.
0 pages are entirely empty.
CPU 0.00s/0.00u sec elapsed 0.00 sec.
INFO:  analyzing "public.example_2"
INFO:  "example_2": scanned 30000 of 6966379 pages, containing 528443 live rows and 522 dead rows; 30000 rows in sample, 152953760 estimated total rows

A: The physical size of the table is typically (except for opportunistic pruning of removable pages from the end of the table) not reduced by running VACUUM (or VACUUM ANALYZE). You need to run VACUUM FULL to actually shrink the table.
The above is a quote from the related answer, which has more details:

*

*For alignment optimized table is bigger than original table - why?
The manual (just below your quote, actually):

Plain VACUUM (without FULL) simply reclaims space and makes it
available for re-use. This form of the command can operate in parallel
with normal reading and writing of the table, as an exclusive lock is
not obtained. However, extra space is not returned to the operating
system (in most cases);

More here:

*

*VACUUM returning disk space to operating system
You will be interested in pg_repack or pg_squeeze, which can compact tables without exclusive locks.

A: VACUUM can only remove dead tuples which are long-dead, that is, dead to all possible uses.  If you have long-lived transactions, they may prevent the recently-dead tuples from being removed.
This is an example of a situation where a long-lived transaction prevented removal:
INFO:  "pgbench_accounts": found 0 removable, 2999042 nonremovable row versions in 49181 out of 163935 pages
DETAIL:  2999000 dead row versions cannot be removed yet.

It is not really long-lived transactions, but long lived snapshots.  Certainly a long running select or insert statement will do that.  For isolation levels higher than read-committed, the whole transaction will retain the snapshot until it is down, so if some opens a repeatable read transaction and then goes on vacation without committing it, that would be a problem.  Hung-up prepared transactions will as well (if you don't know what a prepared transaction is, then you probably aren't using them).
The examples you show don't indicate a problem, but you also say the problem had resolved by then.  If this is a recurring problem, you should probably start logging the output of your VACUUM VERBOSE statements, so that you can find the information that covers the period during which the problem exists.
The multiple passes over the index are because of your maintenance_work_mem settings.  It can only remove one tuple for every 6 bytes of memory on each pass over the index, and needs to make multiple passes if you need to remove more than that.  So increasing maintenance_work_mem will help.


text:
Q: How to scroll line numbers in Label with Text widget in tkinter I have this code:
#Displaying Line Numbers
def update_line_number(event=None):
    txt = ''
    if showln.get():
        endline, endcolumn = textPad.index('end-1c').split('.')
        txt = '\n'.join(map(str, range(1, int(endline))))
    lnlabel.config(text=txt, anchor='n', font=("Arial",13))

And I have this:
textPad = Text(root, undo=True, relief='flat', font=("Arial",13))
textPad.pack(expand=YES, fill=BOTH)
scroll=Scrollbar(textPad)
textPad.configure(yscrollcommand=scroll.set, insertbackground='#cbcbcb',bg='#202020',fg='#cbcbcb', highlightbackground="#252525", highlightcolor="#252525")

lnlabel = Label(textPad,  width=3,  bg='#252525', fg='#a2a2a2', relief='flat')
lnlabel.pack(side=LEFT, anchor='nw', fill=Y)

When I add too many lines the lines are not displayed correctly only shows up to line 27,
lines are added, but in the Label widget are not moving, the lines are not allocated to each line number if I maximize the application only shows up to line 47 the Text widget scrolls but the lines don't,
what I can do?


text:
Q: Is there an optimal way to disable parent scroll I am trying to disable parent scroll, when scrolling up/down in the child component (child component is a horizontal FlatList). Is there an optimal way?
   <ScrollView scrollEnabled={scrollEnabled}>
    <Header />
    <FlatList
      horizontal={true}
      data={cards}
      renderItem={() => (
        <Pressable onPressIn={() => setScrollEnabled(false)} onPressOut={() => setScrollEnabled(true)}>
          <ScrollingCard />
        </Pressable>
      )}
      keyExtractor={(item) => item.toString()}
    />
    {cards.map((item) => <ScrollingCard key={`vertical-${item}`} item={item} type="Vertical" />)}
  </ScrollView>

A: Declare a state:-
const [data, setData] = useState({
    username: "Mark White",
    enableScrollViewScroll: true
})

Handle state when scroll:-
const onEnableScroll = (value) => {
    setData({
        ...data,
        enableScrollViewScroll: value
    })
}

Inside component:-
         <ScrollView
            showsVerticalScrollIndicator={false}
            scrollEnabled={data.enableScrollViewScroll}>
           <View>
                <FlatList
                    onTouchStart={() => {
                        onEnableScroll(false);
                    }}
                    onMomentumScrollEnd={() => {
                        onEnableScroll(true);
                    }}
                  ...
                />
            </View>
         </ScrollView>

A: export const ScrollEnabledContext = createContext(null);

const Parent = () => {
    const ref = useRef(null);

    const setIsEnabled = (bool) => {
        ref.current?.setNativeProps({ scrollEnabled: bool });
    };

    return (
        <ScrollEnabledContext.Provider value={setIsEnabled}>
            <ScrollView ref={ref} nestedScrollEnabled={true}>
                <ChildScrollView />
            </ScrollView>
        </ScrollEnabledContext.Provider>
    );
};

const ChildScrollView = () => {
    const value = useContext(ScrollEnabledContext);

    return (
        <ScrollView onTouchStart={() => value(false)} onTouchEnd={() => value(true)}>
            ....
        </ScrollView>
    );
};

It works without any re-renders and works way faster than setting state.


text:
Q: subsetting a Python DataFrame I am transitioning from R to Python. I just began using Pandas. I have an R code that subsets nicely:
k1 <- subset(data, Product = p.id & Month < mn & Year == yr, select = c(Time, Product))

Now, I want to do similar stuff in Python. this is what I have got so far:
import pandas as pd
data = pd.read_csv("../data/monthly_prod_sales.csv")

#first, index the dataset by Product. And, get all that matches a given 'p.id' and time.
 data.set_index('Product')
 k = data.ix[[p.id, 'Time']]

# then, index this subset with Time and do more subsetting..

I am beginning to feel that I am doing this the wrong way. perhaps, there is an elegant solution. Can anyone help? I need to extract month and year from the timestamp I have and do subsetting. Perhaps there is a one-liner that will accomplish all this:
k1 <- subset(data, Product = p.id & Time >= start_time & Time < end_time, select = c(Time, Product))

thanks.

A: I'll assume that Time and Product are columns in a DataFrame,  df is an instance of DataFrame, and that other variables are scalar values:
For now, you'll have to reference the DataFrame instance:
k1 = df.loc[(df.Product == p_id) & (df.Time >= start_time) & (df.Time < end_time), ['Time', 'Product']]

The parentheses are also necessary, because of the precedence of the & operator vs. the comparison operators. The & operator is actually an overloaded bitwise operator which has the same precedence as arithmetic operators which in turn have a higher precedence than comparison operators.
In pandas 0.13 a new experimental DataFrame.query() method will be available. It's extremely similar to subset modulo the select argument:
With query() you'd do it like this:
df[['Time', 'Product']].query('Product == p_id and Month < mn and Year == yr')

Here's a simple example:
In [9]: df = DataFrame({'gender': np.random.choice(['m', 'f'], size=10), 'price': poisson(100, size=10)})

In [10]: df
Out[10]:
  gender  price
0      m     89
1      f    123
2      f    100
3      m    104
4      m     98
5      m    103
6      f    100
7      f    109
8      f     95
9      m     87

In [11]: df.query('gender == "m" and price < 100')
Out[11]:
  gender  price
0      m     89
4      m     98
9      m     87

The final query that you're interested will even be able to take advantage of chained comparisons, like this:
k1 = df[['Time', 'Product']].query('Product == p_id and start_time <= Time < end_time')

A: Just for someone looking for a solution more similar to R:
df[(df.Product == p_id) & (df.Time> start_time) & (df.Time < end_time)][['Time','Product']]

No need for data.loc or query, but I do think it is a bit long.

A: I've found that you can use any subset condition for a given column by wrapping it in []. For instance, you have a df with columns ['Product','Time', 'Year', 'Color']
And let's say you want to include products made before 2014. You could write,
df[df['Year'] < 2014]

To return all the rows where this is the case. You can add different conditions.
df[df['Year'] < 2014][df['Color' == 'Red']

Then just choose the columns you want as directed above. For instance, the product color and key for the df above,
df[df['Year'] < 2014][df['Color'] == 'Red'][['Product','Color']]

A: Regarding some points mentioned in previous answers, and to improve readability:

No need for data.loc or query, but I do think it is a bit long.
The parentheses are also necessary, because of the precedence of the & operator vs. the comparison operators.

I like to write such expressions as follows - less brackets, faster to type, easier to read. Closer to R, too.
q_product = df.Product == p_id
q_start = df.Time > start_time
q_end = df.Time < end_time

df.loc[q_product & q_start & q_end, c('Time,Product')]

# c is just a convenience
c = lambda v: v.split(',')

A: Creating an Empty Dataframe with known Column Name:
Names = ['Col1','ActivityID','TransactionID']
df = pd.DataFrame(columns = Names)

Creating a dataframe from csv:
df = pd.DataFrame('...../file_name.csv')

Creating a dynamic filter to subset a dtaframe:
i = 12
df[df['ActivitiID'] <= i]

Creating a dynamic filter to subset required columns of dtaframe
df[df['ActivityID'] == i][['TransactionID','ActivityID']]


text:
Q: Why does the original Game Boy support four shades of grey? Why does the Game Boy specifically support four shades of grey, why not three or five? Is there something about the hardware that made four colours optimal?
Was there a precedent to using four shades of grey in computer graphics before the Game Boy, or was this an invention of the system?

A: While Nolonar's answer is true from a technical perspective, it's not the actual reason why the developers chose to go with a monochrome system. Gunpei Yokoi, the creator of the Game Boy, intentionally designed the system monochrome to force games to be more abstract, thus preventing players from getting too caught up in details.  As he put in in a 1997 interview:

The technology was there to do color. But I wanted us to do black and white anyway. If you draw two circles on a blackboard, and say "that's a snowman", everyone who sees it will sense the white color of the snow, and everyone will intuitively recognize it's a snowman. That's because we live in a world of information, and when you see that drawing of the snowman, the mind knows this color has to be white. I became confident of this after I tried playing some Famicom games on a black and white TV. Once you start playing the game, the colors aren't important. You get drawn, mentally, into the world of the game.

The full interview can be read here: http://www.techspot.com/news/61318-console-gaming-now-fascinating-1997-interview-nintendo-legendary.html

A: The first computers were monochrome; they only knew 2 colors, as for each pixel, you only had 1 bit:
0
1

As for the Gameboy, it supported 2 bits per pixel, which gives us 4 possible colors to choose from:
00
01
10
11

How did the makers decide on four and why not three

Because they already had 4 colors to choose from. When people have 10 fingers, why not count up to 10?

or five?

Because that would've required they increase the screen's bit depth to 3 bits per pixel, which would have given us 8 colors to choose from. Why didn't they do it? Probably for performance reasons. As you increase the amount of bits per pixel, you increase the amount of data to process, which in turn requires more powerful hardware to process.

Was there a precedent to using four shades of grey in computing graphics before the Gameboy, or was this an invention of the system?

Of course there were precedents.

CGA, gray-scale early NeXTstation, color Macintoshes, Atari ST.

A: While I haven't studied the internal workings of the Game Boy, I have designed and built a controller for a four-gray-level LCD, for use with display panels that were designed for on/off control only.  To get four-level grayscale from a panel that's designed for on-off control, one must be able to do the following:

*

*Switch instantly between two display buffers.

*Time the display switching so that the first buffer will be shown for one scan, the second for two, the first for one, the second for two, etc.

*Set the refresh rate about 3x as fast as would otherwise be needed to avoid flicker [in practice, it can be a bit less than 3x as fast; I used 100Hz].
Adding the ability to switch between two display buffers at the proper times and boosting the refresh rate are both things that can be done quite cheaply.  While the same approach might in theory be used to achieve an eight-level or sixteen-level grayscale, doing those things would require significantly increasing display refresh rates.  While pushing things to eight gray levels or even sixteen might be feasible, the comparative benefit obtained by doing so would be slight compared with the benefits of going from on-off control to four-level control.
[BTW, some common controllers have the ability to automatically flip between two buffers, but show each one for two scans rather than doing a 1-2-1-2 pattern; I don't know why they don't have 1-2-1-2 since it provides four gray levels rather than three, doesn't require quite as high a refresh rate, and is at least as effective if not moreso at preventing display polarization].


text:
Q: C++ - Competing cast/assignment If I have 2 classes A and B and wish to implement conversion from A to B, I can see 2 possibilities.

1st possibility
class A {
    // Some attributes, methods
    operator B() const {
        // Conversion from A to B
    }
}

class B {
    // Some attributes, methods
}

2nd possibility
class A {
    // Some attributes, methods
}

class B {
    // Some attributes, methods
    B& operator =(const A& src) {
        // Conversion from A to B
    }
}

Both these methods allow to run the following code:
Executed code
A instA;
B instB;

instB = instA; // Ok

Now let's imagine I implement both functions (cast to B in class A and operator = from A in class B:
3rd possibility
class A {
    // Some attributes, methods
    operator B() const {
        // Conversion from A to B - Code 1
    }
}

class B {
    // Some attributes, methods
    B& operator =(const A& src) {
        // Conversion from A to B - Code 2
    }
}

assuming Code 1 and Code 2 have the same effect (or even different effects, why not).
My questions are:

*

*If competing cast/assignment methods are provided, which one would be chosen first when doing implicit cast?

*Is there any interest implementing both competing cast/assignment methods?

*Perhaps this would even be a good idea to call operator = of class B in B() cast operator of class A?

A:
If competing cast/assignment methods are provided, which one would be chosen first when doing implicit cast?

Given the choices, the operator=() will be given the first preference since it does not require the argument, the RHS, to be converted.

Is there any interest implementing both competing cast/assignment methods?

No. That's best avoided to prevent confusion.

Perhaps this would even be a good idea to call operator = of class B in B() cast operator of class A?

If you must support both, then, yes, it would be a good idea to do that.


text:
Q: Why can't turn off my win10 with power button on the front panel in my home computer main chassis? I can turn off my win10 in the menu  power--shut down,it will never be turned on automatically.

The strange things happen when i press the power button on the front panel in my home computer main chassis,my pc will be turned off and then immediately automatically turned on !
I google searched some article ,still can't solved then!
The main setting in my win10.


text:
Q: Powershell.exe process running as system on several domain machines pushing cpu usage to 100% I have several machines on a domain all running a 'powershell.exe' process as system and its smashing the pants off the servers. They're all 100% CPU and, naturally, ground to a halt.
This is Windows server 2012 R2 on HyperV virtual machines.
Killing the process fixes the issue for a while, but then later the CPU smashes the ceiling again and everything just grinds to a halt.
This powershell process was also running on the underlying hypervisor, causing further issues.
Any thoughts?

A: You need to determine which script PowerShell is running that is causing the issue. You should be able to see that by adding the "CommandLine" column in task manager details view, or you could also look at it like this:
gwmi win32_process | where {$_.processName -eq "Powershell.exe"} | select -prop processName,ProcessId,commandLine

The CommandLine field will contain the script being run by that PowerShell process.


text:
Q: Azure VM: How to send Start/Stopped/Restart Events to Webapp I have a Webapp that writes the status of Azure VMs in a DB. I want to be able to have the DB update automatically every time a VM is started/stopped/restarted. How do I set up a trigger that POST to my Webapp when the VM is started/stopped/restarted?   I'm using the Azure Python SDK.  Thank you.

A: You don't need to write code to achieve this you could use EventGrids in Azure linked to a logic app which would write straight into your database. Here is an example of how to set up an EventGrid to send emails when linked to a logic app. This is an example in how to connect a Logic App to a database. The combination of these two examples will allow you to use Azure native technologies to achieve your goal.
Alternatively instead of writing straight to the database you could use the logic app to POST to your website using one of the connectors.
Hope that helps.


text:
Q: Appending datetime rows and forward filling data in pandas dataframe Beginner panda/python user.
I am using 24 hour data in pandas dataframe, however there is often no data for the last few minutes of the day.
I simply need to append rows onto each file until the last Timestamp reaches 23.59, and forward fill those last few minutes with data. So this:
    19-12-2016 00:00    2   0.003232323
    ...
    19-12-2016 23:53    2   0.002822919
    19-12-2016 23:54    4   0.002822919
    19-12-2016 23:55    1   0.002822919

becomes:
    19-12-2016 00:00    2   0.003232323
    ...
    19-12-2016 23:53    2   0.002822919
    19-12-2016 23:54    4   0.002822919
    19-12-2016 23:55    1   0.002822919
    19-12-2016 23:56    1   0.002822919
    19-12-2016 23:57    1   0.002822919
    19-12-2016 23:58    1   0.002822919
    19-12-2016 23:59    1   0.002822919

Unfortunately the code I am using for this is really long and I can't pinpoint exactly where I could amend this.

A: you can:
reindex your data as
idx = pd.date_range('2016-12-19', periods=1440, freq='T')
df = df.reindex(idx)

and then forward fill any missing values using df.mycol.ffill()

A: A generic solution to multiple days of data in a single frame might look something like this. Get the start and end date and then reindex the entire frame and fill in the missing values.
start = df.index.min().date()
end = df.index.max().date() + pd.Timedelta(1, 'D')
df.reindex(pd.date_range(start, end, freq='T', closed='left')).fillna(method='ffill')


text:
Q: pushbullet curl w/ access token doesn't work I generated an access token at https://www.pushbullet.com/#settings/account but it doesn't seem to work:
$ curl --http1.1 --header "Access Token: $PUSHBULLET_API_TOKEN"  https://api.pushbullet.com/v2/users/me | jq .
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   176  100   176    0     0   1093      0 --:--:-- --:--:-- --:--:--  1086
{
  "error": {
    "code": "invalid_access_token",
    "type": "invalid_request",
    "message": "Access token is missing or invalid.",
    "cat": "(=^・ω・^)y="
  },
  "error_code": "invalid_access_token"
}

Any suggestions for what might be going wrong?  The only deviation from the example in the API docs is the http1.1 option, which i added because http2.0 support seems broken:
$ curl --header "Access Token: $PUSHBULLET_API_TOKEN"  https://api.pushbullet.com/v2/users/me  | jq .
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0  1555    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (92) HTTP/2 stream 0 was not closed cleanly: PROTOCOL_ERROR (err 1)


text:
Q: Milky Way: where does it end? The milky way galaxy, as is typical for spirals (and others?), has a relatively flat rotation curve except very near the center:

Eventually, at great enough distances, almost the entire mass of the galaxy will be enclosed and the rotation curve must become nearly Keplerian and fall off (dark matter, if it is important at all at these scales, would make the curve fall off even faster). Do we have any data that shows the curve becoming nearly Keplerian at great distances? Do we even have an idea of what that distance would be?

A: Over at astronomy they have a post looking at this from the astronomical perspective. There is no clear boundary and it comes down to arbitrary definitions or decisions.
The rotation curve has been measured out to almost 100kpc. See this article for a nice and current review. From that paper comes this figure:

You can see that we have measurements beyond 100kpc, with the curve clearly decreasing once you go beyond 20 or 30kpc. (Don't think much of the two data points going back up at ~200kpc, that is well within the uncertainty and thus not significant)
For comparison, note that the Andromeda Galaxy is over 700kpc away. Since the two galaxies have similar mass, you could also argue that the Milky Way ends half way between us and there.

A: Galaxies generally have quite flat rotation curves even at very large distances (much farther away from all the stars forming the galaxy).
At such distances most if the ordinary matter of the galaxy is just a heated gas. The rotation velocity of this gas is measured by observing the Doppler shift of some particular splectral lines.
Astronomers explain these rotation curves by means of a dark matter halo which surrounds the galaxies at large distances.


text:
Q: C++ cout behavior / order of execution I was looking at some example questions of CPPInstitute's CPA-21-01 exam, and am a bit confused about Question #11.
It states the following:

What is the output of the following program?

#include <iostream>

using namespace std;

class A {
public:
    A() {
        a.a = a.b = 1;
    }
    struct { int a,b; } a;
    int b(void);
};

int A::b(void)
{
    int x=a.a;
    a.a=a.b;
    a.b=x;
    return x;
}

int main(void) {
    A a;
    a.a.a = 0;
    a.b();
    cout << a.b() << a.a.b << endl;

    return 0;
}

A. The program will cause a compilation error
B. 10
C. 01
D. 11

It can be boiled down a more minimal example:
int swap_and_return(int& a, int& b) {
    std::swap(a,b);
    return a;
}

int main() {

    int a = 0;
    int b = 1;

    cout << swap_and_return(a,b) << a << endl;

    return 0;
}

So far so good; The answer key says it's B.
Let's say you choose D.
According to this, the execution order is arbitrary:

15) In a function call, value computations and side effects of the initialization of every parameter are indeterminately sequenced with respect to value computations and side effects of any other parameter.

There has already been a similar question here
I think the cout line can be translated into cout.operator<<(a.b()).operator<<(a.a.b);, meaning there should be a sequence point and behavior should be deterministic?
In practice, the following results are obtained:
MS cl.exe, Debug: 10
MS cl.exe, Release: 11
GCC, C++11: 11
Clang: 11
Needless to say, I am a bit confused now, because they say it's answer B when it appears that indeed order of execution is arbitrary.
Could anyone please explain whether I am right about the execution order and what it should be then?
Thanks!

A: Before C++17, you're right, and the quiz does not allow for the right answer.
Since then, the answer is deterministic.


text:
Q: Laravel 5.2 CORS, GET not working with preflight OPTIONS The dreaded CORS Error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
  the remote resource at http://localhost/mysite/api/test. (Reason: CORS
  header 'Access-Control-Allow-Origin' missing).

Laravel route:
$router->group(['prefix' => 'api', 'middleware' => 'cors'], function ($router) {
    $router->get('/test', 'MyController@myMethod');
});

Laravel Cors Middlware:
public function handle($request, Closure $next)
    {
        header('Access-Control-Allow-Origin: *');

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization'
        ];
        if ($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach ($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }

Laravel Kernel:
 protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'cors' => \App\Http\Middleware\CORS::class
    ];

Relevant .htaccess:
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Relevant Vue.js:
 new Vue({
        el: '#app',
        data: {
           //data here
        },
        http: {
            headers: {
                "Authorization": "Basic " + "apiKeyHere"
            }
        },
        methods: {
            mymethod: function (e)
            {
                e.preventDefault();
                this.$http.get('http://localhost/mysite/api/test').then(
                        function (response)
                        {
                          //do something
                        }
                )
            }
        }
    });

If I take out the Authorization header option the request works.
I've also tried https://github.com/barryvdh/laravel-cors but still no joy.
Any help appreciated!

A: The issue arises from the preflight request, indeed, but the way of handling requires some additional explanation, when we're talking about Laravel - mainly OPTIONS request is routed (something the other answers rather do PHP way, than Laravel way), so, you have to add this to your routes for it to be successfull:
Route::options('/{any}', function(){ return ''; })->where('any', '.*');
Now, let's cater for all other methods - create CORS middleware:
namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE');
    }
}

And finally, for given route, use that middleware:
Route::put('/test', function(){ echo('test'); })->with('cors');

A: You can bypass this one without using any middleware like Barryvdh\Cors for Laravel which was not working properly with JWT AUTH , I have added the following statements in the index.php in Laravel just before the Kernel instantiation
header('Access-Control-Allow-Origin: http://localhost:8001');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token,Authorization');
header('Access-Control-Allow-Credentials: true');

add this one before
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

this should work properly with JWT AUTH also. Kindly note that in Access-Control-Allow-Headers you should include Authorization otherwise your accesstoken will not be allowed with Authorization header therefore JWT AUTH will fail. Happy Coding.

A: Clearly not the ideal solution but it WORKS. I've added this to the top of my routes.php file:
header('Access-Control-Allow-Origin: *');
header( 'Access-Control-Allow-Headers: Authorization, Content-Type' );

It would be nice to get this working without a hack... alas.
UPDATE: It turned out to be IIS related. I ended up setting the headers in the web.config file and now CORS works without hacking the routes.php file.
<httpProtocol>
    <customHeaders>
       <add name="Access-Control-Allow-Headers" value="Origin, Authorization, X-Requested-With, Content-Type, Accept" />
       <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />
    </customHeaders>
</httpProtocol>

If you want to restrict access, you can add outbound rules:
      <outboundRules>
          <clear />
                <rule name="AddCrossDomainHeader">
                    <match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
                        <add input="{HTTP_ORIGIN}" pattern="(http(s)?://((.+\.)?somesite\.com|(.+\.)?anothersite\.org))" />
                    </conditions>
                    <action type="Rewrite" value="{C:0}" />
                </rule>
      </outboundRules>

A: I have solved my problem easily by adding headers in bootstrap/app.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');

A: I solve my problem just adding these line on my routes.php Laravel 5.2
For greater then 5.2 in routes/web.php
header('Access-Control-Allow-Origin:  *');
header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Origin, Authorization');

OR register Cors middleware in global HTTP middleware stack
protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\CorsMiddleware::class
];

A: Laravel 7 or lower:
Your middleware is ok but you need to register Cors middleware in global HTTP middleware stack.
protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\CorsMiddleware::class
];

Laravel 8 or higher:

All CORS settings may be configured in your application's config/cors.php configuration file. The OPTIONS requests will automatically be handled by the HandleCors middleware that is included by default in your global middleware stack.

Link to the official documentation

A: My solution:
$router->group(['prefix' => 'api', 'middleware' => 'cors'], function ($router){
    $router->options('{param1?}/{param2?}/{param3?}', function () {});
});

A: This answer is based on this article.
barryvdh/laravel-cors middleware library, can be used to fix the problem(Cross-Origin Resource Sharing).
step 1 Install it:
composer require barryvdh/laravel-cors

step 2 Releasing vendor files of the library:
php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

step 3 The command ran in step 2 will copy a cors.php file to config directory, which looks like this:

return [

/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value.
|
*/

'supportsCredentials' => false,
'allowedOrigins' => ['*'],// ex: ['abc.com', 'api.abc.com']
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],// ex: ['GET', 'POST', 'PUT', 'DELETE']
'exposedHeaders' => [],
'maxAge' => 0,

];

For allowedOrigins the value can either be ['*'] which indicated that the origin of request can be from any domain, or an array of specific domains which can be the origins that we will allow to send request to our api, like this ['first.com', 'second.com', 'register.third.com']
and also allowedMethods can either be ['*'] or a list of allowed HTTP verbs for instance ['POST', 'GET']
step 4 Registering the cors middleware. Open app/Http/kernel.php and add the HandleCors class to $routeMiddleware like this:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'cors' => \Barryvdh\Cors\HandleCors::class, // add this line to enable cors to your routes
];

step 5 Now you can add the laravel-cors middleware to any route that you want. For instance in Routes/api.php I will do this:
Route::apiResource('category', 'CategoryController')->middleware('cors');
Route::apiResource('product', 'ProductController')->middleware('cors');

A: Even if it works to put your middleware directly into $middleware instead of $routeMiddleware or to simply define the headers globally in the app.php, it is a horrible decision, because it will expose all endpoints with the new CORS policy, in case you only want to make a part of your API public to third party solutions.
The better solution is to only allow OPTIONS calls to go through on all endpoints and still redirect other HTTP methods through the $routeMiddleware to be able to limit the CORS policy only on a subset of endpoints.
So, build two middlewares:
Cors.php
 <?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
          ->header('Access-Control-Allow-Origin', '*')
          ->header('Access-Control-Allow-Methods', '*')
          ->header('Access-Control-Allow-Headers', '*');
    }
}

OptionsCors.php
<?php

namespace App\Http\Middleware;

use Closure;

class OptionsCors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      if($request->isMethod('OPTIONS')) {
        return $next($request)
          ->header('Access-Control-Allow-Origin', '*')
          ->header('Access-Control-Allow-Methods', '*')
          ->header('Access-Control-Allow-Headers', '*');
      }
      return $next($request);
    }
}

app/Http/Kernel.php
<?php
namespace App\Http
{
    class Kernel extends \Illuminate\Foundation\Http\Kernel
    {
        protected $middleware = [
            // ...
            'App\Http\Middleware\OptionsCors',
        ];
        protected $middlewareGroups = [
            'web' => [
                 // ...
            ],
            'api' => [
                'App\Http\Middleware\UseApiGuard',
                'throttle:60,1',
                'bindings'
            ]
        ];
        protected $routeMiddleware = [
            // ...
            'cors' => 'App\Http\Middleware\Cors',
        ];
    }

}

Now in your routes you have full control about what endpoints will be exposed with your tightened CORS policy:
Route::namespace('Api')->middleware(['cors'])->group(function () {

    Route::get('api/im_open', 'TestController@ping');

});
Route::namespace('Api')->group(function () {

    Route::get('api/im_closed', 'TestController@ping');

});


text:
Q: how to pass a hostname as env var with rancher server I am using docker 1.12 and rancher server 1.5.9. I am trying to create a stack in rancher to deploy and orchestrate my app. My issue is that I need to pass as env var the hostname of the host where the container will be running.
Since I have only one image that will be used to create one kind of container on several host (let's say 2 for the tests) I can't pass it like HOSTNAME=myhostname. The value needs to be a var which will be set with the docker host.
Does anyone know how to do that with the rancher server UI?
Does anyone know how rancher retrieve the hostname when adding a custom host?
Can we use the entry point or CMD to do that?

A: Having an /etc/hosts on the machine that prioritizes the desired name over localhost helped in my case. Obviously, also have an /etc/hostname that agrees with /etc/hosts.
I am using container linux. So for me, it looks like so in the ct-config before converting to ignition.
storage:
  files:
    - filesystem: "root"
      path:       "/etc/hostname"
      mode:       0644
      contents:
        inline: ${hostname}
    - filesystem: "root"
      path:       "/etc/hosts"
      mode:       0644
      contents:
        inline:  "127.0.0.1 ${hostname} localhost\n
                 ::1 ${hostname} localhost"

Just be sure to have the above before you run the rancher registration line.
sudo docker run --rm --privileged \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /var/lib/rancher:/var/lib/rancher \
rancher/agent:v1.2.7 https://myrancher/v1/scripts/TOKEN


text:
Q: Trigger a Alert From server side Asp.net MVC Using signal R     [HttpPost]
    [ValidateInput(false)]
    public ActionResult UpdateMyData(User model)
    {
        _service.add(model);
       Task.Factory.StartNew(() =>
                {
                    _Data.ProcessBigTask();

                });
    return new JsonResult { Data = "Success") };
    }

After complete this Task ( _Data.ProcessBigTask();) i need a automatic alert on browser

A: Create new function on client side and call it.
You can create and invoke client function like this.
Client Side function
var chat = $.connection.myHub;

chat.client.getUpdateStatus = function (msg) {
      alert(msg);
};

HUB
public ActionResult UpdateMyData(User model)
{
    Clients.All.getUpdateStatus ("Status :" + msg);
}


text:
Q: Counting variable not working and I'm not sure why im trying to make a variable that counts up but it comes up with this error:
local variable 'cobblestone' referenced before assignment
@bot.command()
async def mine(ctx):
  cobblestone = cobblestone + int('1')
  await ctx.send('the sever now has',cobblestone,'cobblestone')

I'm pretty new to coding, so if the answer is really obvious, I'm sorry

A: cobblestone only exists within the function. You need it to be global.  It also doesn't exist when you add cobblestone to it at first.  You want something like this:
cobbleston = 0

@bot.command
async def mine(ctx):
  global cobblestone
  cobblestone += 1
  await ctx.send('the sever now has',cobblestone,'cobblestone')

Note that the easiest way to get an int.... is to write an int, rather than cast a string.
Global variables
If a variable is defined in global scope it is available inside a function (or other inclosing scope) unless shadowed.  So this works:
x = 0

def incr():
    print(x)

incr()

But Python doesn't allow you to reassign global variables without explicitly declaring them as global:
x = 0

def incr():
    x += 1
    print(x)

incr()

Raises UnboundLocalError, whereas:
x = 0

def incr():
    global x
    x += 1
    print(x)

incr()

Behaves as expected.
If x is a muteable, this is not needed, because the name x is never changed: we don't move x to point at another integer, but we mutate it.  So this is fine:
x = [0] # lists are muteable

def incr():
    x[0] += 1
    print(x)

incr()

A: You have to create that variable outside the function to do this.
like this:
cobblestone = 0

@bot.command()
async def mine(ctx):
  cobblestone += 1
  await ctx.send('the sever now has',cobblestone,'cobblestone')

A: An alternative to defining a global outside the function is to create an attribute in the function itself:
>>> def mine():
...     try:
...         mine.cobblestone += 1
...     except AttributeError:
...         mine.cobblestone = 1
...     print(mine.cobblestone)
...
>>> mine()
1
>>> mine()
2
>>> mine()
3
>>> mine()
4


text:
Q: In bash, grep for a line beginning with \, and assign the result using backticks In bash, I'm trying to grep a file for a line beginning with a \, and return the result using backticks.
For example:
echo \\Hello > myFile
out=`cat myFile | grep '^\\Hello'`
echo $out

returns nothing, even though
cat myFile | grep '^\\Hello'

returns, as epected.
\Hello

This seems extremely odd shell behavior.    In particular, the anologous command sequence in tcsh does what one would expect:
set out=`cat myFile | grep '^\\Hello'`; echo $out

returns
\Hello

Could somebody explain what's going on please?    Thanks

A: Read http://mywiki.wooledge.org/BashFAQ/082 and especially

Backslashes inside backticks are handled in a non-obvious manner

:
`...`

is the legacy syntax required by only the very oldest of non-POSIX-compatible bourne-shells. There are several reasons to always prefer the $(...) syntax, so :
echo \\Hello > myFile

and instead of
out=$(cat myFile | grep '^\\Hello')

simplify it a bit :
out=$(grep '^\\Hello' myFile)

then
echo $out

And  "Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See http://mywiki.wooledge.org/Quotes , http://mywiki.wooledge.org/Arguments and http://wiki.bash-hackers.org/syntax/words .
So finally :
echo \\Hello > myFile
out="$(grep '^\\Hello' myFile)"
echo "$out"


text:
Q: Razor encodes everything Razor is encoding every unicode character. How to prevent that?
Example:
This is my Razor:
@Html.DropDownListFor(model => model.Category,
    (IEnumerable<SelectListItem>) ViewBag.CategoriesList,
    "موضوع صفحه را انتخاب کنید...", new{
        @class = "form-control some-css"
    })

And this the rendered html:
<select class="form-control some-css" id="Category" name="Category">
    <option value="">
        موضوع صفحه را انتخاب کنید...
    </option>
    <option value="SomeValue">
        موزه
    </option>
    <!-- some other options -->
</select>

A: You could use Html.Raw()
@Html.DropDownListFor(model => model.Category,
    (IEnumerable<SelectListItem>)ViewBag.CategoriesList,
    Html.Raw("موضوع صفحه را انتخاب کنید..."), new
    {
        @class = "form-control some-css"
    })


text: Q: Is it possible to export Map Service to cache or to raster I've added The server under GIS Servers  in ArcCatalog. At that server i have Map Service of an orthophoto. is it possible to export that that Map Service to raster or to cache ?


text:
Q: Is it possible to switch to a database on a linked server using a 'USE' statement in SQL Server 2005? I've tried the obvious:
USE linkedServerName.databaseName

Which gives me the error:
`Could not locate entry in sysdatabases for database 'linkedServerName'.

If something like this were possible, it'd save me a bunch of clicking around in management studio!

A: Linked server definitions are designed for use as part of the four-part naming convention:
[LinkedServerDefinition.][DatabaseName.][SchemaName.]DatabaseObject

for example, OtherServer.Database.dbo.MyTable
They might have other uses, but with the USE statement is not one of them.
Would
SELECT * from LinkedServerDefinition.master.sys.databases

help in identifying what databases are "over ther"?