text:
Q: getting:Error: ngModel:nonassign Non-Assignable Expression I have created a filter to calculate sum of the input values inside ng-repeat and am accessing that filter outside the ng-repeat am getting the  error as :Error: ngModel:nonassign Non-Assignable Expression how do I resolve it, below is my code
**HTML**
     <input type="disable" ng-disabled="true" class="form-control"  name="count" ng-model="table.fields | mysum">

**Angularjs Filter**

      app.filter('mysum', function() {
  return function(items) {
    var sum = 0;
    items.forEach(function(item) {
     if (item.item_count) {
         sum += item.item_count;
      }
    })
    return sum;
  }
})

A: ng-model is a two way binding. What you are trying to do is bind it to a filter output. Which is not supported.
Instead use this value="{{table.fields | mysum}}"


text:
Q: Pandas - Select rows based on a hierachy of conditions I have a data frame where I would like to obtain the 'first available' index based on a nested hierarchy of values in some of the data frame's columns.
Example:
import pandas as pd

foo = ['a','a','a','a','b','b','b','b']
bar = [0,0,1,1,2,2,1,1]
foobar = ['x',1,1,2,2,3,4,5]

df = pd.DataFrame({'foo':foo,'bar':bar,'foobar':foobar})

which gives you:
  foo  bar foobar
0   a    0      x
1   a    0      1
2   a    1      1
3   a    1      2
4   b    2      2
5   b    2      3
6   b    1      4
7   b    1      5

The rules should be the following: For each value in foo choose one and only one row index based on values in bar and foobar. For bar, this is the hierarchy of conditions: 0 > 1 > 2 > ... and for foobar it's 'x' > 1 > 2 > ...
foobar should be nested in bar so if there are multiple available values for bar only consider rows for the 'first available' value in bar and only then obtain one row index based on the hierarchy of values in foobar for that specific value of bar.
Expected output:
For my example, the indices 0 and 6 should be chosen.

A: IIUC, you could use sort_values + duplicated:
df = df.sort_values(by=['foo', 'bar', 'foobar'], key=lambda x: x.replace('x', 0).astype(int))
mask = df.duplicated(subset=['foo'])
res = df[~mask].index
print(res)

Output
Int64Index([0, 4], dtype='int64')

The idea is to sort the rows of the DataFrame by hierarchy priority, replacing 'x' for 0 (or any other high priority). Then find the rows that are duplicated by the foo column.
UPDATE
For the new case you could do:
df = df.set_index('foo').sort_index().sort_values(by=['bar', 'foobar'],
                                                  key=lambda x: x.replace('x', 0).astype(int)).reset_index()
mask = df.duplicated(subset=['foo'])
res = df[~mask].index
print(res)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Time handling in application handling multiple timezone I have users from multiple timezone and storing time in Database in UTC format.
Running into issue with time part alone.
Storing user working hours for the Week as follows.

Id
UserId
Day
StTime
EndTime

1
1
0
10:00
18:00

2
1
1
10:00
18:00

3
1
2
10:00
18:00

4
1
3
10:00
18:00

5
1
4
10:00
18:00

Day, 0 for Sunday,1 for Monday, ...
Here, the time is being stored in UTC. The time is being converted in the UI based on the browser timezone. Since, there is no date part needed here, it is causing issues here.
For ex, Let's say user is selecting 7AM to 7PM in UI and the time gets converted to UTC which is 15:00 today to 02:00 tomorrow. So, in DB the time is being stored as

Id
UserId
Day
StTime
EndTime

1
1
0
15:00
02:00

2
1
1
15:00
02:00

3
1
2
15:00
02:00

4
1
3
15:00
02:00

5
1
4
15:00
02:00

Here, start time is bigger than the end time, which is not correct.
How do we need to handle timezone when storing just the time part of it?
My requirement is to get open slots for a user based on the following info.

*

*Booked slots

*Blocked Slots

*Working hours

BookedSlots,

Id
userId
St_time(datetime)
duration(mins)

1
1
2021-11-27 16:00:00
30

1
1
2021-11-27 18:00:00
45

Here, the time is in UTC.

*BlockedSlots

Id
userId
St_time
end_date
st_time
end_time

1
1
2021-11-22
2021-11-25
09:00
18:00

1
1
2021-12-17
2021-12-20
09:00
18:00

Here also, time needs to be stored in UTC

*WorkingHours

Id
UserId
Day
StTime
EndTime

1
1
0
15:00
02:00

2
1
1
15:00
02:00

3
1
2
15:00
02:00

4
1
3
15:00
02:00

5
1
4
15:00
02:00

I need to calculate open slots based on the above 3 info. But, time part is confusing when we store that in UTC. What is the best way to handle this?

A: One way to avoid the midnight wrap-around would be to store the working hours as having a start time and duration, instead of a start time and end time, just like you are doing for the booked slots.  You could do the same for blocked slots, so that you have a nice consistent storage model for all of your events.
I would also suggest storing the working hours in the user's local time, along with an IANA timezone string indicating the work location.  The problem with storing in UTC is that some time zones will enter in and out of Daylight Saving Time throughout the year.  Let's say I'm in New York City, and I want my working hours to be 09:00 to 17:00, New York time.  Since it is Eastern Standard Time (UTC-5) in New York at the moment, that would be converted to 14:00 to 22:00.  Once the summer comes, New York will enter Eastern Daylight Time (UTC-4), so my working hours will then suddenly appear to be 10:00 to 18:00 New York time.
You could also store the time zone with the user information, so that working hours are agnostic to the time zone.  This would allow you to specify something like "09:00 to 17:00 in whatever time zone the user is in."
Any time you are dealing with recurring events, I always find it's more clear to store them in the time zone in which the events will occur, since the logic for converting from UTC changes throughout the year.  For absolute events, like booked and blocked slots, it still makes sense to keep them in UTC, since they are referring to one particular event in time.

A: If you want the endTime > startTime
you can do this kind of calculation
sTime = StTime
eTime = StTime + mod(EndTime-StTime+24hour, 24)

For example:
StTime=15
EndTime=02

sTime = 15
eTime = 15 + mod(2-15+24, 24) = 26

which 26 means (24+2) => next day + 2 hours
and
StTime=09
EndTime=18

sTime = 09
eTime = 09 + mod(18-09+24, 24) = 18

the 09 to 18 will remain the same
calculate the datetime in Postgresql
SELECT TO_TIMESTAMP('2021-11-26 00:00:00', 'YYYY-MM-DD HH24:MI:SS') +StTime AS stime , TO_TIMESTAMP('2021-11-26 00:00:00', 'YYYY-MM-DD HH24:MI:SS')+StTime+(MOD((EXTRACT(EPOCH FROM (EndTime - StTime)::interval)+86400)::int4, 86400) || ' second')::interval AS etime FROM WorkingHours

you should be able to get the start and end datetime which end > start
a result example
UserId  StTime      EndTime       stime                   etime
1       15:00:00    02:00:00      2021-11-26 15:00:00     2021-11-27 02:00:00
2       09:00:00    18:00:00      2021-11-26 09:00:00     2021-11-26 18:00:00

hope this could help you


text:
Q: Want to transfer login status from store to Login Screen for wrong credentials identification I have to React Native IOS App with Login Screen for users. In the store auth, I am getting string output from Login API as 'success' or 'Login Failed'.I want to transfer this login status to Login Screen, to tell the user about the wrong credentials. Below is the auth store:
auth.js:

      export const LOGIN ='LOGIN';

      export const login=(textemailid,textpassword) =>{
      const formData = new FormData();
      formData.append('txtUemail',textemailid);
      formData.append('txtUpass',textpassword);
      return async dispatch =>{
      await fetch('https:/-------------------/login.php',
      {
      method:'post',
      headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      },
      body: formData
      })
      .then(res => res.text())
      .then(
      (loginresult) =>{
      var login = loginresult.replace('\r\n\r\n\r\n\t\r\n\t\r\n\t','');
      console.log('loginstatus is '+login);

      }).catch(err =>{
        console.log(err);
      })

      dispatch({type:LOGIN,loginStatus:login});
      }
      }

I want to transfer the 'login' value to Login Screen using navigation. Below is the LoginScreen code:
LoginScreen.js:
    import React,{useEffect} from 'react';
    import {  ActivityIndicator,StyleSheet, Text, View
     ,KeyboardAvoidingView,TouchableOpacity,Image} from "react-native";
    import { Button } from 'react-native-elements';
    import { ScrollView } from "react-native-gesture-handler";
    import {  HelperText,TextInput } from 'react-native-paper';
    import { useDispatch } from 'react-redux';
    import * as authActions from '../../store/actions/auth';
    import Icon from 'react-native-vector-icons/FontAwesome5';
    import AsyncStorage from '@react-native-async-storage/async-
       storage'
    import Toast from 'react-native-root-toast';

    const LoginScreen = ({route}) => {
    const [textemailid, setTextEmailId] = React.useState('');
    const [textpassword, setTextPassword] = React.useState('');
    const [isLoading,setIsLoading] = React.useState(false);
    const [error, setError] = React.useState('');
    const dispatch = useDispatch();
    const loginStatus1 = useSelector(state =>
           state?.auth?.login_Status);   **getting login_Status from auth reducer**
     //console.log(state);
       console.log('login status is '+loginStatus1)

     const loginHandler =  async () => {

      let action
        action =  authActions.login(
                 textemailid,
                 textpassword
                 );
       setError(null);
       setIsLoading(true);
             try{
              dispatch(action);
              console.log('login status is '+loginStatus);
              if(loginStatus === 'Login Failed'){
                let toast_success = Toast.show('Wrong Credentials');
                setIsLoading(false);

                }
                 else if(loginStatus === 'success'){
                  props.navigation.navigate({routeName:'Home'});
                }

             } catch(err){
               setError(err.message);
               console.log(err.message);
              setIsLoading(false);
             }
          };

       return(
     <KeyboardAvoidingView style={styles.container}>
     <ScrollView>
     <View style={styles.container}>

     <View style={styles.subView}>

     <Image
      style={{flex:1, height: 100, width: 100,alignSelf:'center',bottom:350}}
      source={require('../../assets/profile1.png')}
      resizeMode="contain"
     />
     <View style={styles.welcometextview}>
        <Text style={styles.welcometext}>Welcome!</Text>
      {/*   <Loader loading={isLoading} color="#ff66be" title='Loading'/> */}
        </View>

        <View style={styles.textinputemailview}>

        <TextInput
        underlineColor='grey'
        style={styles.textinputemail}
        label='Email'
        keyboardType="email-address"
        editable={true}
        autoCapitalize = 'none'
        value={textemailid}
        theme={{ colors: {  placeholder: "#f5f5f5", background: "transparent", text:
        'green', primary: '#D43790' } }}
        onChangeText={textemailid=>setTextEmailId(textemailid)}>
        </TextInput>
        </View>
        <View style={styles.textinputpasswordview} >
       <TextInput style={styles.textinputpassword}
        underlineColor='grey'
        label='Password'
        autoCapitalize = 'none'
        editable={true}
        value={textpassword}
        onChangeText={textpassword => setTextPassword(textpassword)}
         theme={{ colors: {  placeholder: "#f5f5f5", background: "transparent",text:
         'green',primary: '#D43790'  } }}>
        </TextInput>
     </View>
     <View style={styles.loginbuttonview}>
     {isLoading ? (
                <ActivityIndicator size='small' color='green'/>
              ) :
              (
                <Button buttonStyle={{
                  backgroundColor: "#EB4207"
               }}
                  containerStyle={{
                  marginTop: 12,
                  width: "50%"
               }}
         onPress={
           () => { loginHandler();
          }}
         title='Log in'/>
        )}
     </View>
     </View>
     <TouchableOpacity style={styles.textforgotpasswordview} onPress=.
       {()=>props.navigation.navigate('ForgotPasswordPage')}>
     <Text style={styles.textforgotpassword}>Forgot your password?</Text>
     </TouchableOpacity>
     <TouchableOpacity  style={styles.textregisterview} onPress=.
     {()=>props.navigation.navigate('SignUp')} >
     <Text style={styles.textregister}>Not a member?Sign up now</Text>
     </TouchableOpacity>
     </View>
     </ScrollView>
     </KeyboardAvoidingView>
    )}

    const styles = StyleSheet.create({
     container: {
    backgroundColor: '#0B0B45',
    flex:1,
    },
     subView: {
    backgroundColor: '#1D1F33',
    height: 750,
    marginTop: 150,
    borderTopRightRadius: 40,
    borderTopLeftRadius: 40,
    },
     welcometextview:{
      bottom:'80%',
      justifyContent:'center',
      alignItems:'center'
    },
     welcometext:{
     fontWeight:'bold',
     color:'grey',
     fontSize:20,

    },
     textinputemailview:{
    position:'absolute',
    top:'23%',
    width:'80%',
    alignSelf:'center'
    },
    textinputemail:{
    backgroundColor:'transparent',
    fontWeight:'bold',
    fontSize:20,
     },
     textinputpasswordview:{
     position:'absolute',
     top:'35%',
     width:'80%',
     alignSelf:"center"
     },
     textinputpassword:{
     backgroundColor:'transparent',
     fontWeight:'bold',
     fontSize:20,
    },
    textregisterview:{
    position:'absolute',
    top:'75%',
    alignSelf:'center'
    },
    textregister:{
    color: "#EB4207",
    fontSize: 20,
    fontWeight: "bold",
    textDecorationLine: 'underline'
    },
    textforgotpasswordview:{
    position:'absolute',
    alignSelf:'center',
    bottom:'33%'
    },
     textforgotpassword:{
    color: "white",
    fontSize: 20,
    fontWeight: "bold",
    },
    loginbuttonview:{
    bottom:'45%',
    justifyContent:'center',
    alignItems:'center'
    },
    });

   export default LoginScreen;

Below is the auth reducer:
auth.js:
  import { GETDEVICEINFO, LOGIN,LOGOUT } from '../actions/auth';

   const initialState = {
   mobileno: null,
   login_Status:null,
    availableDevice:[],
    };

 export default (state = initialState,action) => {
 switch(action.type){
    case LOGIN:
 return {
    login_Status : action.loginStatus

 };
  case GETDEVICEINFO:
    return {
        availableDevice:action.devices
    }

case LOGOUT:
    return initialState;

    default: return state;
 }
 }

I don't think async storage will work here because I don't want to persist data but only want to get data from auth store and also using AsyncStorage will not flush old data, it stores data till u logout and login.
After running the above code, I am getting the whole function as below:
login status is function login(textemailid, textpassword) {
var formData = new FormData();
formData.append('txtUemail', textemailid);
formData.append('txtUpass', textpassword);
return function _callee(dispatch) {
  return _regenerator.default.async(function _callee$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return _regenerator.default.awrap(fetch('https:--------
        -/login.php', {
            method: 'post',
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            },
            body: formData
          }).then(function (res) {
            return res.text();
          }).then(function (loginresult) {
            var login =
           loginresult.replace('\r\n\r\n\r\n\t\r\n\t\r\n\t', '');
            console.log('login1 is ' + login);
            saveDataToStoragelogin(login, textemailid);
          }).catch(function (err) {
            console.log(err);
          }));

        case 2:
          dispatch({
            type: LOGIN,
            loginStatus: login
          });

        case 3:
        case "end":
          return _context.stop();
      }
    }
  }, null, null, null, Promise);
};

Can anyone say how to get only login_Status string. Thanks in Advance?

A: I would try to change
  try{
    props.navigation.navigate('LoginScreen', {
      paramKey: login,
    })

to
  try{
    navigation.navigate('LoginScreen', {
      paramKey: login,
    })

A: No need to pass navigation prop to auth store. When you dispatch({type:LOGIN}) with payload store that state in reducer.Get the State using UseSelector.
For example you are in Screen A and did login Api call and store api response data in reducer. In same screen use useSelector to get the api data response from reducer. based on response type navigate to respected screens. Don't place api call in reducers.
Please check this example https://github.com/raduungurean/react-native-redux-auth-login-logout-example


text:
Q: Design Critique/Review of a God Method for a ViewModel For some reason the below design doesn't sit well with me, but I'm unable to come up with an articulate reasoning as to why. I would like your help in forming a case against (or for) it.
Say, the design of FooViewModel is as such:
// Some Observables
Observable_1: bool
Observable_2: string;
// --- //

// The method where all the "logic" is dumped
godMethod() {
    if (Singleton1.Status1 != DesiredStatus1) {
        set_state_1();
        return;
    }

    if (Singleton2.Status2 != DesiredStatus2) {
        set_state_2();
        return;
    }

    if (Observable_2.Value != "Desired String") {
        set_state_3();
        return;
    }

    set_state4();
}
// --- //

// In case of ANY external or internal event that may need the observables to change, just call the "godMethod"
externalEvent_Singleton1_Status1_Changed += () => {
    godMethod();
}

externalEvent_Singleton2_Status2_Changed += () => {
    godMethod();
}

Observable_2.Changed += () => {
    godMethod();
}
// --- //

// Actual values of the observables are defined here
set_state_1() {
    Observable_1 = false;
    Observable_2 = "Status 1 is undesirable :(";
}
set_state_2() {
    Observable_1 = false;
    Observable_2 = "Status 2 is undesirable :(";
}
set_state_3() {
    Observable_1 = false;
}
set_state_4() {
    Observable_1 = true;
}
// --- //

I guess this design, instead of defining the logic for each observable, instead defines logic for each "state".

*

*What are some pros/cons of this design?

*What can be some pitfalls of this design?

*Can this become a maintenance nightmare?

My $0.02:

*

*It is very difficult to find out dependencies for the observables by just reading the code:

*

*Say you want to figure out when the Observable_1 is set false.

*The code would indicate:

*

*If Status1 is not appropriate, OR

*If Status1 is appropriate AND If Status2 is not appropriate, OR

*If Status1 is appropriate AND If Status2 is appropriate AND Observable_2 is not appropriate

*Instead of merely defining(declaring?) that if any one of Status1, Status2 or Observable_2 is not appropriate.

*Do you see how complicated it can become?

*The number of "states" can explode exponentially.

*Calling the godMethod after every action just does my head in; but I'm unable to point to any specific principles that this design violates.

*I think that this may be the "procedural" way of doing things, and it's my OOP brain complaining; but again, why is this objectively inferior/superior?
Finally, just to add, the arguments that I've heard for this design are:

*

*You can look at all logic at one place, that make the code more readable.

*Whenever any event occurs, just call the godMethod. This, supposedly, makes the code easier to write and maintain.

A: What you are looking at is the Fix Everything design pattern.  The purpose of godMethod is to inspect everything on the page and ensure that state is set to a value that is correct, given the status of the rest of the controls/observables.
The advantages of this approach are:

*

*godMethod is idemopotent.  You can call it any number of times and you'll get the same result, so you can call it whenever you are not sure.

*You only have to write one handler, and all the logic is in one place.

*The approach works well when data can be updated from more than one source.

The cons are:

*

*A call to godMethod does more work that it would need to do if the code responded to each observable event individually, so performance might not be as good.  On the other hand, below a certain threshold, it probably doesn't matter.

*The logic in godMethod may be a bit complicated to work out since you have to look at the page as a whole and account for all possible states.

There is nothing wrong with your "god method" approach, and in fact I think is it better in most cases.

Say you want to figure out when the Observable_1 is set false

I don't understand the problem.  If a piece of code doesn't care about state and just wants to know if Observable_1 is false, it just needs to read Observable_1 directly, e.g. var f = Observable_1;  What am I missing?

The number of "states" can explode exponentially.

I don't think this is right.  If State is a function of the state of the observables, the number of possible values for State is exactly the same regardless of how you approach this problem, as long as you don't add or remove observables.
The only thing that might change is the cyclomatic complexity of the function that computes State.  If it has to look at everything, then obviously it will be more complex than something that looks at bits in isolation.
On the other hand, if you did away with the "god" function, the aggregate complexity of having several functions whose combined output is needed to determine State is probably higher still, and much harder to test, as order and repetition may impact the results, and there is no easy means of enforcing sequential coupling unless all the logic is in one place, as it is in your "god method" approach.
Stop overthinking it; your approach is fine.

A: I do agree with you that the design smells. But I can't come up with specific design that would be better.
What I can suggest is to isolate the switching logic from side-effect code and write complete unit test suite for the switching logic. There are few advantages to that:

*

*It reduces the fear you are feeling by giving you some confidence in code's correctness.

*Properly written test cases will give easier way to infer behavior of the code. So figuring out "when the Observable_1 is set false" will become easier.

*With proper test suite, it will be trivial to change the internal implementation if you find out better way to implement the design.

*Properly separating the switching logic and side-effect code might provide cleaner design and improve understanding of internal behavior.

One thing I would be really careful is how to build API between the isolated unit representing the switching behavior and rest of the code. You can either isolate just the godMethod or you can also include the observable events in the testable code. I cannot tell you which option is better with information you given us.

A: There are a number of things wrong I guess you are thinking about:

*

*godMethod has multiple exits

*godMethod changes Observable2, which will trigger godMethod, potential infinite loop

The presence of a possible infinite loop shows that the logic for the required state hasn't been thought through. No one is going to specify "when this happens, the app should crash"
Similarly the multiple exits suggest that the logic isn't well defined.
Obviously your code here is just an example, so we don't know the real requirements. Ideally we would be able to distil them down to a single stateless function with a single exit point
state getNextState(status1, status2, observable2)
{
   ...???
   return requiredState
}

state
{
    status1;
    status2;
    observable1;
    observable2;
}

Where the distillation process shows where an input variable isn't used and can be removed, which you could link up in such a way as to avoid infinite loops and be triggered only when appropriate.
You would also expect to see various test methods checking all the combinations of inputs produce the expected output.
The end product might look very similar, but you would be a million times more sure that it was both correct and well thought out.


text:
Q: What is the difference of Pooled ByteBuf and UnPooled ByteBuf Under package io.netty.buffer, there exists many types of ByteBuf, such as PooledDirectByteBuf, PooledHeapByteBuf, UnpooledDirectByteBuf, UnpooledHeapByteBuf. Could anyone kindly explain their difference?

A: Pooled ByteBuf are what they name says... They are pooled which means they are not released directly but pooled so they can be reused again. This is mainly useful as allocating and deallocating of direct ByteBuf is expensive.


text:
Q: Yii2: How to generate a JSON object with "grouped by" with an SQL query? I have a PostgreSQL query with the columns address and price like this. This is a simple example of the result of the SQL query:

I need to send this previous data in a JSON object and also it has to be grouped by address. So I need something like this:
[
   {
      "address":"Elm Street 123",
      "name": {
         "John",
         "Maria",
         "George"
      }
   },
   {
      "address":"Piccadilly Street 456",
      "name": {
         "Robert"
      }
   },
]

I tried the next function to generated my desire JSON object but it doesn't generate the JSON object that I need:
Yii::$app->response->format = Response::FORMAT_JSON;
$persons = persons::find()
    ->select([
        'address',
        'name',
    ])
    ->asArray()
    ->all();

return $persons;

It generates this JSON object:
[
   {
      "address":"Elm Street 123",
      "name": "John"
   },
   {
      "address":"Elm Street 123",
      "name": "Maria"
   },
   {
      "address":"Piccadilly Street 456",
      "name": "Robert"
   },
   {
      "address":"Elm Street 123",
      "name": "George"
   },
]

I use the Yii2 framework so I am looking for a solution in PHP. Maybe a SQL solution can work but I am not sure.

A: SQL (and yii2) cant handle this natively. so I rearrange array to make struct:
Yii::$app->response->format = Response::FORMAT_JSON;
$persons = persons::find()
        ->select([
            'address',
            'name',
        ])
        ->asArray()
        ->all();
$result = [];
foreach ($persons as $person) {
    $address = $person['address'];
    if (!isset($result[$address])) {
        $result[$address] = ['address' => $address, 'name' => [],];
    }
    $result[$address]['name'][] = $person['name'];
}
return array_values($result);


text:
Q: How to create custom pagination link? Right now i have this link on paginate :
www.test.com/search/filter?page=1

www.test.com/search/filter?page=2

and what i want is this:
www.test.com/search?search=&page=2 and so on
Right now i have this:
{!! $properties->appends(['toggle' => Request::get('toggle'), 'search' => Request::get('search')])->render() !!}

How can i change this to have route like this what i want?
i found this:
Route::get('users', function () {
    $users = App\User::paginate(15);

    $users->setPath('custom/url');

    //
});

But problem is that i use one function for multiple stuff so i can not set path in controller.

A: You can keep your existing query like this. you can define one function in your controller
public function getExistingQueryParams()
{
    $existingQueryParams = [];

    foreach (request()->all() as $key => $value)
    {
        if ($key != 'page')
        {
            $existingQueryParams[$key] = urldecode($value);
        }
    }

    return $existingQueryParams;
}

In your controller's function which is returning the view  call this function.
$existingQuery = $this->getExistingQueryParams();

Pass this variable in your view and in your view you can use it like this
{{ $propertiers->appends($existingQuery)->links() }}


text:
Q: Как редактировать БД Mysql через Рнр? Дана Бд нужно было сделать вывод БД через пхп. Это не составило особой проблемы. Но вот как теперь сделать, чтобы эту же таблицу можно было редактировать и изменения сохранялись (в этой же таблице конечно)?
A: Посмотрите в сторону phpmyadmin.

PHPMyAdmin — веб-приложение с открытым кодом, написанное на языке PHP и представляющее собой веб-интерфейс для администрирования СУБД MySQL. PHPMyAdmin позволяет через браузер осуществлять администрирование сервера MySQL, запускать команды SQL и просматривать содержимое таблиц и баз данных. Приложение пользуется большой популярностью у веб-разработчиков, так как позволяет управлять СУБД MySQL без непосредственного ввода SQL команд, предоставляя дружественный интерфейс.


text:
Q: Jquery adding steps like on instructables.com If you go to http://www.instructables.com/ then click on Create->Step by step and as you click "Add step" it adds another step on top of the page and loads that new form. I would like to duplicate that functionality... Can someone point me to the correct direction?

A: Depending on the complexity of your Steps you may want to use something more geared for this than jQuery, Take a look at Knockout.js, backbone.js, and Angularjs. There are a lot of different frameworks out there that make this kind of thing very easy to do and subsequently maintain. These are just a few of the better known ones in my opinion.
That being said you can do this with jQuery, however the code will become very difficult to implement and maintain as your site grows in complexity. If you are dead set on using Jquery there are plenty of tutorials out there, take a look at the JQuery API Docs, which will give you a very good starting point on how to accomplish what you want. But for further help post code that you have tried, which you are having trouble with. That will get you far more help than your current question.


text:
Q: laptop battery isn't seen I have a laptop, which was most of the time on wired power. Now it seems to not work at all on battery and in Control Panel->Power Option battery isn't recognized at all(is 0%).
Do you have any idea about what can I do?
ps: my laptop is Acer Aspire 1640z and I'm using Windows XP SP3

A: Li-Ion batteries start to degrade as soon as they leave the factory.  There is nothing you can do to prevent it either.  Keeping the battery fully charged will make it degrade quicker.  Keeping the battery warm, like in a running laptop, will also speed its demise.  This degradation shows up as a gradual shrinking of the battery's capacity.
Wiki has some information and links.  There is a paper here that discusses it as well.
The battery also has circuitry in it that monitors the health of the battery.  This benifits from being able to "re-learn" the capicity of the battery by occasionaly running the battery through a complete charge/discharge cycle.
So the best way to keep your laptop battery healthy is to keep it about 50% charged, in the fridge, and occasionally get it out, run it down, charge it completely, then run it back down to 50% before putting it back in the fridge.
You shouldn't store a laptop battery in a very low state of charge, becuase the battery contains electronics that monitor the health of the battery which use up power.  If the battery charge gets too low then it becomes unsafe to charge it and the circuitry will kill the battery to prevent you from charging it.

A: Usually this means that the battery is dead. It happens when a laptop is left plugged in constantly for extended periods of time. People wrongly attribute this to "overcharging" which does not happen.
What actually happens in that Lithium-Ion batteries need to discharge and recharge from time to time, otherwise the cells become damaged. If you have it constantly plugged in then chances are that the battery cells have completely degraded.
If you have a friend with the same model of battery you can pop it in just to verify that it isn't something more serious, but it usually isn't.


text:
Q: Pandas - df.size() error: 'numpy.int64' object is not callable Using pandas, I'm trying to plot some data using:
df.size().unstack().plot(kind=barh)

but I got this error:
TypeError: 'numpy.int64' object is not callable

then I tried df.size() only and got the same error. Now I'm not sure what causes this because according to the documentation, DataFrame.size() should work fine. Any idea?

A: There is one problem you need omit () in DataFrame.size, but output is scalar, so impossible call unstack:
df.size

Sample:
df = pd.DataFrame({'A':list('abcdef'),
                   'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'D':[1,3,5,7,1,0],
                   'E':[5,3,6,9,2,4],
                   'F':list('aaabbb')})

print (df)
   A  B  C  D  E  F
0  a  4  7  1  5  a
1  b  5  8  3  3  a
2  c  4  9  5  6  a
3  d  5  4  7  9  b
4  e  5  2  1  2  b
5  f  4  3  0  4  b

a = df.size
print (a)
36

Maybe need groupby + GroupBy.size():
df1 = df.groupby(['F', 'B']).size().unstack()
print (df1)
B  4  5
F
a  2  1
b  1  2


text:
Q: Multiplying with plus or minus sign in front I am having a hard time following what happens in between these steps:
$\frac{L^2}{(1{\mp}e)}=L^2(1{\pm}e)$
How did the minus-plus sign move to the numerator after a change to a plus-minus sign?


text:
Q: what, besides Class objects, is stored in Perm Gen Space (sun 1.6 VM)? I am seeing 'java.lang.OutOfMemoryError: PermGen space' while running ~300 JUnit tests and using Spring context. Having a tough time figuring out what's eating up PermGen since:

*

*in steady state the app consumes about 90m of permgen space

*I've tried -XX:MaxPermSize=256m for unit tests - still running out

*With -XX:+TraceClassLoading and -XX:+TraceClassUnloading enabled, I see no additional "loading" events while executing the last 20-30 tests before the OutOfMemoryError.

The latter seemingly suggests that something besides Class objects is filling PermGen, no? If so, what could it be? For example, are there circumstances when class instances are stored in PermGen?
Here's my VM info:
$ java -version
java version "1.6.0_25"
Java(TM) SE Runtime Environment (build 1.6.0_25-b06)
Java HotSpot(TM) 64-Bit Server VM (build 20.0-b11, mixed mode)

related
FWIW, the root of my problem that precipitated this post turned out to be somewhat trivial: I assumed that Maven Surefire plugin inherits VM settings from MAVEN_OPTS (or VM instance running mvn) when it forks a VM - it does not (boo). One has to specify those explicitly using argLine in plugin's configuration. HTH.

A: Sometimes abuse of String.intern() can cause out of PermGen space errors since interned String instances are stored in PermGen.
This might be what you are seeing - try eliminating unnecessary String.intern() calls to see if this solves the problem. In general, I wouldn't recommend using String.intern() unless you are sure that both of the following are true:

*

*You are sure that only a limited number of Strings will be added

*You actually need such Strings to share the same object identity (e.g. if many instances of the same strings would consume unacceptable amounts of memory or you need to rely on == for String comparison for complex performance reasons)

A: Interned Strings are also stored in permgen, although hundreds of megabytes of string sseems unlikely.  Remember each Spring Bean for which you are using proxies is generating new classes on the fly at runtime to implement the interfaces that you're proxying.  (Or your classes if you're using CGLIB proxies, etc.)  So if you're creating a 'fresh' Spring ApplicationContext for each JUnit, you are in fact cranking out 300 copies of all your proxies etc.
Also remember instances of Class are unique per classloader, not across the entire permgen space, so there can in fact be duplicates depending on how your runs are set up (if it involves deployment in a container or something, although that also seems unlikely in a JUnit :) ).

A: I notice you are running a 64 bit JVM. These are known to use twice the actually memory on your machine because it requires twice as large of memory spaces per allocation.
If you have JUnit tests which actually load up a spring context (not so Unit after all), these will instantiate ALL of the beans in your appContext. This will most likely require more than 128mb (256mb on a 64bit box) of memory.
In my experience, it is not absurd to allocate half a gig or more to a large test suite on a 64 bit machine. Try upping it to 512mb or even 1gb.
These are the options I run one of my larger project's test suite with...
-Xms256m
-Xmx512m
-XX:MaxPermSize=512m


text:
Q: how to list groups along with its users using terminal in ubuntu 14.04.5? For example: Group workers have 2 users: john and jony . What command do I have to use to list the members of group workers ?
These commands don't serve my purpose:  compgen -u , compgen -g, cut -d ":" -f 1 /etc/passwd

A: Several options are available:
getent group <group_name> | cut -d":" -f4-

or
grep -iE "^adm" /etc/group | cut -d":" -f4-

Note you have to add the group name where I have "^adm, this will present members of that group.
See: man getent


text:
Q: CSS Navigation Drops only in Google Chrome. Rails Tutorial Feedback I am going through the awesome Rails Tutorial http://railstutorial.org/chapters/filling-in-the-layout#sec:custom_css I've run into an issue with the Navigation dropping down into the body of the page, but this only happens in Chrome (I'm on Linux, Ubuntu 10.10 if that matters). Here is a screenshot and a URL to show you actually what the navigation looks like before and after as I really can't explain it as well as I'd like. If I refresh a couple of times in Chrome it drops down the page like the "after" image I uploaded.
Here is a URL to the web page so you can recreate it:
http://afternoon-wind-61.heroku.com/pages/home
Try it in Chrome, Firefox and IE as well.
Any insight in why this is happening would be appreciated.

A: Adding
<%= javascript_include_tag :defaults %>

in /app/views/layouts/application.html.erb solved this issue for me.


text:
Q: Multiple natural keys for Django Serializer Consider I have he following model:
class BankLoan(models.Model):
    amount=models.IntegerField()
    issued_to_account = models.ForeignKey(Account)
    issued_by = models.ForeignKey(BankOfficer)
    issue_date = models.DateField()

For Django's serializer, it looked like I could only have 1 natural_key. However, my scenario calls for 2 foreign key. Could anybody help for this?

A: I made a mistake when asking this question.
Consider I have a BankLoan object
class BankLoan(models.Model):
    amount=models.IntegerField()
    issued_to_account = models.ForeignKey(Account)
    issued_by = models.ForeignKey(BankOfficer)
    issue_date = models.DateField()

And with Django Serializer, I want the JSON output to be
{
'pk' : 1,
'amount' : 100.00,
'issued_to_account' : 'john.doe',
'issued_by' : 'bank_teller_jane',
'issue_date' : '2016-06-20 12:00:00'
}

I should be relying on the natural_key method of the related models, instead of focusing on changing stuff on the serializer. In other words:
class Account(models.Model):
    def natural_key(self):
        return self.username

and so on


text:
Q: Is it possible for the adapter to send two items at a time to the dropdownlistview in android When i click on a item in dropdownlistview of android i want it to display the id of the respective item.
json data:
{"categories":[{"id":"1","name":"Beverages"},{"id":"2","name":"Bread"},{"id":"3","name":"Cereals"},{"id":"4","name":"Cheese"},{"id":"5","name":"Citrus Fruits"}]}


text:
Q: Largest value of sequence What is the idea of this problem?  I couldn't understand it

Any help would be much appreciated
EDIT: further details inside this post
Find $\max_{i \in \mathbb{N}} a_i$ where $a_i = \left\lfloor \frac{10^{i+1}}{7}\right\rfloor-100\left\lfloor\frac{10^{i-1}}{7}\right\rfloor$

A: The formula means "what is the largest digit in decimal expansion of $\dfrac 1{13}$" ?
Since $\dfrac 1{13}=0.\overline{076923}\cdots$ then this digit is $9$.
Multiply by $10^i$ shifts the sequence to the left for instance by $1000$ we get $76.923\overline{076923}\cdots$
The entire part is $76$. The other term is shifted one less place but multiplied by $10$ so it is $70$. The difference is $6$ which is the digit at this $3^{rd}$ place in the expansion.
You can write $\displaystyle \dfrac 1{13}=\sum_{k=1}^{\infty} d_k10^{-k}$ apply the formula above and realize you'll find $d_i$ as an answer.
I did it once in this post :
Find $\max_{i \in \mathbb{N}} a_i$ where $a_i = \left\lfloor \frac{10^{i+1}}{7}\right\rfloor-100\left\lfloor\frac{10^{i-1}}{7}\right\rfloor$
This is a bit tedious to write, please refer to that post for more details.

A: The period is $$0,7,6,9,2,3,$$ which gives that $9$ is a maximum.

A: The correct choice is $(D)$
The maximum value of $9$ occurs at $i=10$
that is $a_{10} =9$ is the largest.


text:
Q: Assign a global variable in a subclass and use it in the onCreate method - Android I created a public global variable, I assigned data it from a subclass and I want to use that data in the onCreate method. The problem is that the variable returns null in the onCreate method and returns the data in other subclass. Am just trying to get value from javascript and store it in Java variable in the onCreate method. I am relatively new to Java and android development. Any help is appreciated.
public class MainActivity extends AppCompatActivity {

// Initiallising the WebView
private WebView mywebView;

public String userData;

private GoogleApiClient client;

@SuppressLint("JavascriptInterface")
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Webview
    mywebView = (WebView) findViewById(R.id.myWebView);
    WebSettings webSettings = mywebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    mywebView.setWebViewClient(new MyWebViewClient());
    mywebView.addJavascriptInterface(new JavascriptBridge(this), "AndUser");

    mywebView.loadUrl("file:///android_asset/www/index.html");

    Toast t = Toast.makeText(getApplicationContext(), userData+" Tesing..." , Toast.LENGTH_LONG);
    t.show(); // returns null Testing...
}

public class JavascriptBridge{
    Context mContext;
    JavascriptBridge(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public String getUserDetails(String message){
        userData = message;
        return message;
    }
}

}

A:
I created a public global variable, I assigned data it from a subclass
  and I want to use that data in the onCreate method.

Java used a oops concept for accessing parent variable that can change your parent value : i.e
// parent
public class Parent {
    private int value = 0;
    public Parent( int initialValue ) {
        value = initialValue;
    }

    public void print() {
        System.out.println(value);
    }
}

// child class
public class Child extends Parent{
    public Child() {
       super( 1 ); /// This super keyword change your parent class variable.
    }
}

Perhaps if you have issue in create bridge than you can go through this Post.


text:
Q: Issues with sliding rtl and ltr in IE 7 I have a simple div sliding animation(built from scratch no thrid party) which works fine in IE10,FF,Chrome but in IE 7 it doesn't work.Even in IE 8 it works.
HTMl

CLick here to go to some content div which is next div and this div will go to the extreme left.

Some Content div.Click here to go to previous div.

CSS
.about_container {
    margin: 0px auto;
    position: relative;
    width: 500px;
    background:#ddd;
    height:300px
}
.whatwedo_container {
    position: absolute;
    right: -100%;
    width: 300px;
    background:#000;
    height:300px;
    color:#fff;
    top:0;
}
.aboutus {
    background: #20407B;
    height: 400px;
    margin-top: 0;
    position: relative;
    width: 100%;
}
.margin_slide {
  margin: auto 0;
  position: relative;
  width: 1100px;
}

JQuery
$('.about_container').click(function () {
    var $slideupto = $('.margin_slide');
    var ending_right = $(window).width() - $slideupto.offset().left;
    $('.about_container').animate({
        right: ending_right
    }, 600);
    var rightpos = $(window).width() - ($(".margin_slide").offset().left + $('.whatwedo_container').outerWidth());

    $('.whatwedo_container').animate({
        right: rightpos
    }, 800);
});

$('.whatwedo_container').click(function () {
    $('.about_container').animate({
        right: '0'
    }, 600);
     $('.whatwedo_container').animate({
        right: '-100%'
    }, 600);
});

Jsfiddle is http://jsfiddle.net/squidraj/uv6Q5/7/
IN ie 7 the div2 scrolls from right to left and takes the position of div 1 and div goes to further right.But when I click the div 2 to get back the div 1,the div 1 comes back in it's own position but div 2 doesn't go back to it's original position.
Any help please.Thanks in advance.

A: You could try this, for your animation function:
$('.whatwedo_container').animate({
        right: -($(window).width())
}, 600);

See fiddle.


text:
Q: How to specify offset using `@formula` and implement a similar function to `model.frame()` in R using Julia? Given the model formula, response family and DataFrame, I would like to return as the output of this function things such as n, p, model_matrix, model_response, model_offset. Offsets are very important for our use case but I cannot work out how to specify a formula within Julia accounting for offset terms.
function frame(formula,family,data)
    # code to implement something similar to `model.frame` function in R

   return model_matrix,model_response,model_response
end


text:
Q: Using "merge" and "include" I'm trying to put a copyright image in the bottom of my LinearLayout with an "include tag". I am doing it successfully, but when I'm trying to add android:layout_marginTop="330dp" or android:layout_marginBottom="20dp" for instance to my include - it doesn't show in the UI.
What is the problem ?
Here is my code:
copyrights.xml:
 <merge xmlns:android="http://schemas.android.com/apk/res/android">
    <ImageView
            android:src="@drawable/copyrights"
            android:id="@+id/copyrights"
            android:layout_width="fill_parent"
            android:layout_height="40dip"/>
</merge>

mylayout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
        <include layout="@layout/copyrights"  android:layout_marginTop="330dp"/>
    </LinearLayout>

A: The <include /> tag is basically a copy&paste instruction for the android layout framework. It's not an actual object in your layout hierachy. That means that it can't have margin/padding/size/any other layout property.
Assign the margin to the <ImageView /> in your layout instead.


text:
Q: Access http-only or secure cookies on Android devices React Native I'm current build a RN app with react-native-webview and @react-native-community/cookies.
Now, i need to access all cookies in webview. With some help of @react-native-community/cookies on ios devices, i can get all of this but on android i only get non-secure/non-httpOnly cookies.
Android devices is running on API 28.
Here my code:

*

*Implement webview

          <WebView
            ref={webViewRef}
            source={{uri: 'https://example.com'}}
            javaScriptEnabled={true}
            sharedCookiesEnabled={true}
            thirdPartyCookiesEnabled={true}
          />

*Get cookies

  useEffect(() => {
    let getCookies = () =>
      CookieManager.getAll(useWebKit).then((cookies) => {
        console.log('CookieManager.get =>', cookies);
      });

    if (Platform.OS === 'android') {
      getCookies = () =>
        CookieManager.get('https://linkedin.com').then((cookies) => {
          console.log('CookieManager.get =>', cookies);
        });
    }

    getCookies();
  }, [url]);

Thanks.

A: Try: CookieManager.setAccessCookie(true)


text:
Q: Ways around putting a password in code I have a bit of code that needs to run with elevated privileges (more that I want the rest of my code running at).
I have my code that sets up the Impersonation working, but it requires a username, domain and password.  As my code is in C#.net I know that the password can be found by anyone determined enough.
Is there a way to encrypt the password in my code?  Or otherwise secure this password and still be able to pass it in?
Here is the code I am calling:
using (new Impersonator("UserNameGoesHere", "DomainNameGoesGere", "Password Goes Here"))
{
     uint output;
     NetUserAdd(AUTHENTICATION_SERVER, 1, ref userinfo, out output);
     return output;
}

I would love an example that shows how to fix this to not show my password in plain text.
I am using Visual Studio 2008, .NET 3.5 SP1, and running on Windows Server 2003.

A: Vaccano,
I would recommend investigating the data protection API (DPAPI) for what you're attempting to achieve.  It is considered part of the solution in many best practice approaches to reversibly storing passwords needed by applications.
A good article discussing the DPAPI (and other techniques + concerns) can be found here:
http://msdn.microsoft.com/en-us/magazine/cc164054.aspx
With C# 2.0, P/Invoking isn't even required; managed wrappers exist:
http://blogs.freshlogicstudios.com/Posts/View.aspx?Id=41ca5a99-ddc0-4d0a-9919-2ce10bf50c7e
I hope this helps!

A: You have multiple options here.

*

*You can hash the password the very first time and store the hash to a file. Now the next time, you want to execute the code with elevated privileges, you need to accept/retype the password and re-compute the hash and match it with the stored hash. Only if it matches will you execute your code in elevation modes. You could hash using SHA. Please look at System.Crytography namespace for examples on hashing.

*Second option is to encrypt the password using algorithms like AES. However you will need to have a key to do this and you will have to worry about securing this key.

*Third option is to use DPAPI and encrypt the password but not worry about securing the keys - much easier option than 2.
I would recommend 1 if you do not mind re-entering the password every time the application starts. If that is not a possibility, I would suggest going with 3 and use DPAPI.
Here are some links to get you started.
1.http://www.obviex.com/samples/dpapi.aspx
2. http://www.obviex.com/samples/Encryption.aspx

A: You can use safe-config nuget package. Internally it uses data protection api to encrypt and decrypt data.
//Save some configuration data at folder data\temp\
var configManager = new ConfigManager()
    .WithOptions(DataProtectionScope.CurrentUser)
    .Set("password", "my-massword")
    .AtFolder(@"data\temp\")
    .Save();

    ...

//Load configuration data
var loadedValue = new ConfigManager()
    .AtFolder(@"data\temp\")
    .Load()
    .Get<string>("password");


text:
Q: 502 Bad Gateway When callback social of facebook by laravel I'm using package socialite of Laravel to login by facebook or gmail. In function callback social, It has been successfully login with google but it failed with facebook.
enter image description here
enter image description here


text:
Q: How can I determine if one rectangle is completely contained within another? I have a theoretical grid of overlapping rectangles that might look something like this:

But all I have to work with is a collection of Rectangle objects:
var shapes = new List<Rectangle>();
shapes.Add(new Rectangle(10, 10, 580, 380));
shapes.Add(new Rectangle(15, 20, 555, 100));
shapes.Add(new Rectangle(35, 50, 40, 75));
// ...

What I'd like to do is build a DOM-like structure where each rectangle has a ChildRectangles property, which contains the rectangles that are contained within it on the grid.
The end result should allow me to convert such a structure into XML, something along the lines of:
<grid>
  <shape rectangle="10, 10, 580, 380">
    <shape rectangle="5, 10, 555, 100">
      <shape rectangle="20, 30, 40, 75"/>
    </shape>
  </shape>
  <shape rectangle="etc..."/>
</grid>

But it's mainly that DOM-like structure in memory that I want, the output XML is just an example of how I might use such a structure.
The bit I'm stuck on is how to efficiently determine which rectangles belong in which.
NOTE No rectangles are partially contained within another, they're always completely inside another.
EDIT There will typically be hundreds of rectangles, should I just iterate through every rectangle to see if it's contained by another?
EDIT Someone has suggested Contains (not my finest moment, missing that!), but I'm not sure how best to build the DOM. For example, take the grandchild of the first rectangle, the parent does indeed contain the grandchild, but it shouldn't be a direct child, it should be the child of the parent's first child.

A: As @BeemerGuy points out, Rect.Contains will tell you whether one rectangle contains another.  Building the hierarchy is a bit more involved...
There's an O(N^2) solution in which for each rectangle you search the list of other rectangles to see if it fits inside.  The "owner" of each rectangle is the smallest rectangle that contains it.  Pseudocode:
foreach (rect in rectangles)
{
    owner = null
    foreach (possible_owner in rectangles)
    {
        if (possible_owner != rect)
        {
            if (possible_owner.contains(rect))
            {
                if (owner === null || owner.Contains(possible_owner))
                {
                    owner = possible_owner;
                }
            }
        }
    }
    // at this point you can record that `owner` contains `rect`
}

It's not terribly efficient, but it might be "fast enough" for your purposes.  I'm pretty sure I've seen an O(n log n) solution (it is just a sorting operation, after all), but it was somewhat more complex.

A: An average-case O(n log n) solution:
Think of your set of rectangles as a tree, where parent nodes "contain" the child nodes -- the same kind of thing as a DOM structure.  You'll be building the tree a rectangle at a time.
Make a dummy node to serve as the root of your tree.  Then, for each of your rectangles ("current_rect"), start with the root's children and work downwards until you find where it goes:
parent_node = root_node
sibling_nodes = [children of parent_node]

for this_node in sibling_nodes:
    if current_rect contains this_node:
        move this_node: make it a child of current_rect instead of parent_node
    elseif this_node contains current_rect:
        parent_node = this_node
        sibling_nodes = [children of parent_node]
        restart the "for" loop using new set of sibling_nodes

make current_rect a child of parent_node

The "contains" relation asks whether one rectangle contains the other.  "Parent", "child", and "sibling" are referring to the tree structure.
EDITED: Fixed a bug that would miss moving some nodes into current_rect.

A: Use the Contains() of a Rectangle.
Rectangle rect1, rect2;
// initialize them
if(rect1.Continas(rect2))
{
    // do...
}

UPDATE:
For future reference...
It's interesting to add that Rectangle also has IntersectsWith(Rectangle rect) in case you want to check if a rectangle partially collides with another rectangle.

A: Check that each point in the rectangle is within the bounds of the other rectangles.
In .NET the Rectangle class has a .Contains(Point) method.  Or you can check the corner point coordinates againt the target rect's .Left, .Right, .Top, and .Bottom properties.

A: pseudo code:
for i = 0 to rectangles.length - 2
 for j = i + 1 to rectangles.length - 1
     if rectangles[i].Contains(rectangles[j])
        //code here
}}}


text:
Q: Stable sort of 2 valued array? I have an array of objects. the objects have a Boolean value in them that I want to use as a key for sorting the array (all objects with true come before all objects with false) but otherwise leave things in the same order.
Is there a simple, in-place, O(n) solution to this? Maybe some variant of radix-sort?

A: See here for a discussion on this topic. You can basically have either an O(n)-solution which needs additional space or a O(n log n) in-place solution.

A: Merge sort. O(n log n).

A: Hmm. With a linked list it should be feasible - you'd search for the first "false" entry and keep it as the "insertion location". (If there are no "false" entries then you're done anyway :) Then just iterate through the whole list - if you're before the insertion location and find a "false" entry or if you're after the insertion location and find a "true" entry then move it to directly before the "insertion location". So far, so O(n).
Now you can convert an array into a linked list in O(n) and you can copy the data back into the array in O(n). So I think it would work in terms of complexity - but it's not in-place. I'll think about whether it can be done in-place...


text:
Q: Load text file to memory in Java I have wiki.txt file and its size is 50 MB.

*

*I need to do several things on the file and so I thought that the best way in terms of performance is to load the file to memory, is that correct?

*This is the code that I written:
File file = new File("wiki.txt");
FileInputStream fileInputStream = new FileInputStream(file);
FileChannel fileChannel = fileInputStream.getChannel();
MappedByteBuffer mapByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
System.out.println((char)mapByteBuffer.get());

I get error on this code: mapByteBuffer.get().
I tried the get() function a few options but all of them I get error and didn't even get an error on e.getMessage() I just got null.
Another important thing to note, my text file contains English words and actions I need to do is search, if expressed is exist in this text file.
Thank you.

A: I would suggest using a MemoryMappedFile, to read the file directly from the disk instead of loading it in memory.
RandomAccessFile file = new RandomAccessFile("wiki.txt", "r");
FileChannel channel = file.getChannel();
MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1024*50);

And then you can read the buffer as usual.

A: My answers for point (1):
It depends on what you want to do with the file. If your processing doesn't involve rewind operation (looking what was read behind/before), it's best to just read as a stream and process it in one go (instead of loading all into memory).
Even if you need random access across the file, you may also be interested in doing block file operation, because your solution may not scale well when the file size change to bigger size.
RandomAccessFile if you are on Java 1.4 or above.
For random access, the operating system usually handles the file buffer caching quite well you don't have to handle yourself.

A: It is important to read the whole error, not just the message.  Often the real information is in the exception's name not the text associated with it.
You will get an error if the file is empty as there is no first byte.
Note: the approach you are using assumes ASCII 7-bit characters.  If you want to assume ISO-8859-1 characters you can use  (char) (byteBuffer.get() & 0xFF)
However, if you have plan text you may find that using strings is simpler to use and not much slower. e.g. you can read a 50 MB file as text in less than a second.  I would only use a memory mapped file if this is far too long.

A: I would suggest to use BufferedReader. It is much faster and requires relatively less resources.
First read number of lines:
InputStream is = new BufferedInputStream(new FileInputStream(filename));
byte[] chars = new byte[1024];
int numberOfChars = 0;
while ((numberOfChars = is.read(chars)) != -1)
{
    for (int i = 0; i < numberOfChars; ++i)
    {
        if (chars[i] == '\n' && numberOfChars - i != 1)
        {
            ++count;
        }
    }
}
count++
return count; // number of lines

Then read the lines:
BufferedReader in = new BufferedReader(new FileReader(fileName));
for (int i = 0; i < endLine; i++)
{
    String oneLine = in.readLine();
}

In this strings you can even do search for what you need.


text:
Q: Mod_Rewrite Apache Remove 2 Files I am making a social network for my companies intranet. I have successfully been able to utilize htaccess to remove the index.php file from my url, however, there is a "profile.php" file that will allow a user to pull up another users profile. Is there a way to use .htaccess and mod_rewrite to remove both the index.php, and the profile.php?
This is my current htaccess file:
RewriteEngine on
RewriteCond $1 !^(index\.php|css|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

Again, I want to be able to remove the profile.php as well as the index.php.
Edit: I am running on cPanel's latest version on CentOS Server.

A: Since no one answered for over a week, I did this the roundabout way. I redirected all 404 requests to one profile.php excluding all existing files and directories.
I then removed only the profile.php, since index.php is listed as the directoryindex.
Upon completion, profile.php located the profile and displayed the necessary information.


text:
Q: Import X509 certificate to certlm with private key (.NET Core 6) I am generating X509 certificates to authorize apps in Azure using .NET using the below code:
private static X509Certificate2 BuildSelfSignedCertificate(string CertificateName, int DaysValid)
        {
            SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
            sanBuilder.AddIpAddress(IPAddress.Loopback);
            sanBuilder.AddIpAddress(IPAddress.IPv6Loopback);
            sanBuilder.AddDnsName("localhost");
            sanBuilder.AddDnsName(Environment.MachineName);

            X500DistinguishedName distinguishedName = new X500DistinguishedName($"CN={CertificateName}");

            using RSA rsa = RSA.Create(2048);
            var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

            request.CertificateExtensions.Add(
                new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false));

            request.CertificateExtensions.Add(
               new X509EnhancedKeyUsageExtension(
                   new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false));

            request.CertificateExtensions.Add(sanBuilder.Build());

            var certificate = request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(DaysValid)));
#pragma warning disable CA1416 // Validate platform compatibility
            certificate.FriendlyName = CertificateName;
#pragma warning restore CA1416 // Validate platform compatibility

            return certificate;
        }

This works great, but when I import it the cert using the following, the private key is not included:
X509Store store = new(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadWrite);
            store.Add(cert);
            store.Close();

However, if I export the cert to a byte array and create a new X509Certificate2 object from the array, the private key is imported correctly.
var cert = new X509Certificate2(certificate.Export(X509ContentType.Pkcs12, "password"), "password", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);

Notice the "You have a private key that corresponds to this certificate" message.
How can I import the cert + private key without resorting to this awkward workaround?

A:
How can I import the cert + private key without resorting to this awkward workaround?

By creating the key as a persisted key to begin with.
using RSA rsa = RSA.Create(2048);

This line creates an ephemeral (in-memory only) private key.  Instead you can do
CngKeyCreationParameters keyParams = new CngKeyCreationParameters
{
    ExportPolicy = CngExportPolicies.AllowPlaintextExport,
    KeyCreationOptions = CngKeyCreationOptions.MachineKey,
    Parameters =
    {
        new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.Persist),
    },
};

using CngKey cngKey = CngKey.Create(CngAlgorithm.Rsa, Guid.NewGuid().ToString("D"), keyParams);
using RSA rsa = new RSACng(cngKey);

And now the created certificate is associated with an already-persisted key.
(Note that this snippet uses MachineKey and exportable because that's what the question has as the PFX import flags)


text:
Q: What does the term 'hyperbolic model' mean? I am reading this non-linear discrete dynamical system paper. The authors mention the term hyperbolic model. What does that mean?

A: I suppose it is related to hyperbolic partial differential equations.

A: Example of a hyperbolic system, the first order wave equation: $ {\partial \underline{U} \over \partial t} + \underline{A} {\partial \underline{U} \over \partial x} = 0$
The term hyperbolic means that:

*

*The eigenvalues of the $m \times m$ Jacobian matrix ($\underline A $) are all real

*There is a corresponding set of $m$ linearly independent eigenvectors

This allows decomposition of the system into a linear combination of these eigenvectors, where the corresponding eigenvalues of $\underline{A}$ give the wave speeds.


text:
Q: Push–Relabel Maximum Flow Algorithm $x_f(s)\leq0$ I'm looking at Push–Relabel Maximum Flow Algorithm (or Goldberg-Tarjan Algorithm) and trying to solve some homework question.
As part of the answer I'm trying to prove $x_{f}(s)\leq0$
  during the entire algorithm run (where $s$
  is the source, and $x_{f}:V\to\mathbb{R}$
  is the excess function $x_{f}\left(u\right)=\underset{v\in V}{\sum}f\left(v,u\right)$
 ).
I feel like this somehow should be trivial, but no matter what I've tried, I was unable to prove it.
I know pushes into $s$ are possible
 , just not sure how to show they don't make $x_{f}\left(s\right)>0$
 .
I assume the proof would be by induction, as at the start $x_{f}\left(s\right)\leq0$
  since the initialization step saturates all of $s$
 's adjancet nodes.
If we assume $x_{f}\left(s\right)\leq0$
 , we have to show that after one iteration of the algorithm it still holds.

*

*Lift is trivial since it doesn't change the flow.

*A Push from nodes unrelated to s is trivial as well.

*A Push from s to any other node would decrease $x_{f}\left(s\right)$
so that is trivial as well.

*I'm only left with the case $Push\left(u,s\right)$.

Help or direction would be appreciated,Thanks!

A: In a preflow, at a certain moment, the potential excess to be pushed to $s$ is the sum of all $e(v), v \in V - \{s,t\}$, where $e$ is the net flow into a vertex, as defined in the original paper.
Here we define the sum of $e(v)$ aformentioned in a certain iteration as $p$, it can be shown that in a push operation between two vertices other than $s,t$, it is not changed. And it can only be reduced when pushing to $s$ or $t$. When push to $s$, $x_f(s)$ reduces as much as $p$ recudes. In other words, $p$ is the potential amount of reduction that might be applied to $s$.
As a result, during the whole execution, there does not exist a moment when $p$ can be larger than that after the initialization.
After the initialization, the sum of $e(v)$ is just equal to $x_f(s)$. That is it.


text:
Q: Modify Path Param of an HttpServletRequest I have a method which processes that URL:
http://IP:PORT/auth/myapp?Username=username

and accessible from remote. However I can not change external system which uses my app and it sends username within HTTP Header. I mean they access that URL:
http://IP:PORT/auth/myapp

I think that I can get related HTTP Header as follows:
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
    String headerName = (String)headerNames.nextElement();
    if (headerName.equals("UNAME")) {
        String username = request.getHeader(headerName);
    }
}

I can not modify whole part of my app and I have to add that info as path parameter into existing request. I mean change that request to:
http://IP:PORT/auth/myapp?Username=username

How can I do that?
PS:
Can this piece of code solve the problem that I've described?
if (request.getParameter("Username") == null) {
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        if (headerName.equals("UNAME")) {
            String username = request.getHeader(headerName);
            response.sendRedirect(request.getRequestURI() + "&Username="+username);
        }
    }
}

A: If you are accessing 'username' query parameter using HttpServletRequest.getParameter('username') in other parts of your app, you can try using HttpServletRequestWrapper
class MyRequestWrapper extends HttpServletRequestWrapper{

    public String getParameter(String name){
        // if name equals username, call super.getHeader('username')
        //else super.getParameter(name);
    }
}

You can extend this class and override getParameter() method. In your implementation, you get the value from header if parameter name is username else call the super method.

A: I think there is two solutions:

*

*Use a filter on your application mapped on each request. The filter will check header and add a parameter if the UNAME header is there

*Use Apache Rewrite Module in front of your web application. Rewrite module will add the parameter to the url (check "Module Apache mod_rewrite")

UPDATE: As mohit said used a HttpRequestWrapper combined with a filter
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
        FilterChain filterChain) throws IOException, ServletException {
        //create the MyCustomWrapperRequest object to wrap the HttpServletRequest
        MyCustomWrapperRequest request = new MyCustomWrapperRequest((HttpServletRequest)servletRequest);
        //continue on in the filter chain
        filterChain.doFilter(request, servletResponse);
}

And in MyCustomWrapperRequest override getParameter() function

A: It's round-a-bout, but if you also have the HttpServletResponse object, you can send a redirect request to the http://IP:PORT/auth/myapp?Username=username URL


text:
Q: Wikidata property statement and property direct I'm trying to retrieve entities as well as their properties that relate to Golden Gate Bridge. I used this query (https://query.wikidata.org/#SELECT%20%3Fp2%20%3Fs%0AWHERE%0A%7B%0A%20%20%09%3Fs%20%3Fp2%20wd%3AQ44440%20.%0A%7D):
SELECT ?p2 ?s
WHERE
{
    ?s ?p2 wd:Q44440 .
}

But I noticed that in the result, property "p:statement/P800" and property "wdt:P800" actually point to the same thing. They have the same id. I'm wondering why it returns both. What is their difference? How do I just get one?
I use DBpedia a lot, so I'm not familiar with they uri schemes in Wikidata, it's quite confusing.

A: I guess it has something to do with the option to do reification on the statements itself, at least that's what I understand from the documentation here: https://www.wikidata.org/wiki/Wikidata:Glossary#Claims_and_statements That's why they use multiple namespace for the same property. You can see it better if you change your query to
SELECT ?s ?p
WHERE
{
    ?s ?p wd:Q44440 .
    ?p a owl:ObjectProperty
}

It returns, among others,
+-------------------------------------------------------------+------------------+
|                              s                              |        p         |
+-------------------------------------------------------------+------------------+
| wd:Q16803333                                                | wdt:P301         |
| wd:Q261174                                                  | wdt:P800         |
| wd:Q950029                                                  | wdt:P921         |
| wd:statement/Q16803333-12EFD280-98AF-4CA1-BEA3-5C142674827D | p:statement/P301 |
| wd:statement/Q261174-4B53E291-A47B-48E3-AE28-7FDE75849E28   | p:statement/P800 |
| wd:statement/Q950029-fd9f357a-45ff-403a-86ba-b462acb2ffbd   | p:statement/P921 |
+-------------------------------------------------------------+------------------+

In that case you can see that the subjects also have a different namespace with statement as keyword. And about those statements you could make statements as well, called reification.


text:
Q: Custom Yii2 grid ActionButton I've problem with a section of code that I've created to generate dinamically buttons that I need to include in my yii2 Grid ActionColumn. With this function I can define a button just specifying an array of parameter:

*

*name

*controller (destination)

*icon

Function works pretty good, but I can't replace the static string "my name" with my variabile $config['icon'] because I can't send the value to the function.
Can I solve this problem? (I'm using Kartik grid estension)
foreach(...) {
  $actionColumns['controller'] = $config['controller'];
  $actionColumns['buttons']    = array($config['name'] => function ($url, $model, $key) {
                                                        return Html::a('my name', $url);
                                                    });
  $actionColumns['template']   = '{'.$config['name'].'}';
}

Ty

A: I think you can passing the value by use for closure
 function ($url, $model, $key)   use  ($config['icon'])
 {
   .....
 }

so in your case
foreach(...) {
   $actionColumns['controller'] = $config['controller'];
   $actionColumns['buttons']    = array($config['name'] =>
          function ($url, $model, $key) use  ($config['icon']) {
                  return Html::a($config['icon'], $url);
          });
   $actionColumns['template']   = '{'.$config['name'].'}';
}


text:
Q: mysql select user only if they are in the top 12 newest records I want to run a check to see if the username is in the top 12 most recent registered users. I only want mysql to return a result if they are in the 12 most recent. I want to sort it by id.
I've tried:
  Select * FROM users WHERE uname ='$uname' ORDER BY id DESC LIMIT 12

When I run this query, it shows the username weather they are in the top 12 most recent or not. Any ideas?
I didn't put a timestamp or date on the register form, so it needs to be sorted by id.
Thanks!

A: If you want check if the uname is in the last 12  (assuming that you have an auto_increment  id ) you could select the most recent in subquery and join for what you are looking
  select uname  from users WHERE uname ='$uname'
  INNER JOIN (
    Select uname  FROM users ORDER BY id DESC LIMIT 12
  ) t on tuname = users.uname

A: You should look for "recent registered users" and then for uname in this...
Something like this where dateRegistered is you column name where you have the registered date data...
select * FROM users
 WHERE uname in (select uname FROM users ORDER BY dateRegistered DESC LIMIT 12)


text:
Q: How to pass query string values to .ashx and return a value in Javascript I had .aspx webform wherein I would like to use javascript to show google earth from the generated kml.
I am grabbing parameters from other form and redirecting to current webform  and pass parameters to a handler file which would generate a kml file based on parameters I pass to the .ashx handler file.
In the handler file, I am able to generate kmlstring along with kml filepath.
I would like to return that kml path back to the .aspx webform from which I passed the parameters.
In simple words, I would like to have a function in javascript wherein I pass parameters to .ashx file and in return the .ashx file would return the generated kmlpath.
Rest,I would manage with the javascript code for showing the kml in google earth.
Please anyone of you can guide me how to do it so that I can implement the same.

A: var kmlFile;
            var url = "MultipleKML_TKHH.ashx";
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                XMLHttpRequestObject = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
            }

            XMLHttpRequestObject.open("GET", url, false);
            XMLHttpRequestObject.send();
            kmlFile = XMLHttpRequestObject.responseText;
            //alert(kmlFile);


text:
Q: Is it possible yet to use Decodable with Firestore Timestamps/Dates? I have a dictionary that's a [String: Bookmark] but that createdAt is saved as a Timestamp and the decoder throws an error when trying to make sense of the Date

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSDate)'

struct Bookmark: Decodable {
    let messageId: String
    let messageCreatedAt: Date
}

JSONDecoder().decode([String: Bookmark].self, data: data)

Is there a way yet to make Swift's Decodable protocol play nicely with Firestore Timestamps?
Edit:
If I print the [String: Any] and then try to decode in the console like so
 ▿ 1 : 2 elements
    - key : "messageCreatedAt"
    - value : 2018-11-27 20:59:11 +0000

po valueDict["messageCreatedAt"] as? Date

I get
▿ Optional<Date>
  ▿ some : 2018-11-27 20:59:11 +0000
    - timeIntervalSinceReferenceDate : 565045151.531769

So it must be something in Decodable then that isn't able to identify and parse this?
Edit:
JSON is
{
  "messageId": "abc123",
  "messageCreatedAt": "2018-11-27 20:59:11 +0000"
}

A: How is JSONDecoder is decoding dates is defined by value of .dateDecodingStrategy property.
If you have to parse Date from a string you should use either .iso8601 or .formatted(_:) (or if your date format is really custom and complicated and/or weird you may to have use .custom(_:)).
Your date string is almost ISO 8601 formatted (it only lacks T between date and time parts), but that's enough to fail.
So your best option here is to use formatted(_:):
// Declare it somewhere and reuse single instance as much as possible, formatter initialization is quite expensive
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // Better to fix Locale here
dateFormatter.dateFormat = "yyyy-MM-dd kk:mm:ss Z"

And then
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)
let bookmark = try decoder.decode(Bookmark.self, from: data)

print(bookmark.messageCreatedAt, bookmark.messageCreatedAt.timeIntervalSince1970)
// prints "2018-11-27 20:59:11 +0000 1543352351.0"


text:
Q: In ggplot2, how to choose which geom appears in legend? Some geom obscure the key to other geoms in the legend (notably, boxplot)
How can I choose which geom appears in the legend?
Eg.:
qplot(data=CO2,
      x=Type,
      y=uptake,
      colour=Plant,
      shape=Treatment)+
        geom_boxplot()

Switching the order of the geoms helps
qplot(data=CO2,
      x=Type,
      y=uptake,
      colour=Plant,
      shape=Treatment,
      geom="boxplot")+
        geom_point()

But I would like the legend found with:
qplot(data=CO2,
      x=Type,
      y=uptake,
      colour=Plant,
      shape=Treatment)

Do I need to extract the legend of one plot and paste it to the other using something like gridExtra?

A: You can suppress the legend for the boxplot by adding show_guide=FALSE to the geom_boxplot() call. You still get the legend from the points.
qplot(data=CO2,
      x=Type,
      y=uptake,
      colour=Plant,
      shape=Treatment)+
        geom_boxplot(show_guide=FALSE)

If you were not already plotting points (that is, just had boxplot, but wanted the legend to be shown with points symbol rather than the boxplot symbol), that is harder, though I think possible.


text:
Q: Alternative to cookie based session/authentication Is there an alternative to the session feature plugin in servicestack? In some scenarios I cannot use cookies to match the authorized session in my service implementation. Is there a possibility to resolve the session using a token in http header of the request? What is the preferred solution for that in case the browser is blocking cookies?

A: I'm using ServiceStack without the built-in auth and session providers.
I use a attribute as request filter to collect the user information (id and token), either from a cookie, request header or string parameter.
You can provide this information after the user takes login. You append a new cookie to the response and inject the id and token info on clientside when rendering the view, so you can use for http headers and query parameters for links.
public class AuthenticationAttribute : Attribute, IHasRequestFilter
{
    public void RequestFilter(IHttpRequest request, IHttpResponse response, object dto)
    {
        var userAuth = new UserAuth { };
        if(!string.IsNullOrWhiteSpace(request.GetCookieValue("auth"))
        {
            userAuth = (UserAuth)request.GetCookieValue("auth");

        }
        else if (!string.IsNullOrEmpty(request.Headers.Get("auth-key")) &&
            !string.IsNullOrEmpty(request.Headers.Get("auth-id")))
        {
            userAuth.Id = request.Headers.Get("id");
            userAuth.Token = request.Headers.Get("token");
        }
        authenticationService.Authenticate(userAuth.Id, userAuth.token);
    }
    public IHasRequestFilter Copy()
    {
        return new AuthenticationAttribute();
    }
    public int Priority { get { return -3; } } // negative are executed before global requests
}

If the user isn't authorized, i redirect him at this point.
My project supports SPA. If the user consumes the API with xmlhttprequests, the authentication stuff is done with headers. I inject that information on AngularJS when the page is loaded, and reuse it on all request (partial views, api consuming, etc). ServiceStack is powerful for this type of stuff, you can easily configure your AngularJS app and ServiceStack view engine to work side by side, validating every requests, globalizing your app, etc.
In case you don't have cookies and the requests aren't called by javascript, you can support the authentication without cookies if you always generate the links passing the id and token as query parameters, and pass them through hidden input on forms, for example.

A: @Guilherme Cardoso: In my current solution I am using a PreRequestFilters and the built-in session feature.
My workflow/workaround is the following:
When the user gets authorized I took the cookie and send it to the client by using an http header. Now the client can call services if the cookie is set in a http-header (Authorization) of the request.
To achieve this I redirect the faked authorization header to the cookie of the request using a PreRequestFilter. Now I am able to use the session feature. Feels like a hack but works for the moment ;-)
public class CookieRestoreFromAuthorizationHeaderPlugin : IPlugin
{
    public void Register(IAppHost appHost)
    {
        appHost.PreRequestFilters.Add((req, res) =>
            {
                var cookieValue = req.GetCookieValue("ss-id");

                if(!string.IsNullOrEmpty(cookieValue))
                    return;

                var authorizationHeader = req.Headers.Get("Authorization");

                if (!string.IsNullOrEmpty(authorizationHeader) && authorizationHeader.ToLower().StartsWith("basictoken "))
                {
                    var cookie = Encoding.UTF8.GetString(Convert.FromBase64String(authorizationHeader.Split(' ').Last()));

                    req.Cookies.Add("ss-id",new Cookie("ss-id",cookie));
                    req.Items.Add("ss-id",cookie);
                }
            });
    }
}


text:
Q: python print a list of items So im pretty new at python and I have a problem I can`t really get my head around. I keep getting an error from a firebase uploader script. It works fine with just 1 item however from my json file i need it to take more than one fields and everytime I try to add another field for it to read it throws me an error

"AttributeError: 'dict' object" has no attribute 'item'.

So bellow is the part of code that when changed stops working.
    def main():
pool = Pool(processes=100)
data= []
try:
    data = getData(JSON_FILE)
except:
    print("please format the json file properly. Parsing error")
print(len(data))
index = 0
for item in data:
    print(str(index)+' items out of '+str(len(data))+' is done.')
    if item.item['email_client', 'persoana_contact'] != '' :
        postClientData(items)
    index+=1
pool.close()

And it worked fine with this bit:
for item in data:
    print(str(index)+' items out of '+str(len(data))+' is done.')
    if item['persoana_contact'] != '' :
        postClientData(item)

So what am I doing wrong, how can I make the script take more than 1 item from my json file and create the Client entity as it should?

A: your problem is in item.item['email_client', 'persoana_contact'] != ''
for item in data:
...
# wrong
# if item.item['email_client', 'persoana_contact'] != '' :
      ..

# maybe you need something like this ?
if item['email_client'] != '' or item['persoana_contact'] != '':
    ...


text:
Q: Retrieve nearby places of a current location I am working on an application where I need to retrieve nearby restaurants of a current location. Forums suggested me to use Google Places API.
When I read about Google Place API, it says that a project needs to be a "Google App Engine project" + Android client. But I got confused that will that be a right way of doing it as I am fairly new to Google world.
Can someone suggest me which will be the best way of retrieving nearby restaurants of a current location?
Thanks.

A: follow this link.
Create an app key for your app & You only have to make an Http request, & you will get all info in Xml//json.
https://developers.google.com/places/documentation/
https://maps.googleapis.com/maps/api/place/search/xml?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AddYourOwnKeyHere
In above url, Add your Api key & locaton. It will return a xml to you containing all restras in circle of 500m.
this url will only accept get Requests. Yov will have to append all parameters in Url itself.
@Override
                public void run()
                {
                     String params="location="+(location.getLatitude())+","+(location.getLongitude())+"&radius=5000&types=food&sensor=false&key=your kay";
                        try
                        {
                            http.getPlaces(new URL("https://maps.googleapis.com/maps/api/place/search/xml?"+params));
                            Log.i("url", "https://maps.googleapis.com/maps/api/place/search/xml?"+params);
                            setList();
                        }
                        catch (MalformedURLException e)
                        {
                            e.printStackTrace();
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }

                }
            });

public void getPlacesDetails(URL url) throws Exception {
    try
    {
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        connection.setConnectTimeout(TIMEOUT_CONNECT_MILLIS);
        connection.setReadTimeout(TIMEOUT_READ_MILLIS);
        connection.setRequestMethod("GET");

        inStream = (InputStream) connection.getInputStream();

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        HospitalDetailParser myXMLHandler = new HospitalDetailParser();
        xr.setContentHandler(myXMLHandler);
        xr.parse(new InputSource(inStream));

    }

    catch (MalformedURLException e)
    {

        Log.i("exception in sms", "" + e.toString());
        throw e;
    }

    catch (Exception e)
    {

        Log.i("exception in sms", "" + e.toString());
        throw e;
    }

}


text:
Q: Why data fetching from Redis is very slow on AWS Instance First I installed redis on my local machine(Ubuntu 14.04) using following links.
https://www.digitalocean.com/community/tutorials/how-to-install-and-use-redis
https://www.digitalocean.com/community/tutorials/how-to-set-up-a-redis-server-as-a-session-handler-for-php-on-ubuntu-14-04
I am using hashes for storing data in redis. The query took about 300 ms when there is a db hit and took 60-70ms when it fetches from redis. After that I do the same thing on my ubuntu AMI which is m4 large but unfortunately I din't see any changes in response time and sometimes it took more time than db hit. I don't know where I am missing.
    $this->redis = New \Redis();
    $this->redis->connect('127.0.0.1', 6379);
    $this->redis-hset($id, $key, serialize($result));
    if($this->redis->hexists($id,$key)) {
         return $this->redis->hget($id, $key);
    }

And I am sure that it fetches data from redis when it is available in redis.

A: I would suggest trying another instance type. The m4.large is only a 2 core instance type, maybe try a 4 core? Or use the AWS elastic-cache redis service.
Might find some helpful info here as well.

A: Benchmark serialization time - for more complex data serialization/unserialization is much longer than actual writing to redis. ( check http://kiss-web.blogspot.com/2016/02/memcached-vs-redisphpredis-vs-predis-vs.html )


text: Q: Let $R_i$ be a family of integrally closed domains contained in a bigger domain. Then is $\cap_i R_i$ integrally closed? Let $R_i$ be a family of integrally closed domains contained in a bigger domain. Then is $\cap_i R_i$ integrally closed ?


text:
Q: How can I randomize the position of a button with Tkinter? I would like the buttons to be placed in random points of the root. I do not understand why they all stack in the middle, since I think I am placing them at random x and y
import tkinter as tk
from tkinter import *
from random import randint

num_buttons = int(input("How many buttons do you want?"))
buttons = [0] * num_buttons

root = tk.Tk()

canvas = tk.Canvas(root, height=700, width=700, bg="dark slate grey")
canvas.pack()

frame = tk.Frame(root, bg="red")
frame.place(relheight=0.6, relwidth=0.6, rely=0.2, relx=0.2)

for k in range(num_buttons):
    randx = int(randint(-100,100))
    randy = int(randint(-100,100))
    buttons[k] = tk.Button(frame, text="DO NOT CLICK ME",
                            fg="Black", highlightbackground="orange",
                            command=you_clicked)
    buttons[k].place(x=randx, y=randy)
    buttons[k].pack()

root.mainloop()

A: You should not be calling both place and pack. Only one geometry manager can control a widget. When you call pack, any effect a previous call to place is thrown away.


text:
Q: How to synchronize wxpython Gauge widget with threads in python? My python project has multiple threads running. I want to add a gauge widget from the wxpython library to show the progress. I want the gauge to fill until my first thread completes. How do I achieve this? I am using Python 2.7 on Windows.

A: Use wx.CallAfter
def add_to_the_gauge(value):
    your_gauge.Value += value

...
#in some thread
def some_thread_running():
    wx.CallAfter(add_to_the_gauge, 2)

A: You need to post events from your worker thread to the main thread asking it to update the gauge, see this overview.

A: You can use some simple things
remember to import the module:
import os

and then put this on the frame
def __init__(self, *a, **k):
    filename = 'game.exe'

    self.timer = wx.Timer()
    self.Bind(wx.EVT_TIMER, self.OnUpdateGauge, self.timer)
    self.timer.Start()
    self.proc = os.popen(filename) # start the process

def OnUpdateGauge(self, event):
    if self.proc.poll() == None: # return None if still running and 0 if stopped
        self.timer.Stop()
        return
    else:
        '''do something with the gauge'''

hope those help


text:
Q: When does $\overline{U(0,1)}=B(0,1)$ hold? Given $R$ an absolute valued ring (with unit), sometimes $\overline{U(0,1)}=B(0,1)$ (for example, $\mathbb{Q},\mathbb{R},\mathbb{C},\mathbb{H}$) and sometimes $\overline{U(0,1)}\neq B(0,1)$ (for example, $\mathbb{Q}_p, \mathbb{Z}$).
Which properties must we impose to $R$ to ensure the identity holds or not?
Smells like the archimedean property has something to say here (p-adic example). But also $B(0,1)$ must be "full" in some sense (compare $\mathbb{Z}$ with $\mathbb{Z}[1/2]$, the latter satisfying the identity). Not sure if inverses really matter.
Also, all my counterexamples satisfy that the open ball is clopen. I wonder if there's a counterexample with a nonclosed open ball or if it is a necessary condition.
Edit: I forgot to say that $U(0,1)=\{x\in R\,:\,|x|<1\}$ and $B(0,1)=\{x\in R\,:\,|x|\leq 1\}$.

A: I believe a complete algebraic closure of the p-adic numbers has the property that the closed unit ball is the closure of the open.
If so, no sort of archimedean property is involved.


text:
Q: maximize flux integral Let S be the unit sphere. I am going to give you three fields, F1,F2,F3. For each
field, you are allowed to choose a subset of the sphere, S1, S2, S3. Your goal is to
make the flux integral as large as possible in each case. Then calculate
each integral.
a) F1 = e_r
b) F2 = i.
c) F3 = < x, y, z + 2>
Well, if I understand the question correctly, I am picking three separate regions of the sphere and I have to maximize the flux of F1 through S1. Can I just take the derivative of F.dS and set it equal to 0?


text:
Q: refresh the uitableview contents I have added uitableview in which I am trying to add custom UIButton. It is added successfully with this code:
    image=[UIButton buttonWithType:UIButtonTypeCustom];
    image.frame=CGRectMake(240, 7, 25, 25);
    image.tag=101;

    image2=[UIButton buttonWithType:UIButtonTypeCustom];
    image2.frame=CGRectMake(240, 7, 25, 25);
    image2.tag=102;

    if ([outputlabel.text isEqualToString:@"Yes"]||[outputlabel.text isEqualToString:@"Yes"]) {
        [image setImage:[UIImage imageNamed:@"tick.png"] forState:UIControlStateNormal];
        [cell1.contentView addSubview:image];
        [cell1.contentView bringSubviewToFront:image];
    }
    else
    {
        [image2 setImage:[UIImage imageNamed:@"cross.png"] forState:UIControlStateNormal];
        [cell1.contentView addSubview:image2];
        [cell1.contentView bringSubviewToFront:image2];
    }

Its working fine at first. When table view reload it overlaps the uibutton old image. I am unable to refresh the whole table with new values. Someone has an idea what I am doing wrong in code.

A: Updated. Always Create content view for cell in cell == nil block. Use that contentview outside by the tag.. Then only it wont overlap and reuse ur cell perfectly..
if (cell == nil)
{

cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIndentifier];

//Add your button here.. set the tag.
   UIButton image=[UIButton buttonWithType:UIButtonTypeCustom];
    image.frame=CGRectMake(240, 7, 25, 25);
    image.tag=101;
}

    UIButton *btn = (UIButton *)[cell.contentView viewWithTag:101];

    if ([outputlabel.text isEqualToString:@"Yes"]||[outputlabel.text isEqualToString:@"Yes"])
        {
                [btn setImage:[UIImage imageNamed:@"tick.png"] forState:UIControlStateNormal];
            }
            else
            {
                [btn setImage:[UIImage imageNamed:@"cross.png"] forState:UIControlStateNormal];
            }

Just do like this in cellForRowAtIndexPath.. It will helpful for you..

A: Basically, if we want to refersh the contents of tableview then need to use this reloadData. Did you try :-
[yourTableView reloadData];

A: Make sure you implement -cellForRowAtIndexPath:. Then refresh your tableViewCells by calling reloadRowsAtIndexPaths:withRowAnimation: on the tableView in question.
The tableView will in turn call cellForRowAtIndexPath, and you simply return the configured cells there.
If you have static cells, you can simply access whatever you need to change by hooking the controls up to an IBOutlet.

A: Try refreshing your cell's view using
[cell1.contentView setNeedsDisplay:TRUE];

every time you set the image.

A: I am suspecting, that you adding this images in -tableView:cellForRawAtIndexPath: method.
First of all - if you reusing cell with some reuse identifier, the Cell will stay in memory and will reused when it needed. It's means that all subviews of your cell will be retained. In this case you need to prepare cell for reusing every time. For example - remove all subViews of cell.
But better way, I recommend in case of less number of operations - to create subclass of UITableViewCell and add UIButton as a property of that cell.
Then you will only need to change this property depend of your condition.
if ([outputlabel.text isEqualToString:@"Yes"]) {
    [cell1.button setImage:[UIImage imageNamed:@"tick.png"] forState:UIControlStateNormal];
}
else
{
    [cell1.image setImage:[UIImage imageNamed:@"cross.png"] forState:UIControlStateNormal];
}

Of course, you button must be added in cell.contentView in the Cell initialiser. Usually it is method -initWithStyle:reuseIdentifier: of your custom cell .m file.


text:
Q: Manual overriding a DC-motor with H-bridge I have created the following circuit where I use a VNH7070BASTR full bridge motor driver to control a DC-motor. The goal is to open and close a drawer using a rack and pinion system. A new requirement that I have is that the drawer can ALWAYS be opened in case of failure somewhere in the circuitry controlling the driver. I want to use an external switch to move the motor in one direction. But I am not sure how to design this correctly.
I thought of shorting directly using a relay or a FET. However I am not sure how to deal with an open state of the H-Bridge. How could one implement such override?