问:
How to set an alarm at a specific date at any chosen time?
So this is my code, it works but i can't set an alarm except at 12:00 AM
i want the user to set an alarm at a specific date, like the one given below but to be able to set it at any time of the day not just midnight...can anyone help ?

Calendar now = Calendar.getInstance();

```<code>    pickerDate.init(
            now.get(Calendar.YEAR),
            now.get(Calendar.MONTH),
            now.get(Calendar.DAY_OF_MONTH),
            null);

    pickerTime.setCurrentHour(now.get(Calendar.HOUR_OF_DAY));
    pickerTime.setCurrentMinute(now.get(Calendar.MINUTE));
    buttonSetAlarm = (Button)findViewById(R.id.setalarm);
    buttonSetAlarm.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View arg0) {

            Calendar current = Calendar.getInstance();

            Calendar cal = Calendar.getInstance();
            cal.set(pickerDate.getYear(),
                    pickerDate.getMonth(),
                    pickerDate.getDayOfMonth(),
                    pickerTime.getCurrentHour(),
                    pickerTime.getCurrentMinute(),
                    0);

            if(cal.compareTo(current) <= 0){

                Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show();
            }else{
                setAlarm(cal);
            }

        }});
}

private void setAlarm(Calendar targetCal){

    String pattern = "MM/dd/yyyy";
    SimpleDateFormat format = new SimpleDateFormat(pattern);

    Calendar cal = Calendar.getInstance();
    cal.set(pickerDate.getYear(),
            pickerDate.getMonth(),
            pickerDate.getDayOfMonth(),
            pickerTime.getCurrentHour(),
            pickerTime.getCurrentMinute(),
            0);
    cal.set(Calendar.MILLISECOND,0);

    try {
    Date date12_25 = format.parse("12/25/2017");

    Lebanon.put(date12_25,"Christmas Day");
        for(Date k : Lebanon.keySet()){

            if(cal.getTime().equals(k)){

                String val = (String)Lebanon.get(k);
                info.setText("Your alarm is set for :"+k+", on:  "+val);
            }

        }

    } catch (ParseException e) {
        e.printStackTrace();
    }format.format(new Date());

    Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
    alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}
</code>```

答:
Use BroadcastReceiver.

```<code>public class MyBroadcastReceiver extends BroadcastReceiver {
    MediaPlayer mp;
    @Override
    public void onReceive(Context context, Intent intent) {
        mp=MediaPlayer.create(context, R.raw.alrm   );
        mp.start();
        Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
    }
}
</code>```

Start Alarm-

```<code>//  i = int time from calander.
     int i = 12;
            Intent intent = new Intent(this, MyBroadcastReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                                          this.getApplicationContext(), 234324243, intent, 0);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                                          + (i * 1000), pendingIntent);
            Toast.makeText(this, "Alarm set in " + i + " seconds",Toast.LENGTH_LONG).show();
</code>```

Body:
So this is my code, it works but i can't set an alarm except at 12:00 AM
i want the user to set an alarm at a specific date, like the one given below but to be able to set it at any time of the day not just midnight...can anyone help ?

Calendar now = Calendar.getInstance();

    pickerDate.init(
            now.get(Calendar.YEAR),
            now.get(Calendar.MONTH),
            now.get(Calendar.DAY_OF_MONTH),
            null);

    pickerTime.setCurrentHour(now.get(Calendar.HOUR_OF_DAY));
    pickerTime.setCurrentMinute(now.get(Calendar.MINUTE));
    buttonSetAlarm = (Button)findViewById(R.id.setalarm);
    buttonSetAlarm.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View arg0) {

            Calendar current = Calendar.getInstance();

            Calendar cal = Calendar.getInstance();
            cal.set(pickerDate.getYear(),
                    pickerDate.getMonth(),
                    pickerDate.getDayOfMonth(),
                    pickerTime.getCurrentHour(),
                    pickerTime.getCurrentMinute(),
                    0);

            if(cal.compareTo(current) <= 0){

                Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show();
            }else{
                setAlarm(cal);
            }

        }});
}

private void setAlarm(Calendar targetCal){

    String pattern = "MM/dd/yyyy";
    SimpleDateFormat format = new SimpleDateFormat(pattern);

    Calendar cal = Calendar.getInstance();
    cal.set(pickerDate.getYear(),
            pickerDate.getMonth(),
            pickerDate.getDayOfMonth(),
            pickerTime.getCurrentHour(),
            pickerTime.getCurrentMinute(),
            0);
    cal.set(Calendar.MILLISECOND,0);

    try {
    Date date12_25 = format.parse("12/25/2017");

    Lebanon.put(date12_25,"Christmas Day");
        for(Date k : Lebanon.keySet()){

            if(cal.getTime().equals(k)){

                String val = (String)Lebanon.get(k);
                info.setText("Your alarm is set for :"+k+", on:  "+val);
            }

        }

    } catch (ParseException e) {
        e.printStackTrace();
    }format.format(new Date());

    Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
    alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}

Body:
Use BroadcastReceiver.

public class MyBroadcastReceiver extends BroadcastReceiver {
    MediaPlayer mp;
    @Override
    public void onReceive(Context context, Intent intent) {
        mp=MediaPlayer.create(context, R.raw.alrm   );
        mp.start();
        Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
    }
}

Start Alarm-

//  i = int time from calander.
     int i = 12;
            Intent intent = new Intent(this, MyBroadcastReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                                          this.getApplicationContext(), 234324243, intent, 0);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                                          + (i * 1000), pendingIntent);
            Toast.makeText(this, "Alarm set in " + i + " seconds",Toast.LENGTH_LONG).show();


来源: stackexchange

问:
Mockito test case for DAO class methods written using java 8
```<code>public class DBConnectionDAOImpl {

public List<String> getData{
    return jdbcTemplate.query("Select abc from table_name ", (ResultSet rs) -> getAllData(rs));
}

public List<String> getAllData(ResultSet rs){
    List<String> ls = new ArrayList<>();
    try{
        while(rs.next()){
            ls.add(rs.getString("pk"));
        }
        return ls;
    }catch(Exception e){

    }
}
</code>```

}

For testing getData method I have written test case as:

```<code>public class DBConnectionDAOImplTest {

@InjectMock
DBConnectionDAOImpl dbConnectionDAOImpl;

@MOck
JdbcTemplate jdbcTemplate;

@Test
public void getDataTest(){
    ResultSet rs = Mockito.mock(ResultSet.class);
    when(rs.next().thenReturn(true).thenReturn(false));
    when(rs.getString("pk")).thenReturn("someVal");
    when(dbConnectionDAOImpl.getAllData(rs)).thenReturn(new ArrayList<String>());
    when(jdbcTemplate.query("Select abc from table_name ", (ResultSet rs) -> dbConnectionDAOImpl.getAllData(rs))).thenReturn(new ArrayList<String>());

    List<String> result = dbConnectionDAOImpl.getData();
    assertNotNull(result);
}
</code>```

}

while running the test case I am getting the error in line

```<code>when(dbConnectionDAOImpl.getAllData(rs)).thenReturn(new ArrayList<String>());
</code>```

as "org.mockito.exceptions.misusing.WrongTypeOfReturnValue:". Not getting where exactly I am getting wrong.

--- EDIT 1--
after changing the

```<code> when(dbConnectionDAOImpl.getAllData(rs)).thenReturn(new ArrayList<String>());
</code>```

as per the comment assertion is failing.

答:
As in provided link in my comment, try to change:

```<code>when(dbConnectionDAOImpl.getAllData(rs)).thenReturn(new ArrayList<String>());
</code>```

to

```<code>doReturn(new ArrayList<String>()).when(dbConnectionDAOImpl).getAllData(rs)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
public class DBConnectionDAOImpl {

public List<String> getData{
    return jdbcTemplate.query("Select abc from table_name ", (ResultSet rs) -> getAllData(rs));
}

public List<String> getAllData(ResultSet rs){
    List<String> ls = new ArrayList<>();
    try{
        while(rs.next()){
            ls.add(rs.getString("pk"));
        }
        return ls;
    }catch(Exception e){

    }
}

}

For testing getData method I have written test case as:

public class DBConnectionDAOImplTest {

@InjectMock
DBConnectionDAOImpl dbConnectionDAOImpl;

@MOck
JdbcTemplate jdbcTemplate;

@Test
public void getDataTest(){
    ResultSet rs = Mockito.mock(ResultSet.class);
    when(rs.next().thenReturn(true).thenReturn(false));
    when(rs.getString("pk")).thenReturn("someVal");
    when(dbConnectionDAOImpl.getAllData(rs)).thenReturn(new ArrayList<String>());
    when(jdbcTemplate.query("Select abc from table_name ", (ResultSet rs) -> dbConnectionDAOImpl.getAllData(rs))).thenReturn(new ArrayList<String>());

    List<String> result = dbConnectionDAOImpl.getData();
    assertNotNull(result);
}

}

while running the test case I am getting the error in line

when(dbConnectionDAOImpl.getAllData(rs)).thenReturn(new ArrayList<String>());

as "org.mockito.exceptions.misusing.WrongTypeOfReturnValue:". Not getting where exactly I am getting wrong.

--- EDIT 1--
after changing the

 when(dbConnectionDAOImpl.getAllData(rs)).thenReturn(new ArrayList<String>());

as per the comment assertion is failing.

Body:
As in provided link in my comment, try to change:

when(dbConnectionDAOImpl.getAllData(rs)).thenReturn(new ArrayList<String>());

to

doReturn(new ArrayList<String>()).when(dbConnectionDAOImpl).getAllData(rs)


问:
How to zoom in leaflet fuse search?
I am using leaflet and leaflet fuse search to search the line drawn in a map.
Currently my code :

```<code>var map = L.map('map').setView([1.3096622448984000, 103.7689017333800], 12);

    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=fhi', {
        maxZoom: 18,
        attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
            '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
            'Imagery © <a href="http://mapbox.com">Mapbox</a>',
        id: 'mapbox.streets'
    }).addTo(map);
    map.doubleClickZoom.disable();

    var options = {
            position: 'topleft',
            title: 'Search',
            placeholder: 'enter link id ',
            maxResultLength: 15,
            threshold: 0.5,
            showInvisibleFeatures: true,
            showResultFct: function(feature, container) {
                props = feature.properties;
                var name = L.DomUtil.create('b', null, container);
                name.innerHTML = props.id;

                container.appendChild(L.DomUtil.create('br', null, container));

                var cat = props.id
                    info = '' + cat + ', ' + 'th link';
                container.appendChild(document.createTextNode(info));
            }
        };

    var searchCtrl = L.control.fuseSearch(options);

    searchCtrl.addTo(map);
searchCtrl.indexFeatures(zones.features, ['id']);
info.addTo(map);
</code>```

So now when I search I am able to display a popup.But additionally I want to zoom into the map when I do the search is it possible?Any help is appreciated.

答:
I copy here the answer I made for How to zoom and change color in leaflet which is the same :

I guess we have to modify the createResultItem function :

https://github.com/naomap/leaflet-fusesearch/blob/master/src/leaflet.fusesearch.js#L286

It seems the function allows only openPoup / panAndpopup as event, it would be usefull to add other events or pass personnal function at this step

Title: How to zoom in leaflet fuse search?

Body:
I am using leaflet and leaflet fuse search to search the line drawn in a map.
Currently my code :

var map = L.map('map').setView([1.3096622448984000, 103.7689017333800], 12);

    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=fhi', {
        maxZoom: 18,
        attribution: 'Map data © OpenStreetMap contributors, ' +
            'CC-BY-SA, ' +
            'Imagery © Mapbox',
        id: 'mapbox.streets'
    }).addTo(map);
    map.doubleClickZoom.disable();

    var options = {
            position: 'topleft',
            title: 'Search',
            placeholder: 'enter link id ',
            maxResultLength: 15,
            threshold: 0.5,
            showInvisibleFeatures: true,
            showResultFct: function(feature, container) {
                props = feature.properties;
                var name = L.DomUtil.create('b', null, container);
                name.innerHTML = props.id;

                container.appendChild(L.DomUtil.create('br', null, container));

                var cat = props.id
                    info = '' + cat + ', ' + 'th link';
                container.appendChild(document.createTextNode(info));
            }
        };

    var searchCtrl = L.control.fuseSearch(options);

    searchCtrl.addTo(map);
searchCtrl.indexFeatures(zones.features, ['id']);
info.addTo(map);

So now when I search I am able to display a popup.But additionally I want to zoom into the map when I do the search is it possible?Any help is appreciated.


问:
NSRangeException related to UIActionSheet
I am using UIActionSheet to display 3 action buttons in a popover when a table row is selected.

In .h of my tableViewController, I have declared the following:

```<code>UIActionSheet *actionSheet;
</code>```

In .m of my tableViewController, I have the following code

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

if (self.actionSheet == nil) {
self.actionSheet = [[UIActionSheet alloc]
                         initWithTitle:@"Available Actions"
             delegate:self
             cancelButtonTitle:nil
             destructiveButtonTitle:@"Delete"
             otherButtonTitles:@"Button1", @"Button2", nil] ;
}
UITableViewCell *cell = (UITableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
CGRect popoverRect = [[cell superview] convertRect:cell.frame toView:self.tableView];
[self.actionSheet showFromRect:popoverRect inView:self.tableView animated:YES];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString *buttonTitle = [self.actionSheet buttonTitleAtIndex:buttonIndex];

    if ([buttonTitle compare:@"button1"] == NSOrderedSame) {
        //...DO Something

    } else if ([buttonTitle compare:@"button2"] == NSOrderedSame) {
        //...Do sometihing

        }else {
        //...
    }
}
</code>```

The Action Sheet does show up correctly after selecting a table row, however, it crashes if I click on anywhere outside the action sheet, and the console displays the following:

```<code>Terminating app due to uncaught exception 'NSRangeException', reason:
'*** -[NSCFArray objectAtIndex:]: index (-1( or possibly larger)) beyond bounds (3)'
</code>```

In comparision, it does NOT crash and the action sheet popover gets dismissed correctly when I click on any buttons on the action sheet.

答: Check if buttonIndex == -1 and if it is redisplay your actionsheet rather than your methods current code.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am using UIActionSheet to display 3 action buttons in a popover when a table row is selected.

In .h of my tableViewController, I have declared the following:

UIActionSheet *actionSheet;

In .m of my tableViewController, I have the following code

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

if (self.actionSheet == nil) {
self.actionSheet = [[UIActionSheet alloc]
                         initWithTitle:@"Available Actions"
             delegate:self
             cancelButtonTitle:nil
             destructiveButtonTitle:@"Delete"
             otherButtonTitles:@"Button1", @"Button2", nil] ;
}
UITableViewCell *cell = (UITableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
CGRect popoverRect = [[cell superview] convertRect:cell.frame toView:self.tableView];
[self.actionSheet showFromRect:popoverRect inView:self.tableView animated:YES];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString *buttonTitle = [self.actionSheet buttonTitleAtIndex:buttonIndex];

    if ([buttonTitle compare:@"button1"] == NSOrderedSame) {
        //...DO Something

    } else if ([buttonTitle compare:@"button2"] == NSOrderedSame) {
        //...Do sometihing

        }else {
        //...
    }
}

The Action Sheet does show up correctly after selecting a table row, however, it crashes if I click on anywhere outside the action sheet, and the console displays the following:

Terminating app due to uncaught exception 'NSRangeException', reason:
'*** -[NSCFArray objectAtIndex:]: index (-1( or possibly larger)) beyond bounds (3)'

In comparision, it does NOT crash and the action sheet popover gets dismissed correctly when I click on any buttons on the action sheet.


问:
VisualStudio 2017 Lightweight mode can't be turned off
I turned off lightweight for solution inVS2017, in Tools->Options->ProjectsAndSolutions->General,

But projects is loading in lazy mode (only when i clicked on the project):

Also i clicked disable light weight solution load mode in the solution context and it doesn't help.

It is hard to work in VS with such bug, because i need to open all 62 projects manually to start working/. Without these 62 steps, code editor thinks that interfces and classes declared in uloaded projects do not exist.

How to turn  off the 'lightweight' mode?

答: Right click on solution, go for “Disable Lightweight Solution Load” context menu option and then re-open the solution.


问:
How to scale video to be as large as possible so that the background area is completely covered by the background video
I want to create a background video using HTML5 so it will scale as large as possible so that the background area is completely covered by the background video, something similarly to the background-size: cover;, but to the video.

I want it to be as cross-platform/browser as possible.

EDIT

I meant background-size: cover;

Sorry for that :/

答: You can use the width and height  properties and set it to 100% or use vh and vw units if the percentage does not work for you</p>


问:
I have two beans and need to calculate the percentage from one to the other?
I have two javabeans which have two numbers, for 8000 and 35000, how can i calculate thei percentage of 8000 to 35000 in jsf

                                            </p>

答:
A JavaBean is a POJO (Plain Old Java Object) width getter and setter for its fields. Its fields can be set by a constructor takes the appropriate arguments or later by the setter methods.

```<code>public class ValueHolder
{
  private double value1;
  private double value2;
  public ValueHolder( double value1_, double value2_ )
  {
    super();
    value1 = value1_;
    value2 = value2_;
  }

  public double getValue1() { return value1; }
  public void setValue1( double value1_ ) { value1 = value1_; };
  public double getValue2() { return value2; }
  public void setValue2( double value2_ ) { value2 = value2_; };
}
</code>```

You can store the values in a common double array (double[]) as well and create indexed accessors (double getValue( int ndx_ ) ).
The JavaBeans does not contain any business logic they are just simple data storages, ENTITIES. The calculation takes place out ther (most of the cases in CONTROLLERS) but now I place in into the main function for simplicity:

```<code>public class PercentageApp
{
  public static void main( String[] args )
  {
    ValueHolder vh = new ValueHolder( 8000, 35000 );
    double percentage = vh.getValue1() / vh.getValue2();
    System.out.println( "Percentage: " + Double.toString( percentage ) );
  }

}
</code>```

Body:
A JavaBean is a POJO (Plain Old Java Object) width getter and setter for its fields. Its fields can be set by a constructor takes the appropriate arguments or later by the setter methods.

public class ValueHolder
{
  private double value1;
  private double value2;
  public ValueHolder( double value1_, double value2_ )
  {
    super();
    value1 = value1_;
    value2 = value2_;
  }

  public double getValue1() { return value1; }
  public void setValue1( double value1_ ) { value1 = value1_; };
  public double getValue2() { return value2; }
  public void setValue2( double value2_ ) { value2 = value2_; };
}

You can store the values in a common double array (double[]) as well and create indexed accessors (double getValue( int ndx_ ) ).
The JavaBeans does not contain any business logic they are just simple data storages, ENTITIES. The calculation takes place out ther (most of the cases in CONTROLLERS) but now I place in into the main function for simplicity:

public class PercentageApp
{
  public static void main( String[] args )
  {
    ValueHolder vh = new ValueHolder( 8000, 35000 );
    double percentage = vh.getValue1() / vh.getValue2();
    System.out.println( "Percentage: " + Double.toString( percentage ) );
  }

}


问:
Joomla 3 Change website language from framework
We have our site in dutch but we are opening a version in France. We decided to just have the French language when people go to the .fr version of our site and the dutch version if people go to the .nl version.

So I created an onAfterInitialise plugin that gets the domain and now I want to set the language to french. We created overrides for the important language strings.

But how do I change the language to fr_FR? I tried the documentation but noticed that setLanguage is deprecated now in Joomla 3?

Greetings,

答:
You need to use  JLanguage::getInstance instead of setLanguage as it is deprecated. To change a language of site you can use

```<code>$lang_code = "fr_FR";
$newLang = JLanguage::getInstance($lang_code);
$app = JFactory::getApplication();
$app->loadLanguage($newLang);
</code>```

This will load the french language in .fr site.

Body:
You need to use  JLanguage::getInstance instead of setLanguage as it is deprecated. To change a language of site you can use

$lang_code = "fr_FR";
$newLang = JLanguage::getInstance($lang_code);
$app = JFactory::getApplication();
$app->loadLanguage($newLang);

This will load the french language in .fr site.


问:
How to restore default Heroku environment variables?
I accidentally cleared all my app's config vars using Heroku documentation (it should have erased only my environment variables and left the ones set by Heroku).

Now my app can't connect to its db (the default shared PostGreSQL) nor its memcache instance.

Do you know how to restore those variables?

Thank you,

Kevin

答:
Turns out you can't. I tweeted for help and Heroku support answered me really fast. They restored my PostGreSQL variable and it worked.

I only had to manually remove and re-add the other addons such as Memcached and Campfire deploy hooks.


问:
Django create new instance of model with '__init__' function from table, instance data is error?
there is my model code which have problem：

```<code>class Person(models.Model):
    name = models.CharField(max_length=20)
    url = models.URLField()
    card_id = models.CharField(max_length=20)

    def __init__(self, name, card_id, url, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.name = name
        self.card_id = card_id
        self.url = url

    def __str__(self):
        return str({
            'name': self.name,
            'card_id': self.card_id,
            'url': self.url
        })
</code>```

there is test code:

```<code>class PersonTestCase(TestCase):
    def setUp(self):
        Person.objects.create(name="test",
                          card_id="123",
                          url="http://www.baidu.com")

    def test_get(self):
        p = Person.objects.get(name="test")
        print(p)
</code>```

the print of test function 'test_get' is:

```<code>{'name': 1, 'card_id': 'test', 'url': '123'}
</code>```

which is error.

the value of name is data of id column in table ,
the value of card_id is data of name column in table,
...

but if I change function __init__ to follow:

```<code>    def __init__(self, id=None, name=None, card_id=None, url=None, *args, **kwargs):
</code>```

or delete function __init__, get the print of function test_get is:

```<code>{'name': 'test', 'card_id': '123', 'url': 'http://www.baidu.com'}
</code>```

which is right.

In somewhere, I use Person(....) to create new instance, if I delete __init__, it means I cannot use Person(...) to create new instance,
Shall I change my code？

So what is best way to create new instance from table data?

答: You should not define __init__ on a model at all. The base class - which you call via super - already sets attributes from kwargs. Remove that method.

Body:
there is my model code which have problem：

class Person(models.Model):
    name = models.CharField(max_length=20)
    url = models.URLField()
    card_id = models.CharField(max_length=20)

    def __init__(self, name, card_id, url, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.name = name
        self.card_id = card_id
        self.url = url

    def __str__(self):
        return str({
            'name': self.name,
            'card_id': self.card_id,
            'url': self.url
        })

there is test code:

class PersonTestCase(TestCase):
    def setUp(self):
        Person.objects.create(name="test",
                          card_id="123",
                          url="http://www.baidu.com")

    def test_get(self):
        p = Person.objects.get(name="test")
        print(p)

the print of test function 'test_get' is:

{'name': 1, 'card_id': 'test', 'url': '123'}

which is error.

the value of name is data of id column in table ,
the value of card_id is data of name column in table,
...

but if I change function __init__ to follow:

    def __init__(self, id=None, name=None, card_id=None, url=None, *args, **kwargs):

or delete function __init__, get the print of function test_get is:

{'name': 'test', 'card_id': '123', 'url': 'http://www.baidu.com'}

which is right.

In somewhere, I use Person(....) to create new instance, if I delete __init__, it means I cannot use Person(...) to create new instance,
Shall I change my code？

So what is best way to create new instance from table data?


问:
How to use an asynchronous Swift Firebase function?
So basically I have a function that connects to Firebase and gets data in the form of a string and returns a string(at least I think).

this question Is very simple and kind of a dumb question but how would I call this method in a different thread or core. Sorry don't really know the terms yet. I am trying.

also, I don't think it returns a String which I need so how would I accomplish that?

also this is not a duplicate because if you look at all these type of questions I have not found one that calls the actual method.

```<code>typealias someting = (String?) -> Void
    func getOpposingUsername( _ index: Int, completionHandler: @escaping someting) {
        var opposingUser: String = ""
        self.datRef.child("Bets").child(self.tieBetToUser[index]).observe(.childAdded, with: { snapshot in

            guard let dict = snapshot.value as? [String: AnyHashable] else {
                return
            }

            opposingUser = dict["OpposingUsername"] as! String
            if opposingUser.isEmpty {
                completionHandler(nil)
            } else {
                completionHandler(opposingUser)
            }

        })

    }
</code>```

答:
Changing threads would be something like this DispatchQueue.main.async {your code} here is the documentation on GCD Dispatch.

Here is an example of a function that returns a string,

```<code>func stringReturn() -> String {
  let aString = "a string"
  return aString
}
</code>```

Body:
So basically I have a function that connects to Firebase and gets data in the form of a string and returns a string(at least I think).

this question Is very simple and kind of a dumb question but how would I call this method in a different thread or core. Sorry don't really know the terms yet. I am trying.

also, I don't think it returns a String which I need so how would I accomplish that?

also this is not a duplicate because if you look at all these type of questions I have not found one that calls the actual method.

typealias someting = (String?) -> Void
    func getOpposingUsername( _ index: Int, completionHandler: @escaping someting) {
        var opposingUser: String = ""
        self.datRef.child("Bets").child(self.tieBetToUser[index]).observe(.childAdded, with: { snapshot in

            guard let dict = snapshot.value as? [String: AnyHashable] else {
                return
            }

            opposingUser = dict["OpposingUsername"] as! String
            if opposingUser.isEmpty {
                completionHandler(nil)
            } else {
                completionHandler(opposingUser)
            }

        })

    }

Body:
Changing threads would be something like this DispatchQueue.main.async {your code} here is the documentation on GCD Dispatch.

Here is an example of a function that returns a string,

func stringReturn() -> String {
  let aString = "a string"
  return aString
}


问:
PHP return array from function not working properly
I have 2 phps, one containing the main code and another containing functions:

From PHP1 I call a function contained in PHP2 parsing a value: $ubicacionlibre=listado($pasillo);

Function listado() creates an array $ubicacionlibre. If I var_dump($ubicacionlibre) from the function it shows correctly the array with 233 items:
array(233) { [0]=> string(4) "5014" [1]=> string(4) "5015"...

Then I use return_array($ubicacionlibre) to send this array back to PHP1

If I var_dump returned $ubicacionlibre from PHP1 it shows array as 1 item:

```<code>array(1) { [0]=> array(233) { [0]=> string(4) "5014" [1]=> string(4) "5015"....
</code>```

Then if I try to access the values contained in the array it shows "Array to string convertion" and I cannot use the array properly. May I use serialize/unserialize or what am I missing?

答:
If $ubicacionlibre is an array then you should just return $ubicacionlibre;.

If you return array($ubicacionlibre); then you create a new array that contains a single element ($ubicacionlibre), i.e. a two-level array.

Body:
I have 2 phps, one containing the main code and another containing functions:

From PHP1 I call a function contained in PHP2 parsing a value: $ubicacionlibre=listado($pasillo);

Function listado() creates an array $ubicacionlibre. If I var_dump($ubicacionlibre) from the function it shows correctly the array with 233 items:
array(233) { [0]=> string(4) "5014" [1]=> string(4) "5015"...

Then I use return_array($ubicacionlibre) to send this array back to PHP1

If I var_dump returned $ubicacionlibre from PHP1 it shows array as 1 item:

array(1) { [0]=> array(233) { [0]=> string(4) "5014" [1]=> string(4) "5015"....

Then if I try to access the values contained in the array it shows "Array to string convertion" and I cannot use the array properly. May I use serialize/unserialize or what am I missing?


问:
Compare two strings in selenium
I need to take value from row from page

my code is

```<code>String bname1 = selenium.getText("//table[@id='bank']/tbody/tr[3]/td[2]");
assertEquals(bname1,"HDFC");
if(bname1=="HDFC") {
    System.out.println("Bank name is:"+bname1);
} else {
    System.out.println("Bank name not found");
}
System.out.println(bname1);
</code>```

Result:
Bank name not found
HDFC

My bank name is "VIJAYA"
But when i compare to "bname1" and "VIJAYA",RESULT will be negative?
How can i compaire these strings
pls help me...

答:
Try this..</p>

```<code>        WebDriver driver = new FirefoxDriver();
        driver.navigate().to("Url");

        WebElement strvalue = driver.findElement(By.xpath("  "));
        String expected = "Text to compare";
        String actual = strvalue.getText();
        System.out.println(actual);

    if(expected.equals(actual)){
        System.out.println("Pass");
    }
        else {
            System.out.println("Fail");
        }
</code>```

Title: Compare two strings in selenium

Body:
I need to take value from row from page

my code is

String bname1 = selenium.getText("//table[@id='bank']/tbody/tr[3]/td[2]");
assertEquals(bname1,"HDFC");
if(bname1=="HDFC") {
    System.out.println("Bank name is:"+bname1);
} else {
    System.out.println("Bank name not found");
}
System.out.println(bname1);

Result:
Bank name not found
HDFC

My bank name is "VIJAYA"
But when i compare to "bname1" and "VIJAYA",RESULT will be negative?
How can i compaire these strings
pls help me...

Body:
Try this..

        WebDriver driver = new FirefoxDriver();
        driver.navigate().to("Url");

        WebElement strvalue = driver.findElement(By.xpath("  "));
        String expected = "Text to compare";
        String actual = strvalue.getText();
        System.out.println(actual);

    if(expected.equals(actual)){
        System.out.println("Pass");
    }
        else {
            System.out.println("Fail");
        }


问:
Impala with Sas 9.4 : not import data with create table
creating a table with Sas and Impala I can't import data with many columns (more than 1500). The table is created but the data is not written and the following error is generated:

ERROR: CLI execute error: [Cloudera][ImpalaODBC] (110) Error while executing a query in Impala:
   [HY000] : AnalysisException: Syntax         error in line 1: ...,xxx`)  VALUES ( ? , ? , ? , ? , ? , ? , ? , ...
    ^ Encountered:         Unexpected character Expected: CASE, CAST, DEFAULT, EXISTS, FALSE, IF, INTERVAL, NOT, NULL, TRUNCATE, TRUE, IDENTIFIER

Thank you

答:
I try to create a view or a table with engine SAS Impala (ODBC impala ClouderaImpalaODBC-2.5.36.1009-1.x86_64) RedHat 6.8. And I get this error:

ERROR: CLI execute error: [Cloudera] [ImpalaODBC] (110) Error while executing a query in Impala: [HY000]: AnalysisException: Syntax
        error in line 1: ... King ((a.trns_dt between {d '31.10.2015'} and {d '^ 2 ... Encountered:
        Unexpected character Expected: CASE, CAST, EXISTS, FALSE, IF, INTERVAL, NOT NULL, TRUNCATE, TRUE, IDENTIFIER Caused BY:
        Exception: Syntax error

We have seen that characters that are passed impala can not read such. "{}".


问:
Function arithmetic library for python
I'm searching for a library that will let me manipulate functions with the standard operators (*, -, *, /, etc.).

Lets suppose you have a function f(x) = x ** 2 and g(x) = x + 2. I'd like to be able to write f * g and get a new functor that is essentialy x ** 2 * (x + 2) or f(g) and get (x + 2) ** 2.

I know this is not too hard to implement, you'll just have to make a Functor class and overload it's __call__ function, but I'm hoping there is a 3rd party library for it.

I'm not trying to use this for anything heavyweight just for learning. Thanks for the help.

答: I don't completely understand what you're after, but does the operator module (in the standard library) help at all? It defines functions for all the standard arithmetic operators.

Title: Function arithmetic library for python


问:
python - pxssh - failed to login
I'm trying to connect to a server using ssh via the pxssh python library.
Here's my code:

```<code>import pxssh
import getpass
try:
    s = pxssh.pxssh()
    s.force_password = True
    hostname = 'myserverip'
    username = 'username'
    password = 'password'
    s.login (hostname, username, password)
    s.sendline ('get system number')  # run a command
    s.prompt()             # match the prompt
    print s.before         # print everything before the prompt.
    s.logout()
except pxssh.ExceptionPxssh, e:
    print "pxssh failed on login."
    print str(e)
</code>```

Here is the response I am getting:

```<code>pxssh failed on login.
could not set shell prompt
 unset PROMPT_COMMAND

error,09
$ PS1='[PEXPECT]\$ '

error,09
$ set prompt='[PEXPECT]\$ '

error,09
$
</code>```

答:
Pretty old question but just for posterity. (For the one's who would bump in to this like me :) )

```<code>from pexpect import pxssh
import getpass
try:
    s = pxssh.pxssh()
    hostname = raw_input('hostname: ')
    username = raw_input('username: ')
    password = getpass.getpass('password: ')
    s.login(hostname, username, password)
    s.sendline('uptime')   # run a command
    s.prompt()             # match the prompt
    print(s.before)        # print everything before the prompt.
    s.sendline('ls -l')
    s.prompt()
    print(s.before)
    s.sendline('df')
    s.prompt()
    print(s.before)
    s.logout()
except pxssh.ExceptionPxssh as e:
    print("pxssh failed on login.")
    print(e)
</code>```

which I just yanked from http://pexpect.readthedocs.io/en/latest/api/pxssh.html#pexpect.pxssh.pxssh

Title: python - pxssh - failed to login

Body:
I'm trying to connect to a server using ssh via the pxssh python library.
Here's my code:

import pxssh
import getpass
try:
    s = pxssh.pxssh()
    s.force_password = True
    hostname = 'myserverip'
    username = 'username'
    password = 'password'
    s.login (hostname, username, password)
    s.sendline ('get system number')  # run a command
    s.prompt()             # match the prompt
    print s.before         # print everything before the prompt.
    s.logout()
except pxssh.ExceptionPxssh, e:
    print "pxssh failed on login."
    print str(e)

Here is the response I am getting:

pxssh failed on login.
could not set shell prompt
 unset PROMPT_COMMAND

error,09
$ PS1='[PEXPECT]\$ '

error,09
$ set prompt='[PEXPECT]\$ '

error,09
$

Body:
Pretty old question but just for posterity. (For the one's who would bump in to this like me :) )

from pexpect import pxssh
import getpass
try:
    s = pxssh.pxssh()
    hostname = raw_input('hostname: ')
    username = raw_input('username: ')
    password = getpass.getpass('password: ')
    s.login(hostname, username, password)
    s.sendline('uptime')   # run a command
    s.prompt()             # match the prompt
    print(s.before)        # print everything before the prompt.
    s.sendline('ls -l')
    s.prompt()
    print(s.before)
    s.sendline('df')
    s.prompt()
    print(s.before)
    s.logout()
except pxssh.ExceptionPxssh as e:
    print("pxssh failed on login.")
    print(e)

which I just yanked from http://pexpect.readthedocs.io/en/latest/api/pxssh.html#pexpect.pxssh.pxssh


问:
How to access NSMutableArray index Xamarin.ios
I am getting NSMuttableArray cannot access in foreach statement. Anyone can guide how to get it in xamarin.ios c#?

I am having enum class as FontType, I need to change symbol to FontType

```<code>static NSMutableArray symbols;
foreach (var number in symbols)
{
    FontType d = symbols.IntValue
}
</code>```

答:
```<code>foreach (var number in NSArray.FromArray<T>(symbols))
{
}
</code>```

or

```<code>foreach (var number in NSArray.FromArray<NSObject>(symbols))
{
}
</code>```

Body:
I am getting NSMuttableArray cannot access in foreach statement. Anyone can guide how to get it in xamarin.ios c#?

I am having enum class as FontType, I need to change symbol to FontType

static NSMutableArray symbols;
foreach (var number in symbols)
{
    FontType d = symbols.IntValue
}

Body:
foreach (var number in NSArray.FromArray<T>(symbols))
{
}

or

foreach (var number in NSArray.FromArray<NSObject>(symbols))
{
}


问:
How do I connect to a node.js(keystone) app on a remote host? 0.0.0.0:3000
I want to play around with node.js a bit so I launched an Amazon ec2 micro instance. I set up node and keystone, it appears to be running:

```<code>------------------------------------------------
KeystoneJS Started:
My Project is ready on http://0.0.0.0:3000
------------------------------------------------
</code>```

I've tried connecting to my app via: my-remote-ip-address:3000 but it just keeps timing out. I'm very inexperienced with the server side, what am I forgetting?

答:
By default AWS only allows incoming HTTP requests on port 80
So your request to port 3000 will time out.

You have two options:

Open port 3000 in the AWS console
Login to AWS console > goto EC2 instances > at the extreme right under security  groups click on the group to open the group linked to that particular instance. > in the tabs below select inbound > edit > add rule > type - HTTP, port - 3000, IP - anywhere or you own > save

In your EC2 instance use a server like nginx to internally point requests that come to port 80 to the port your node server is running on i.e. 3000
So you will only need to got to my-remote-ip-address and nginx will internally redirect the request

Body:
I want to play around with node.js a bit so I launched an Amazon ec2 micro instance. I set up node and keystone, it appears to be running:

------------------------------------------------
KeystoneJS Started:
My Project is ready on http://0.0.0.0:3000
------------------------------------------------

I've tried connecting to my app via: my-remote-ip-address:3000 but it just keeps timing out. I'm very inexperienced with the server side, what am I forgetting?


问:
Run node.js as secure server and use webRTC when IIS is using port 443?
I am trying to use webRTC to stream audio from a client to Node.js.
The problem is: webRTC does not work on HTTP, only HTTPS. So - My IIS is using this port. I tried establishing my Node.js to listen to port 443:

First attempt: Use https.createServer, over port 9001:

Node.JS script:

```<code>var options = {
    key: fs.readFileSync('../cert/key.pem'),
    cert: fs.readFileSync('../cert/server.crt')

};
var httpsserver = https.createServer(options).listen(443);
var server = binaryServer({ server: httpsserver, port: 443 });
</code>```

Client script:

```<code>client = new BinaryClient('ws://example.com:443');
</code>```

I'm getting this error in my node script, so my first question is: Is this because port 443 is being used by my IIS?

throw er; // Unhandled 'error' event ^

Error: listen EACCES 0.0.0.0:443 at Object.exports._errnoException
  (util.js:1018:11) at exports._exceptionWithHostPort (util.js:1041:20)
  at Server._listen2 (net.js:1249:19)

Having this error, I tried using a different port (9001).

Second attempt: Use https.createServer, over port 9001:

Client script:

```<code>client = new BinaryClient('ws://example.com:9001');
</code>```

When I try to connect from a client to the node.js server on 9001, because the site address is https://example.com, I'm getting this error in the client:

Mixed Content: The page at
  'https://example.com/page.aspx'
  was loaded over HTTPS, but attempted to connect to the insecure
  WebSocket endpoint 'ws://example.com:9001/'. This request has been
  blocked; this endpoint must be available over WSS.

Because the error mentions using wss://, I tried the following.

Third attempt: Use WSS://, over port 9001:

So, I switch the client to work with WSS://,

```<code>client = new BinaryClient('wss://example.com:9001');
</code>```

but then, in the client, I get this error:

WebSocket connection to 'wss://example.com:9001/' failed: Error in
  connection establishment: net::ERR_CONNECTION_CLOSED

Any ideas how can I run my node.js server on a srcure port, assuming my IIS uses port 443, and still be able to connect securly to a client, and use webRTC ?

答:
Chrome is allowing gUM/WebRTC from Secure origins only, i.e: page url should be https & all the subsequent requests from that page should be secure.

So we must use wss:// as websocket url

It seems you are using self signed certificates,
Allow the certificate manually by entering the URL https://example.com:9001 in browser tab.

After opening the page you should get an error page, then you need to allow by clicking Advanced -> proceed.

If the page is not loaded, then u need to look into firewall or ip/dns of your server is reachable from the browser.

Body:
I am trying to use webRTC to stream audio from a client to Node.js.
The problem is: webRTC does not work on HTTP, only HTTPS. So - My IIS is using this port. I tried establishing my Node.js to listen to port 443:

First attempt: Use https.createServer, over port 9001:

Node.JS script:

var options = {
    key: fs.readFileSync('../cert/key.pem'),
    cert: fs.readFileSync('../cert/server.crt')

};
var httpsserver = https.createServer(options).listen(443);
var server = binaryServer({ server: httpsserver, port: 443 });

Client script:

client = new BinaryClient('ws://example.com:443');

I'm getting this error in my node script, so my first question is: Is this because port 443 is being used by my IIS?

throw er; // Unhandled 'error' event ^

Error: listen EACCES 0.0.0.0:443 at Object.exports._errnoException
  (util.js:1018:11) at exports._exceptionWithHostPort (util.js:1041:20)
  at Server._listen2 (net.js:1249:19)

Having this error, I tried using a different port (9001).

Second attempt: Use https.createServer, over port 9001:

Client script:

client = new BinaryClient('ws://example.com:9001');

When I try to connect from a client to the node.js server on 9001, because the site address is https://example.com, I'm getting this error in the client:

Mixed Content: The page at
  'https://example.com/page.aspx'
  was loaded over HTTPS, but attempted to connect to the insecure
  WebSocket endpoint 'ws://example.com:9001/'. This request has been
  blocked; this endpoint must be available over WSS.

Because the error mentions using wss://, I tried the following.

Third attempt: Use WSS://, over port 9001:

So, I switch the client to work with WSS://,

client = new BinaryClient('wss://example.com:9001');

but then, in the client, I get this error:

WebSocket connection to 'wss://example.com:9001/' failed: Error in
  connection establishment: net::ERR_CONNECTION_CLOSED

Any ideas how can I run my node.js server on a srcure port, assuming my IIS uses port 443, and still be able to connect securly to a client, and use webRTC ?


问:
Why react server side rendering strips event handlers?
I have a React Server Side rendered component with img tag. I want to attach an onload event listener on the image tag and made the component like below:

```<code>render () {
  return (
    <img onLoad={() => { console.log('Image loaded'); }} src='/abc.jpg'/>
  )
}
</code>```

Ideally React's renderToString method should have generated an HTML template like below:

```<code><img onload='function () { console.log('Image loaded'); }' src='/abc.jpg' />
</code>```

but it doesn't. What am I missing? I checked there was a similar issue here but with no solution

答:
React doesn't use inline event handlers in the dom/html. The listeners are added with JavaScript when your app loads on the client.

This has the benefit that they don't depend on global variables, and that it can use event delegation for performance and other reasons.

Take this code for example:

```<code>var a = 1;
<div onClick={() => console.log(a)}</div>
</code>```

There's no way React could create that as an inline event handler.

Body:
I have a React Server Side rendered component with img tag. I want to attach an onload event listener on the image tag and made the component like below:

render () {
  return (
     { console.log('Image loaded'); }} src='/abc.jpg'/>
  )
}

Ideally React's renderToString method should have generated an HTML template like below:

but it doesn't. What am I missing? I checked there was a similar issue here but with no solution

Body:
React doesn't use inline event handlers in the dom/html. The listeners are added with JavaScript when your app loads on the client.

This has the benefit that they don't depend on global variables, and that it can use event delegation for performance and other reasons.

Take this code for example:

var a = 1;
<div onClick={() => console.log(a)}</div>

There's no way React could create that as an inline event handler.


问:
IntelliJ IDEA Live Template default value as last entered value?
In IntelliJ IDEA, I'd like to create a Live Template that has a variable with a default value that updates to whatever the last thing I typed for that variable was.

For example, say I have the very simple template

```<code>$example$;
</code>```

and the first time I use the template, I type "value".  Obviously the text that should appear is

```<code>value;
</code>```

What I'd like to happen is that, the next time I use the template, "value" is already filled in for the variable $example$ (because the last time I used the template, the value of $example$ was "value").

Is there a way to get this to happen?

答: IntelliJ IDEA doesn't have this functionality. One can probably create a plug-in that would remember the last used value and provide methods to save/restore this value for the live template functions via groovyScript().

Body:
In IntelliJ IDEA, I'd like to create a Live Template that has a variable with a default value that updates to whatever the last thing I typed for that variable was.

For example, say I have the very simple template

$example$;

and the first time I use the template, I type "value".  Obviously the text that should appear is

value;

What I'd like to happen is that, the next time I use the template, "value" is already filled in for the variable $example$ (because the last time I used the template, the value of $example$ was "value").

Is there a way to get this to happen?


问:
Blurred text in Iphone 4 browser when loading content dynamically
I am using the Jquery/Jqtouch libraries for an iphone compatible site. I am now stuck with a problem just in iPhone 4 (not in 2g, 3g or 3gs) where the text becomes blurry on one specific scenario. Below is how it happens

The site has one common div container.

```<code><div id="container"></div>
</code>```

The container is filled with content dynamically based on the user action. Below is the function that does that.

```<code>function loadPage(url, section, callback) {
   $('#container').empty();
   $('#container').load(url + ' ' + section, loadComplete(section));
}
</code>```

One sample call to the above function

```<code>loadPage("Data.htm", "#Friends", null);
</code>```

Basicaly eveything works fine except on one scenario where the amount the data on the container is huge (ie the #container height increases to 1500px+ not predictable). Now if i replace it with smaller data for different tabs on the same container then the text becomes blurry.  Attached is the image

http://i.stack.imgur.com/XE9q4.png

Did anyone come across this scenario. Thanks in advance.

答:
This is a shot in the dark, but have you aset your sizes using pt values for your block elements, and em for your text?

The iphone4 resizes your content to fit its higher-res Retina display (compared to the older iphone), and with that scaling i have sometimes noticed blur when using pixel values for block height, width, font size, etc.

Very hard to diagnose without seeing the actual code, but could be the issue.

Body:
I am using the Jquery/Jqtouch libraries for an iphone compatible site. I am now stuck with a problem just in iPhone 4 (not in 2g, 3g or 3gs) where the text becomes blurry on one specific scenario. Below is how it happens

The site has one common div container.

The container is filled with content dynamically based on the user action. Below is the function that does that.

function loadPage(url, section, callback) {
   $('#container').empty();
   $('#container').load(url + ' ' + section, loadComplete(section));
}

One sample call to the above function

loadPage("Data.htm", "#Friends", null);

Basicaly eveything works fine except on one scenario where the amount the data on the container is huge (ie the #container height increases to 1500px+ not predictable). Now if i replace it with smaller data for different tabs on the same container then the text becomes blurry.  Attached is the image

http://i.stack.imgur.com/XE9q4.png

Did anyone come across this scenario. Thanks in advance.


问:
Ruby: map array of strings into array of arrays
Let's assume I have an array which looks like this:

```<code>["aaa", "bbb", "ccc"]
</code>```

I want to replace each of these items of an array into an array adding the same value, like this:

```<code>[["aaa", 0], ["bbb", 0], ["ccc", 0]]
</code>```

I don't understand why using:

```<code>arr_of_arr = arr.map{|single_item| single_item = [single_item, 0]}
</code>```

does not work, but rather returns the following error:

```<code> syntax error, unexpected keyword_end, expecting '}'
</code>```

答:
As ndn pointed out, I can just write:

```<code>arr_of_arr = arr.map{|single_item| [single_item, 0]}
</code>```

But my problem was somewhere else.

Body:
Let's assume I have an array which looks like this:

["aaa", "bbb", "ccc"]

I want to replace each of these items of an array into an array adding the same value, like this:

[["aaa", 0], ["bbb", 0], ["ccc", 0]]

I don't understand why using:

arr_of_arr = arr.map{|single_item| single_item = [single_item, 0]}

does not work, but rather returns the following error:

 syntax error, unexpected keyword_end, expecting '}'

Body:
As ndn pointed out, I can just write:

arr_of_arr = arr.map{|single_item| [single_item, 0]}

But my problem was somewhere else.


问:
Shopify Blog get more than 50 articles
I have a shopify blog with over 150 articles in it

```<code>{% assign countItem = 0 %}
{% for article in blogs.recipes.articles %}
    {% if countItem < 3 %}
        {% if article.tags contains product.title %}
        {% assign countItem = countItem | plus: 1 %}
        <li class="article">
            <a href="{{ article.url }}">
                <img src="{{ article | img_url: 'grande' }}" alt="{{ article.title }}" />
                <span class="title">{{ article.title }}</span>
            </a>
        </li>
        {% endif %}
    {% endif %}
{% endfor %}
</code>```

However blogs.recipes.articles only returns 50.

Any way to remove this limitation?

答:
Shopify limits the results to 50 so as to balance the server load. As per shopify docs.

Don't ever paginate a collection by more than 50, that's how many products maximum you should query per page. Be respectful of Shopify's app servers. If you are not using any paginate tags, pagination does kick in behind the scene and you will only receive the first 50 products in said collection.

However I have tried to load more than 50 products by using paginate tag. But that slows the page load and also the page may become unresponsive if the number of records is large. You can give it a try as following:-

```<code>{% paginate blogs.recipes.articles by 500 %}
{% assign countItem = 0 %}
{% for article in blogs.recipes.articles %}
{% if countItem < 3 %}
    {% if article.tags contains product.title %}
    {% assign countItem = countItem | plus: 1 %}
    <li class="article">
        <a href="{{ article.url }}">
            <img src="{{ article | img_url: 'grande' }}" alt="{{ article.title }}" />
            <span class="title">{{ article.title }}</span>
        </a>
    </li>
    {% endif %}
{% endif %}
{% endfor %}
{% endpaginate %}
</code>```

Title: Shopify Blog get more than 50 articles

Body:
I have a shopify blog with over 150 articles in it

{% assign countItem = 0 %}
{% for article in blogs.recipes.articles %}
    {% if countItem < 3 %}
        {% if article.tags contains product.title %}
        {% assign countItem = countItem | plus: 1 %}

                {{ article.title }}

        {% endif %}
    {% endif %}
{% endfor %}

However blogs.recipes.articles only returns 50.

Any way to remove this limitation?

Body:
Shopify limits the results to 50 so as to balance the server load. As per shopify docs.

Don't ever paginate a collection by more than 50, that's how many products maximum you should query per page. Be respectful of Shopify's app servers. If you are not using any paginate tags, pagination does kick in behind the scene and you will only receive the first 50 products in said collection.

However I have tried to load more than 50 products by using paginate tag. But that slows the page load and also the page may become unresponsive if the number of records is large. You can give it a try as following:-

{% paginate blogs.recipes.articles by 500 %}
{% assign countItem = 0 %}
{% for article in blogs.recipes.articles %}
{% if countItem < 3 %}
    {% if article.tags contains product.title %}
    {% assign countItem = countItem | plus: 1 %}
    <li class="article">
        <a href="{{ article.url }}">
            <img src="{{ article | img_url: 'grande' }}" alt="{{ article.title }}" />
            <span class="title">{{ article.title }}</span>
        </a>
    </li>
    {% endif %}
{% endif %}
{% endfor %}
{% endpaginate %}


问:
Parsing Json Array
I have been using the the Json library to try and parse the following Json data:

```<code>{"dailygameschedule": {
    "lastUpdatedOn": "2016-12-19 12:32:56 AM",
    "gameentry": [
        {
            "id": "37705",
            "date": "2016-04-03",
            "time": "1:30PM",
            "awayTeam": {
                ID: "133",
                City: "St. Louis",
                Name: "Cardinals"
                Abbreviation: "STL"
            },
            "homeTeam": {
                "ID": "132",
                "City": "Pittsburgh",
                "Name": "Pirates",
                "Abbreviation": "PIT"
            },
            "location": "PNC Park"
        },

        ...

    ]
}
</code>```

I cant figure out how to get the "gameentry" array. I was looking at other threads for guidance but it is not quite working for me. Heres what I have so far:

```<code>    JSONObject obj = new JSONObject(todaysGames);
    String pageName = obj.getJSONObject("dailygameschedule").getString("lastUpdatedOn");

    System.out.println("2 asdfasdf "+ pageName);

    JSONArray arr = obj.getJSONArray("gameentry");
    for (int i = 0; i < arr.length(); i++)
    {
        //String post_id = arr.getJSONObject(i).getString("id");
        System.out.println(arr.getJSONObject(i).getString("awayTeam.ID"));
    }
</code>```

There error that im getting is:

Exception in thread "main" org.json.JSONException:
  JSONObject["gameentry"] not found.

Thanks!

答:
Try this,</p>

```<code>JSONArray arr=obj.getJSONObject("dailygameschedule").getJSONArray("gameentry");
for (int i = 0; i < arr.length(); i++)
{
    JSONObject obj = arr.getJSONObject(i);
    String id = obj.getString("id");

    JSONObject awayTeam_obj=obj.getJSONObject("awayTeam");
    String awayTeam_ID = awayTeam_obj.getString("ID");
    String awayTeam_City = awayTeam_obj.getString("City");
    String awayTeam_Name = awayTeam_obj.getString("Name");

    JSONObject homeTeam_obj=obj.getJSONObject("homeTeam");
    String homeTeam_ID = homeTeam_obj.getString("ID");
    String homeTeam_City = homeTeam_obj.getString("City");
    String homeTeam_Name = homeTeam_obj.getString("Name");

}
</code>```

Title: Parsing Json Array

Body:
I have been using the the Json library to try and parse the following Json data:

{"dailygameschedule": {
    "lastUpdatedOn": "2016-12-19 12:32:56 AM",
    "gameentry": [
        {
            "id": "37705",
            "date": "2016-04-03",
            "time": "1:30PM",
            "awayTeam": {
                ID: "133",
                City: "St. Louis",
                Name: "Cardinals"
                Abbreviation: "STL"
            },
            "homeTeam": {
                "ID": "132",
                "City": "Pittsburgh",
                "Name": "Pirates",
                "Abbreviation": "PIT"
            },
            "location": "PNC Park"
        },

        ...

    ]
}

I cant figure out how to get the "gameentry" array. I was looking at other threads for guidance but it is not quite working for me. Heres what I have so far:

    JSONObject obj = new JSONObject(todaysGames);
    String pageName = obj.getJSONObject("dailygameschedule").getString("lastUpdatedOn");

    System.out.println("2 asdfasdf "+ pageName);

    JSONArray arr = obj.getJSONArray("gameentry");
    for (int i = 0; i < arr.length(); i++)
    {
        //String post_id = arr.getJSONObject(i).getString("id");
        System.out.println(arr.getJSONObject(i).getString("awayTeam.ID"));
    }

There error that im getting is:

Exception in thread "main" org.json.JSONException:
  JSONObject["gameentry"] not found.

Thanks!

Body:
Try this,

JSONArray arr=obj.getJSONObject("dailygameschedule").getJSONArray("gameentry");
for (int i = 0; i < arr.length(); i++)
{
    JSONObject obj = arr.getJSONObject(i);
    String id = obj.getString("id");

    JSONObject awayTeam_obj=obj.getJSONObject("awayTeam");
    String awayTeam_ID = awayTeam_obj.getString("ID");
    String awayTeam_City = awayTeam_obj.getString("City");
    String awayTeam_Name = awayTeam_obj.getString("Name");

    JSONObject homeTeam_obj=obj.getJSONObject("homeTeam");
    String homeTeam_ID = homeTeam_obj.getString("ID");
    String homeTeam_City = homeTeam_obj.getString("City");
    String homeTeam_Name = homeTeam_obj.getString("Name");

}


问:
WPF BitmapImage Serialization/Deserialization
I've been trying to Serialize and Deserialize BitmapImages. I've been using methods which supposedly works which I found in this thread: error in my byte[] to WPF BitmapImage conversion?

Just to iterate what is going on, here is part of my Serialization code:

```<code>using (MemoryStream ms = new MemoryStream())
                {
                    // This is a BitmapImage fetched from a dictionary.
                    BitmapImage image = kvp.Value;

                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(image));
                    encoder.Save(ms);

                    byte[] buffer = ms.GetBuffer();

                    // Here I'm adding the byte[] array to SerializationInfo
                    info.AddValue((int)kvp.Key + "", buffer);
                }
</code>```

And here is the deserialization code:

```<code>// While iterating over SerializationInfo in the deserialization
// constructor I pull the byte[] array out of an
// SerializationEntry
using (MemoryStream ms = new MemoryStream(entry.Value as byte[]))
                    {
                        ms.Position = 0;

                        BitmapImage image = new BitmapImage();
                        image.BeginInit();
                        image.StreamSource = ms;
                        image.EndInit();

                        // Adding the timeframe-key and image back into the dictionary
                        CapturedTrades.Add(timeframe, image);
                    }
</code>```

Also, I'm not sure if it matters but earlier when I populated my dictionary I encoded Bitmaps with PngBitmapEncoder to get them into BitmapImages. So not sure if double-encoding has something to do with it. Here's the method that does that:

```<code>// Just to clarify this is done before the BitmapImages are added to the
// dictionary that they are stored in above.
private BitmapImage BitmapConverter(Bitmap image)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                BitmapImage bImg = new BitmapImage();
                bImg.BeginInit();
                bImg.StreamSource = new MemoryStream(ms.ToArray());
                bImg.EndInit();
                ms.Close();

                return bImg;
            }
        }
</code>```

So the problem is, serialization and deserialization works fine. No errors, and the dictionary has entries with what seems to be BitmapImages, however their width/height and
some other properties are all set to '0' when I look at them in debugging-mode. And of course, nothing is shown when I try to display the images.

So any ideas as to why they aren't properly deserialized?

Thanks!

答:
1) You should not dispose MemoryStream, used from image initializing. Remove using in this line

```<code>using (MemoryStream ms = new MemoryStream(entry.Value as byte[]))
</code>```

2) After

```<code>encoder.Save(ms);
</code>```

Try adding

```<code>ms.Seek(SeekOrigin.Begin, 0);
ms.ToArray();
</code>```

Body:
I've been trying to Serialize and Deserialize BitmapImages. I've been using methods which supposedly works which I found in this thread: error in my byte[] to WPF BitmapImage conversion?

Just to iterate what is going on, here is part of my Serialization code:

using (MemoryStream ms = new MemoryStream())
                {
                    // This is a BitmapImage fetched from a dictionary.
                    BitmapImage image = kvp.Value;

                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(image));
                    encoder.Save(ms);

                    byte[] buffer = ms.GetBuffer();

                    // Here I'm adding the byte[] array to SerializationInfo
                    info.AddValue((int)kvp.Key + "", buffer);
                }

And here is the deserialization code:

// While iterating over SerializationInfo in the deserialization
// constructor I pull the byte[] array out of an
// SerializationEntry
using (MemoryStream ms = new MemoryStream(entry.Value as byte[]))
                    {
                        ms.Position = 0;

                        BitmapImage image = new BitmapImage();
                        image.BeginInit();
                        image.StreamSource = ms;
                        image.EndInit();

                        // Adding the timeframe-key and image back into the dictionary
                        CapturedTrades.Add(timeframe, image);
                    }

Also, I'm not sure if it matters but earlier when I populated my dictionary I encoded Bitmaps with PngBitmapEncoder to get them into BitmapImages. So not sure if double-encoding has something to do with it. Here's the method that does that:

// Just to clarify this is done before the BitmapImages are added to the
// dictionary that they are stored in above.
private BitmapImage BitmapConverter(Bitmap image)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                BitmapImage bImg = new BitmapImage();
                bImg.BeginInit();
                bImg.StreamSource = new MemoryStream(ms.ToArray());
                bImg.EndInit();
                ms.Close();

                return bImg;
            }
        }

So the problem is, serialization and deserialization works fine. No errors, and the dictionary has entries with what seems to be BitmapImages, however their width/height and
some other properties are all set to '0' when I look at them in debugging-mode. And of course, nothing is shown when I try to display the images.

So any ideas as to why they aren't properly deserialized?

Thanks!

Body:
1) You should not dispose MemoryStream, used from image initializing. Remove using in this line

using (MemoryStream ms = new MemoryStream(entry.Value as byte[]))

2) After

encoder.Save(ms);

Try adding

ms.Seek(SeekOrigin.Begin, 0);
ms.ToArray();


问:
How to show and hide textbox and label on the radio button selection in pyqt?
This is my gui.If user select the pass radiobutton then marks(label) and textbox should be visible and as user select the fail radiobutton then marks(label) and textbox should not be visible.
This should be completely depend on radiobutton selection.How to do this in pyqt4 python?

GUI

答:
You will need something like:

```<code># Connect radio button
self.radio_pass.toggled.connect(passToggled)

def passToggled(self):

    """Hides markls label and qlineedit if radiobutton is not checked."""

     if not self.radio_pass.isChecked():
        self.lbl_marks.hide()
        self.qle_marks.hide()
</code>```

lbl_marks is your label, qle_marks your marks field and radio_pass the radio button.

Body:
You will need something like:

# Connect radio button
self.radio_pass.toggled.connect(passToggled)

def passToggled(self):

    """Hides markls label and qlineedit if radiobutton is not checked."""

     if not self.radio_pass.isChecked():
        self.lbl_marks.hide()
        self.qle_marks.hide()

lbl_marks is your label, qle_marks your marks field and radio_pass the radio button.


问:
Django create new instance of model with '__init__' function from table, instance data is error?
there is my model code which have problem：

```<code>class Person(models.Model):
    name = models.CharField(max_length=20)
    url = models.URLField()
    card_id = models.CharField(max_length=20)

    def __init__(self, name, card_id, url, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.name = name
        self.card_id = card_id
        self.url = url

    def __str__(self):
        return str({
            'name': self.name,
            'card_id': self.card_id,
            'url': self.url
        })
</code>```

there is test code:

```<code>class PersonTestCase(TestCase):
    def setUp(self):
        Person.objects.create(name="test",
                          card_id="123",
                          url="http://www.baidu.com")

    def test_get(self):
        p = Person.objects.get(name="test")
        print(p)
</code>```

the print of test function 'test_get' is:

```<code>{'name': 1, 'card_id': 'test', 'url': '123'}
</code>```

which is error.

the value of name is data of id column in table ,
the value of card_id is data of name column in table,
...

but if I change function __init__ to follow:

```<code>    def __init__(self, id=None, name=None, card_id=None, url=None, *args, **kwargs):
</code>```

or delete function __init__, get the print of function test_get is:

```<code>{'name': 'test', 'card_id': '123', 'url': 'http://www.baidu.com'}
</code>```

which is right.

In somewhere, I use Person(....) to create new instance, if I delete __init__, it means I cannot use Person(...) to create new instance,
Shall I change my code？

So what is best way to create new instance from table data?

答:
So what is best way to create new instance from table data?

You had it, the best way is to use MyModel.objects.create which will handle all the arguments, automatically set the primary key and return the instance.

The second way is:

```<code>my_model = MyModel(...)
my_model.save()
</code>```

If you want to know the problem with your test

It's the instance attribute you are defining, such as self.name = name. When you assign the first argument to it you are actually assigning the id (which is passed by Django ORM behind the scene to the original __init__)

Moral of the story

Don't reinvent the wheel, those attributes are already set by Django.

Body:
there is my model code which have problem：

class Person(models.Model):
    name = models.CharField(max_length=20)
    url = models.URLField()
    card_id = models.CharField(max_length=20)

    def __init__(self, name, card_id, url, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.name = name
        self.card_id = card_id
        self.url = url

    def __str__(self):
        return str({
            'name': self.name,
            'card_id': self.card_id,
            'url': self.url
        })

there is test code:

class PersonTestCase(TestCase):
    def setUp(self):
        Person.objects.create(name="test",
                          card_id="123",
                          url="http://www.baidu.com")

    def test_get(self):
        p = Person.objects.get(name="test")
        print(p)

the print of test function 'test_get' is:

{'name': 1, 'card_id': 'test', 'url': '123'}

which is error.

the value of name is data of id column in table ,
the value of card_id is data of name column in table,
...

but if I change function __init__ to follow:

    def __init__(self, id=None, name=None, card_id=None, url=None, *args, **kwargs):

or delete function __init__, get the print of function test_get is:

{'name': 'test', 'card_id': '123', 'url': 'http://www.baidu.com'}

which is right.

In somewhere, I use Person(....) to create new instance, if I delete __init__, it means I cannot use Person(...) to create new instance,
Shall I change my code？

So what is best way to create new instance from table data?

Body:
So what is best way to create new instance from table data?

You had it, the best way is to use MyModel.objects.create which will handle all the arguments, automatically set the primary key and return the instance.

The second way is:

my_model = MyModel(...)
my_model.save()

If you want to know the problem with your test

It's the instance attribute you are defining, such as self.name = name. When you assign the first argument to it you are actually assigning the id (which is passed by Django ORM behind the scene to the original __init__)

Moral of the story

Don't reinvent the wheel, those attributes are already set by Django.


问:
How to Group by with Count()
```<code>[OrderNo]   [OrderStatus]
PO-01       Received
PO-01       Pending
PO-01       Received
PO-02       Pending
PO-02       Pending
PO-03       Received
PO-03       Received
</code>```

In a Table a have two Column OrderNo and OrderStatus
I want a Result like.

```<code>[OrderNo]   [OrderStatus]
PO-01       Partially Received
PO-02       Pending
PO-03       Received in Full
</code>```

If All Rows of Particular [OrderNo] is Received then Make its Status 'Received in Full' and if Not make its status 'Partially received' and if Every Row is in Pending Status make its Status 'Pending'

答:
Assuming only two status in OrderStatus</p>

```<code>declare @sales1 table
(orderNo nvarchar(10), orderStatus nvarchar(20) )
insert into      @sales1

select 'PO-01',       'Received'
union all select 'PO-01',       'Pending'
union all select 'PO-01',       'Received'
union all select 'PO-02',       'Pending'
union all select 'PO-02',       'Pending'
union all select 'PO-03',       'Received'
union all select 'PO-03',       'Received'

 SELECT orderNo
        ,CASE WHEN count(*) = sum(orderStatus)
                AND sum(orderStatus) > 0 THEN 'Pending' WHEN sum(orderStatus) > 0 THEN 'Partially Received' WHEN sum(orderStatus) = 0 THEN 'Received in full' END AS ststus
    FROM (
        SELECT orderNo
            ,CASE WHEN orderStatus = 'Received' THEN 0 ELSE 1 END AS orderStatus
        FROM @sales1
        ) t
    GROUP BY orderNo
</code>```

Title: How to Group by with Count()

Body:
[OrderNo]   [OrderStatus]
PO-01       Received
PO-01       Pending
PO-01       Received
PO-02       Pending
PO-02       Pending
PO-03       Received
PO-03       Received

In a Table a have two Column OrderNo and OrderStatus
I want a Result like.

[OrderNo]   [OrderStatus]
PO-01       Partially Received
PO-02       Pending
PO-03       Received in Full

If All Rows of Particular [OrderNo] is Received then Make its Status 'Received in Full' and if Not make its status 'Partially received' and if Every Row is in Pending Status make its Status 'Pending'

Body:
Assuming only two status in OrderStatus

declare @sales1 table
(orderNo nvarchar(10), orderStatus nvarchar(20) )
insert into      @sales1

select 'PO-01',       'Received'
union all select 'PO-01',       'Pending'
union all select 'PO-01',       'Received'
union all select 'PO-02',       'Pending'
union all select 'PO-02',       'Pending'
union all select 'PO-03',       'Received'
union all select 'PO-03',       'Received'

 SELECT orderNo
        ,CASE WHEN count(*) = sum(orderStatus)
                AND sum(orderStatus) > 0 THEN 'Pending' WHEN sum(orderStatus) > 0 THEN 'Partially Received' WHEN sum(orderStatus) = 0 THEN 'Received in full' END AS ststus
    FROM (
        SELECT orderNo
            ,CASE WHEN orderStatus = 'Received' THEN 0 ELSE 1 END AS orderStatus
        FROM @sales1
        ) t
    GROUP BY orderNo


问:
foreach return single result codeigniter
I want a array with owen key
but when i am trying to do this it return only first result any idea?</p>

```<code>    $query = $this->db->get('users');
    if ($query->num_rows() > 0) {
    foreach($query->result() as $row) {
        $data = array(
         'Name'-> $row->name
        );
    }
    $users = $data;
</code>```

答:
Try this:</p>

```<code>  $data = array();
  foreach($query->result() as $row) {
        array_push($data,array(
         'Name'-> $row->name
        ));
    }
    $users = $data;
</code>```

Body:
I want a array with owen key
but when i am trying to do this it return only first result any idea?

    $query = $this->db->get('users');
    if ($query->num_rows() > 0) {
    foreach($query->result() as $row) {
        $data = array(
         'Name'-> $row->name
        );
    }
    $users = $data;

Body:
Try this:

  $data = array();
  foreach($query->result() as $row) {
        array_push($data,array(
         'Name'-> $row->name
        ));
    }
    $users = $data;


问:
"value == var" versus "var == value"
At many places, I've seen developers doing value == var comparisons, like this:

```<code>if ('https' === location.protocol) {
   port = 8443;
   protocol = 'wss://';
   isSecure = true;
}
</code>```

I know that a == b is same as b == a, so why do people use value == var instead of var == value?

Is there a standard for this? And if yes, which is the standard way?

答:
What you are seeing is yoda condition.

Yoda conditions describe the same expression, but reversed:

```<code>if ( 42 == $value ) { /* ... */ }
// Reads like: "If 42 equals the value..."
</code>```

The advantage is

Placing the constant value in the expression does not change the behavior of the program (unless the values evaluate to false—see below). In programming languages that use a single equals sign (=) for assignment and not for comparison, a possible mistake is to assign a value unintentionally instead of writing a conditional statement.

Note that it is clearly lack of readability. I personally don't prefer this way.

Title: "value == var" versus "var == value"

Body:
At many places, I've seen developers doing value == var comparisons, like this:

if ('https' === location.protocol) {
   port = 8443;
   protocol = 'wss://';
   isSecure = true;
}

I know that a == b is same as b == a, so why do people use value == var instead of var == value?

Is there a standard for this? And if yes, which is the standard way?

Body:
What you are seeing is yoda condition.

Yoda conditions describe the same expression, but reversed:

if ( 42 == $value ) { /* ... */ }
// Reads like: "If 42 equals the value..."

The advantage is

Placing the constant value in the expression does not change the behavior of the program (unless the values evaluate to false—see below). In programming languages that use a single equals sign (=) for assignment and not for comparison, a possible mistake is to assign a value unintentionally instead of writing a conditional statement.

Note that it is clearly lack of readability. I personally don't prefer this way.


问:
Order of arguments and pipe-right operator
Is there a way to simplify the following, so I won't need a runWithTimeout function?

```<code>let runWithTimeout timeout computation =
   Async.RunSynchronously(computation, timeout)

let processOneItem item =  fetchAction item
                           |> runWithTimeout 2000
</code>```

Edit:
Here's why i needed the extra method:

```<code>let processOneItem item =  fetchAction item
                           |> Async.Catch
                           |> runWithTimeout 2000
                           |> handleExceptions
</code>```

答:
Here's a more complete sample, for future reference:</p>

```<code>let processOneItem item =  fetchAction item
                           |> Async.Catch
                           |> fun x -> Async.RunSynchronously(x,30000)
                           |> handleExceptions
</code>```

Body:
Is there a way to simplify the following, so I won't need a runWithTimeout function?

let runWithTimeout timeout computation =
   Async.RunSynchronously(computation, timeout)

let processOneItem item =  fetchAction item
                           |> runWithTimeout 2000

Edit:
Here's why i needed the extra method:

let processOneItem item =  fetchAction item
                           |> Async.Catch
                           |> runWithTimeout 2000
                           |> handleExceptions

Body:
Here's a more complete sample, for future reference:

let processOneItem item =  fetchAction item
                           |> Async.Catch
                           |> fun x -> Async.RunSynchronously(x,30000)
                           |> handleExceptions


问:
How can i pass 'n' number of requests based on value extracted from json path extractor
In Jmeter, I have extracted a value from json. The value is 2. My requirement is I need to send following HTTP samplers.
Here it is 2.
So I need to send the following 2 http requests.
http://IP:PORT/users/0?authSSOId
http://IP:PORT/users/1?authSSOId

If its 'n' request I need to pass upto 'n' counts in the url
How can i Achieve this

答:
Given you have this 2 living in a JMeter Variable, i.e. ${valueFromJson}

Add While Controller to your Test Plan and put the following expression into the "Condition" input:

```<code>${__javaScript(${counter} < ${valueFromJson},)}
</code>```

Put a Counter as a child of the While Controller and configure it like:

Start: 1

Increment: 1

Reference Name: counter

Put your HTTP Request sampler after the Counter

The HTTP Request will be executed as many times as the ${valueFromJson} variable value

Body:
Given you have this 2 living in a JMeter Variable, i.e. ${valueFromJson}

Add While Controller to your Test Plan and put the following expression into the "Condition" input:

${__javaScript(${counter} < ${valueFromJson},)}

Put a Counter as a child of the While Controller and configure it like:

Start: 1

Increment: 1

Reference Name: counter

Put your HTTP Request sampler after the Counter

The HTTP Request will be executed as many times as the ${valueFromJson} variable value


问:
Get distinct values from each table and each column with SQL Server
I would like to loop through each table for a given database to get unique values for each char field.

My query might something like:

```<code>for each table:
    for each row in table:
       select distinct char_field
       from table
    loop
loop
</code>```

How do I do this?

答:
Try it like this

```<code>DECLARE cur CURSOR FOR
    SELECT 'SELECT DISTINCT ' + QUOTENAME(c.COLUMN_NAME) + 'AS ' + QUOTENAME(TABLE_CATALOG + '.' + TABLE_SCHEMA + '.' + TABLE_NAME) + ' FROM ' + QUOTENAME(TABLE_CATALOG) + '.' + QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
    FROM INFORMATION_SCHEMA.COLUMNS AS c
    WHERE c.DATA_TYPE LIKE '%char%'

DECLARE @cmd VARCHAR(MAX);
OPEN cur;

FETCH NEXT FROM cur INTO @cmd;
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @cmd
    EXEC(@cmd);
    FETCH NEXT FROM cur INTO @cmd;
END

CLOSE cur;
DEALLOCATE cur;
</code>```

This process opens a cursor with all columns of all tables, where the data-type contains char. It will create a statement to select all distinct values and executes this one after the other.

Body:
I would like to loop through each table for a given database to get unique values for each char field.

My query might something like:

for each table:
    for each row in table:
       select distinct char_field
       from table
    loop
loop

How do I do this?

Body:
Try it like this

DECLARE cur CURSOR FOR
    SELECT 'SELECT DISTINCT ' + QUOTENAME(c.COLUMN_NAME) + 'AS ' + QUOTENAME(TABLE_CATALOG + '.' + TABLE_SCHEMA + '.' + TABLE_NAME) + ' FROM ' + QUOTENAME(TABLE_CATALOG) + '.' + QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
    FROM INFORMATION_SCHEMA.COLUMNS AS c
    WHERE c.DATA_TYPE LIKE '%char%'

DECLARE @cmd VARCHAR(MAX);
OPEN cur;

FETCH NEXT FROM cur INTO @cmd;
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @cmd
    EXEC(@cmd);
    FETCH NEXT FROM cur INTO @cmd;
END

CLOSE cur;
DEALLOCATE cur;

This process opens a cursor with all columns of all tables, where the data-type contains char. It will create a statement to select all distinct values and executes this one after the other.


答:
This should be like,</p>

```<code>$data = array();
    $query = $this->db->get('users');
    if ($query->num_rows() > 0) {
    foreach($query->result() as $row) {
        $data[] = $row->name;
    }
print_r($data);
    $users = $data;
</code>```

Title: foreach return single result codeigniter

Body:
This should be like,

$data = array();
    $query = $this->db->get('users');
    if ($query->num_rows() > 0) {
    foreach($query->result() as $row) {
        $data[] = $row->name;
    }
print_r($data);
    $users = $data;


问:
How to Host a Struts/Spring Web application project on Website for beginners?
How to deploy java web project on website, how to host simple java web app online on website.

Any free web hosting websites? for beginners

答:
Heroku provide some free plane which is ideal for experimenting with cloud applications in a limited sandbox.
heroku

If you have git account, and install heroku in local machine then use follow

```<code>commend:
 git add .

 git commit -m "Added a Procfile."

 heroku login
Enter your Heroku credentials.
...

 heroku create
Creating arcane-lowlands-8408... done, stack is cedar-14
http://arcane-lowlands-8408.herokuapp.com/ | git@heroku.com:arcane-lowlands-8408.git
Git remote heroku added

 git push heroku master
...
-----> Java app detected
...
-----> Launching... done
       http://arcane-lowlands-8408.herokuapp.com deployed to Heroku
</code>```

And it's easy to deploy web app on it
Here
 is a doc of heroku to deploye the java web app doc.

Also you can use AWS, it's provide one year free plane with limit of data.

Body:
Heroku provide some free plane which is ideal for experimenting with cloud applications in a limited sandbox.
heroku

If you have git account, and install heroku in local machine then use follow

commend:
 git add .

 git commit -m "Added a Procfile."

 heroku login
Enter your Heroku credentials.
...

 heroku create
Creating arcane-lowlands-8408... done, stack is cedar-14
http://arcane-lowlands-8408.herokuapp.com/ | git@heroku.com:arcane-lowlands-8408.git
Git remote heroku added

 git push heroku master
...
-----> Java app detected
...
-----> Launching... done
       http://arcane-lowlands-8408.herokuapp.com deployed to Heroku

And it's easy to deploy web app on it
Here
 is a doc of heroku to deploye the java web app doc.

Also you can use AWS, it's provide one year free plane with limit of data.


问:
How to scale video to be as large as possible so that the background area is completely covered by the background video
I want to create a background video using HTML5 so it will scale as large as possible so that the background area is completely covered by the background video, something similarly to the background-size: cover;, but to the video.

I want it to be as cross-platform/browser as possible.

EDIT

I meant background-size: cover;

Sorry for that :/

答:
You could do like this, which behave similar to background-size: cover

html, body {
  margin: 0;
}

.video-container {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.video-container video {
  position: absolute;
  min-width: 100%;
  min-height: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="video-container">
  <video autoplay>
    <source type="video/mp4" src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4">
  </video>
</div></code>```

Body:
You could do like this, which behave similar to background-size: cover

html, body {
  margin: 0;
}

.video-container {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.video-container video {
  position: absolute;
  min-width: 100%;
  min-height: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}

<div class="video-container">
  <video autoplay>
    <source type="video/mp4" src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4">
  </video>
</div>


问:
HttpClient getAsync hanging on larger files
I'm sorry if this question has been answered before, but none of the answers helped me. I have an event for my WebView:

```<code>private async void MainWebView_UnviewableContentIdentified(WebView sender, WebViewUnviewableContentIdentifiedEventArgs args)
{
    await downloadFromUri(args.Uri).ConfigureAwait(false);
}
</code>```

My downloadFromUri method will attempt to download a file and store it in the downloads folder and finally it will open the file:

```<code>    static async Task downloadFromUri(Uri uri)
    {
        var url = uri;

        HttpClient client = new HttpClient();

        client.DefaultRequestHeaders.TryAppendWithoutValidation(
          "Authorization Bearer",
              " MYTOKEN"
              );

        Debug.WriteLine("Attempting GET request");

        var response = await client.GetAsync(url);

        Debug.WriteLine("Got response.. checking " + response.StatusCode);

        if (response.IsSuccessStatusCode)
        {
            Debug.WriteLine("Okay, we've got a response");
            var responseFileName = response.Content.Headers.ContentDisposition.FileName;

            Debug.WriteLine("Filename: " + responseFileName);

            var ManualFile = await DownloadsFolder.CreateFileAsync(responseFileName, CreationCollisionOption.GenerateUniqueName);

            Debug.WriteLine("Creating buffer: ");
            var buffer = await client.GetBufferAsync(url);

            Debug.WriteLine("Writing buffer.");
            await Windows.Storage.FileIO.WriteBufferAsync(ManualFile, buffer);

            Debug.WriteLine("Done, opening");

            var openOptions = new Windows.System.LauncherOptions();
            openOptions.DisplayApplicationPicker = true;

            var openFile = await Windows.System.Launcher.LaunchFileAsync(ManualFile, openOptions);
        }
        else
        {
            Debug.WriteLine(response.StatusCode.ToString());
        }
    }
</code>```

The thing is, this code seems to work fine on small PDF or zip files. But when it comes to PDF files that are > 10mb, the application just hangs at the following line:

var response = await client.GetAsync(url);

What can I do to make this work? Thanks a lot in advance!

Note: I'm using the Windows.Web.Http.HttpClient and not the System.Net.Http.HttpClient.

Edit: I've tried to skip the client.GetAsync(url)and run the var buffer = await client.GetBufferAsync(url); directly. This also returns in a hang.

答:
Please change your code to-

```<code>var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false));
</code>```

Also refer this- HttpClient.GetAsync(...) never returns when using await/async

Or, you can also using TPL to execute your long running function in a Task which will be managed the OS thread pool.

```<code>var result = Task.Run(() => downloadFromUri(uri)).Result;
</code>```

Body:
I'm sorry if this question has been answered before, but none of the answers helped me. I have an event for my WebView:

private async void MainWebView_UnviewableContentIdentified(WebView sender, WebViewUnviewableContentIdentifiedEventArgs args)
{
    await downloadFromUri(args.Uri).ConfigureAwait(false);
}

My downloadFromUri method will attempt to download a file and store it in the downloads folder and finally it will open the file:

    static async Task downloadFromUri(Uri uri)
    {
        var url = uri;

        HttpClient client = new HttpClient();

        client.DefaultRequestHeaders.TryAppendWithoutValidation(
          "Authorization Bearer",
              " MYTOKEN"
              );

        Debug.WriteLine("Attempting GET request");

        var response = await client.GetAsync(url);

        Debug.WriteLine("Got response.. checking " + response.StatusCode);

        if (response.IsSuccessStatusCode)
        {
            Debug.WriteLine("Okay, we've got a response");
            var responseFileName = response.Content.Headers.ContentDisposition.FileName;

            Debug.WriteLine("Filename: " + responseFileName);

            var ManualFile = await DownloadsFolder.CreateFileAsync(responseFileName, CreationCollisionOption.GenerateUniqueName);

            Debug.WriteLine("Creating buffer: ");
            var buffer = await client.GetBufferAsync(url);

            Debug.WriteLine("Writing buffer.");
            await Windows.Storage.FileIO.WriteBufferAsync(ManualFile, buffer);

            Debug.WriteLine("Done, opening");

            var openOptions = new Windows.System.LauncherOptions();
            openOptions.DisplayApplicationPicker = true;

            var openFile = await Windows.System.Launcher.LaunchFileAsync(ManualFile, openOptions);
        }
        else
        {
            Debug.WriteLine(response.StatusCode.ToString());
        }
    }

The thing is, this code seems to work fine on small PDF or zip files. But when it comes to PDF files that are > 10mb, the application just hangs at the following line:

var response = await client.GetAsync(url);

What can I do to make this work? Thanks a lot in advance!

Note: I'm using the Windows.Web.Http.HttpClient and not the System.Net.Http.HttpClient.

Edit: I've tried to skip the client.GetAsync(url)and run the var buffer = await client.GetBufferAsync(url); directly. This also returns in a hang.

Body:
Please change your code to-

var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false));

Also refer this- HttpClient.GetAsync(...) never returns when using await/async

Or, you can also using TPL to execute your long running function in a Task which will be managed the OS thread pool.

var result = Task.Run(() => downloadFromUri(uri)).Result;


问:
How to display desired text in hyperlink using VBA code
I have displayed my hyperlink in the column E as shown
\\maroon\cgm images\mech.pdf

But I want to display only mech.pdf in the cell how to modify my code.

my code used for displaying above hyperlink is shown below:

```<code>str = "\\maroon\CGM Images\" & pn & ".pdf"
ActiveSheet.Hyperlinks.Add Range("e" & i), str
</code>```

In this I want to show only pn & str.

答:
If you have

\maroon\cgm images\mech.pdf

in a cell and you wanna get only the name of the pdf with ".pdf" you can do the next code:

```<code>Dim spliter() as String
Dim str_pdf as String

str = \maroon\cgm images\mech.pdf ' Cells(a,b).value
spliter = Split(str, " ") 'To do the first split (You can delete ', " "' )
spliter = Split(spliter(1), "\")
'Now spliter(1) == mech.pdf so...
str_pdf = spliter(1) ' spliter(0) == images , spliter(1) == mech.pdf
</code>```

Body:
I have displayed my hyperlink in the column E as shown
\\maroon\cgm images\mech.pdf

But I want to display only mech.pdf in the cell how to modify my code.

my code used for displaying above hyperlink is shown below:

str = "\\maroon\CGM Images\" & pn & ".pdf"
ActiveSheet.Hyperlinks.Add Range("e" & i), str

In this I want to show only pn & str.

Body:
If you have

\maroon\cgm images\mech.pdf

in a cell and you wanna get only the name of the pdf with ".pdf" you can do the next code:

Dim spliter() as String
Dim str_pdf as String

str = \maroon\cgm images\mech.pdf ' Cells(a,b).value
spliter = Split(str, " ") 'To do the first split (You can delete ', " "' )
spliter = Split(spliter(1), "\")
'Now spliter(1) == mech.pdf so...
str_pdf = spliter(1) ' spliter(0) == images , spliter(1) == mech.pdf