text:
Q: How to change constants and useEffect in reactjs from a function to a render component I have this code in a function
function Lobby () {

but I wanted to pass it on to class Lobby extends Component {
for a component with
render () {
    return (

but putting these const and useEffect ect .. gives me an error,
is there any way to "translate" this into a component?
I thank those who can help me
original code:
   function Lobby () {
    const [message, updateMessage] = useState('')
    const [messages, updateMessages] = useState([])

 useEffect(() => {
        const handleNewMessage = newMessage =>
            updateMessages([...messages, newMessage])
        socket.on('chat.message', handleNewMessage)
        return () => socket.off('chat.message', handleNewMessage)
    }, [messages])

 const handleFormSubmit = event => {
        event.preventDefault()
        if (message.trim()) {
            socket.emit('chat.message', {
                userid: myId,
                lobby,
                username: username,
                message
            })
            updateMessage('')

const recibesound = document.getElementsByClassName("audio-element")[0]
        recibesound.play()

 }

}

const handleInputChange = event =>
updateMessage(event.target.value)

////teste
const handleTesteChange = event =>
updateMessage(event.target.value)

const handleTesteSubmit = event => {
    event.preventDefault()
    if (message.trim()) {
        socket.emit('chat.message', {
            userid: myId,
            message

 })
    updateMessage('')

}

}
///teste

  return(

     //html

)}

   export default Lobby;

goal:
class Lobby extends Component {

// same code

 render() {
   return(

 //html

 );
  }
}

A: From my understanding you are attempting to convert your hooks function component to a class component. You cannot use any of your hooks functions in a class component. You have to rewrite your class component using this.setState() instead of the useState hook (instead of updateMessage, and updateMessages) and this.state.message instead of 'message', and using the componentDidUpdate method instead of the useEffect hook. For your functions (handleInputChange), you can define them as method for your class. For your constant (recibesound), you can define it outside your class.
In short, you have to rewrite your component. I recommend viewing a React tutorial on class components.


text:
Q: Rails - model relations from custom column Having an example of 2 models as follow:
Model 1
column 1 --- column 2 --- column 3
id       --- fb_id    --- someOtherThing

Model 2
column 1 --- column 2 --- column 3
id       --- fb_id    --- someOtherThing

Where for example, fb_id is the Facebook ID as big int.
How can I construct a relation (for example belongs_to) from column 2 of the first model to column 2 of the second model?
For the moment I have do something like this:
model 1:
belongs_to :model2, :foreign_key => 'fb_id'

But how can I pre-select the column from model 1 (column 2) that must match the second model's column? (I think that in this manner it takes column 1 from model 1).
In synthesis:
How to create a relation (belongs_to or has_many) model1(:fb_id) => model2(:fb_id)
and not model1(:id) => model2(:fb_id)

A: If I understood correctly what you need is to retrieve a record with a valid association, right?
You can do that using the following:
Model1.joins(:model2 => :fb_id)

This will retrieve only the Model1' that have a valid association!

redpajama_set_name: RedPajamaStackExchange


text:
Q: mysql How to delete all data except some data I use mysql, nestjs, typeorm.
When I delete user table, I want to delete all but not some table data.
If a user withdraws from my service, I want to delete everything except the information in the cat table.
User [id, name, age ...]
Cat [id, name, age, userId ...]
Doctor [id, name, address, userId ...]
... [id, ...]
... [id, ...]

Is there a way to delete data in all tables except the data in cat table?
I am now running a delete query for each table.
DELETE FROM Doctor where userId = ${userId}
DELETE FROM ... where userId = ${userId}
DELETE FROM ... where userId = ${userId}

However, I write the question because problems can arise when tables are added or deleted.
Please tell me a good way.

A: I understand you need to make some value to be null in column 2 when you delete user as example you can use onDelete : "SET NULL"
in cat Entity you can use
  @ManyToOne(() => UserEntity, user => user,
        {
            onDelete: 'SET NULL'
        })
    @JoinColumn()
    public createdBy: UserEntity;


text:
Q: firebase auth persistence breaks Expo app. (No firebase app '[DEFAULT]') When trying to add persistence to firebase Auth my app breaks. Perhaps anyone here knows what to do? If I remove the persistence part of the initializeAuth everything seems to work OK but obviously it's needed to prevent the user from having to login everytime she starts the app. This happens in the iOS simulator.
my error:
 ERROR  FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
 ERROR  Invariant Violation: "main" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called.

My code:
import {
    FirebaseApp,
    FirebaseOptions,
    getApp,
    getApps,
    initializeApp,
} from 'firebase/app';

import {
    initializeAuth,
    getReactNativePersistence,
    Auth,
    getAuth,
} from 'firebase/auth/react-native';

import Constants from 'expo-constants';
import AsyncStorage from '@react-native-async-storage/async-storage';

const firebaseConfig: FirebaseOptions = {
    apiKey: Constants.manifest.extra.firebase.apiKey as string,
    authDomain: Constants.manifest.extra.firebase.authDomain as string,
    projectId: Constants.manifest.extra.firebase.projectId as string,
    storageBucket: Constants.manifest.extra.firebase.storageBucket as string,
    messagingSenderId: Constants.manifest.extra.firebase
        .messagingSenderId as string,
    appId: Constants.manifest.extra.firebase.appId as string,
    databaseURL: Constants.manifest.extra.firebase.databaseURL as string,
};

const app: FirebaseApp =
    getApps().length === 0 ? initializeApp(firebaseConfig) : getApp();

const auth: Auth =
    getApps().length === 0
        ? initializeAuth(app, {
                persistence: getReactNativePersistence(AsyncStorage),
          })
        : getAuth(app);

export {app, auth};


text:
Q: Can I import my Chrome bookmarks into Firefox? I just switched from Chrome to Firefox and I was wondering if I can get my bookmarks out of Chrome and into Firefox somehow. Is it possible to export to some standard format and import into Firefox?
Thanks

A: How to Export Bookmarks from Chrome and Import into Firefox
1. Export from Chrome
Firstly, open Chrome and press Ctrl+Shift+O to open the Bookmark Manager. Now click the dropdown arrow beside Organize, select Export bookmarks to HTML file..., and now save the file somewhere you can find and access for the Import into Firefox step.

2. Import into Firefox
Secondly, open Firefox and press Ctrl+Shift+B to open the Library window. Now click the dropdown arrow beside Import and Backup, select the Import Bookmarks from HTML..., and now select the HTML file you saved in the first step by double-clicking it or highlighting it and selecting Open.


text:
Q: How to open a WPF Application in a specific Place on a Specific Monitor I have two application which communicates together, to be more specific I have app1.exe and app2.exe this 2 apps are in the same PC which has one monitor and one TV how can I open app1.exe on TV and the other on my Monitor. Actually to do this I'm using a third party tool which is named Actual Multiple Monitors. my goal is to remove this tool because I'm using this only for the function to open my applications in the right place. it would be great if there is a possibility to do this using code. I'm using WPF in Visual Studio 2010?

A: In case Matthew Watson's answer doesn't work, your window may be in Maxmized state. In this case, set its state to WindowState.Normal, change top/left and revert the WindowState.

A: The following assumes that you have the source code to your applications:
You need to do a couple of things:
Firstly use System.Windows.Forms.Screen() to enumerate your screens.
Screen[] allScreens = Screen.AllScreens;
Then you can you use the Screen.Bounds property to determine where to display your main window.
I don't know how you change the location of your main window in WPF - in Windows Forms you just override OnLoad() and set the Form.Location and Form.Size appropriately. I imagine WPF has something similar.


text:
Q: errorMessage: "event is not defined" in lambda function nodejs I am trying to run a lambda function attached to an API gateway GET request and below is the code
const AWS = require('aws-sdk');
const s3 = new AWS.S3();

const bucketName = "dhaval-upload";

let params = {
        Bucket: bucketName,
        Key: event.fileName
};

exports.handler = async (event, context, callback) => {
    return await s3.getObject(params).promise()
    .then((res) => {
        return "abcd";
        // return res.Body.toString('utf-8');
    })
    .catch((err) => {
        return err;
    });
};

but I am getting the below error
errorMessage: "event is not defined"
errorType: "ReferenceError"

But I don't understand the reason for this as I have another POST request running perfectly..
Any help will be highly appreciated

A: You need to place params inside your handler, like this:
exports.handler = async (event, context, callback) => {

    let params = {
        Bucket: bucketName,
        Key: event.fileName
    };

    return await s3.getObject(params).promise()
    .then((res) => {
        return "abcd";
        // return res.Body.toString('utf-8');
    })
    .catch((err) => {
        return err;
    });
};


text:
Q: Трудности при работе с атрибутом hidden Хочу написать скрипт, которые при клике на заголовке скрывает div, когда тот виден, и, наоборот, когда div скрыт, то, чтобы отображался снова. То, что я предлагаю не работает, в чем проблема? И еще, почему когда я атрибуту hidden в html ставлю значение false, то получаю обратное действие на отображаемой странице (элемент пропадает, а не наоборот отображается, как было бы логически предположить)?

function clcHead() {
  if (document.getElementById('txt-area').hidden == false) {
    document.getElementById('txt-area').hidden = true;
  }
  if (document.getElementById('txt-area').hidden == true) {
    document.getElementById('txt-area').hidden = false;
  }
}

Click on header

A: Может вы имеете ввиду display:none? Для чего вы используете атрибут hidden?

const header = document.querySelector("#header")

const handleClick = () => {
  const txtArea = document.querySelector("#txt-area")
  txtArea.hidden = !txtArea.hidden
}

header.addEventListener('click', handleClick)
#txt-area {
  width: 50px;
  height: 50px;
  background-color: red;
}

Click on header

#


text:
Q: Calculate days between two dates once checkbox is checked I am using below code which will count total days if cb1 is checked.
If cb1 is unchecked (default state) weekends will be excluded.
My 1st problem is that it is showing one day less in calculation once cb1 is checked and 2nd problem is that when cb1 is unchecked it is not showing any result.
Any help, please. I took reference from this thread.
(function () {
     if (getField("cb1").value != "Off") {
         var Start = this.getField("LeaveFrom").value;
         var End = this.getField("LeaveEnd").value;
         var dStart = util.scand("dd/mm/yyyy H:MM:SS", Start + " 0:00:00");
         var dEnd = util.scand("dd/mm/yyyy H:MM:SS", End + " 0:00:00");
         var diff = dEnd.getTime() - dStart.getTime();
         var oneDay = 24 * 60 * 60 * 1000;
         var days = Math.floor(diff/oneDay);
         event.value = days;
     } else {
         var start = this.getField("LeaveFrom").value; // get the start date value
         var end = this.getField("LeaveEnd").value; // get the end date value
         var start =util.scand("dd/mm/yyyy H:MM:SS", start + " 0:00:00");
         var end = util.scand("dd/mm/yyyy H:MM:SS", end + " 0:00:00");

         event.value = dateDifference(start, end);

         function dateDifference(start, end) {
             if (end < start) return -1;
             // Copy date objects so don't modify originals
             var s = new Date(+start);
             var e = new Date(+end);

             // Get the difference in whole days
             var totalDays = Math.round((e - s) / 8.64e7);
             // Get the difference in whole weeks
             var wholeWeeks = totalDays / 7 | 0;
             // Estimate business days as number of whole weeks * 5
             var days = wholeWeeks * 5;
             // If not even number of weeks, calc remaining weekend days
             if (totalDays % 7) {
                 s.setDate(s.getDate() + wholeWeeks * 7);
                 while (s < e) {
                     s.setDate(s.getDate() + 1);
                     // If day isn't a Friday or Saturday, add to business days
                     if (s.getDay() != 5 && s.getDay() != 6) {
                         ++days;
                     }
                 }
             }
             return days;
         }
     }
})();


text:
Q: Chrome mobile tab grid layout issue Chrome suddenly changed tab grid layout from "cards" with preview to the simple list of tabs. I checked Chrome://flags, specifically tab-grid-layout. But every setting-switch seems like no effect.
I need a 101% workable method, how to force Chrome work normally.


text:
Q: How do I config Netgear FVL328 as a simple VPN server? I just got a Netgear FVL328 and wanted to be able to connect to my home network using this VPN router when I'm at starbucks/the airport/etc.
I've set up very simple networks before but I have very little knowledge with VPN. I've studied it a little over the internet and found protocol names like IPSec and PPTP but obviously that isn't enough to be able to set up this router.
I downloaded the router's manual from netgear's website and still don't know what to set up to achieve these very simple things
- set up the router to accept a user named user and password password to connect to my home network.
- set up a client to connect to this router without using netgear's VPN client.
You can assume I have a static IP from my ISP and minimal security is needed.
Let me know if I'm unclear.
Thank you very much.
EDIT: Also I just found out that there's a notion of VPN client hardware too. If this router is one of those, then I guess I'm out of luck.

A: I doubt they're using any proprietary protocols. The Windows built-in client is pretty flexible and should be able to negotiate the connection. Follow this KB here, but then configure your Windows client manually
http://kb.netgear.com/app/answers/detail/a_id/1010/~/how-to-connect-vpn-client-software-to-fvl328-or-fvs328


text:
Q: Where to store code that doesn't belong to a model or controller? I have a couple of utility methods that don't belong to a class or model yet.
Where is a good place to keeps this code? And how do I call it from with a model?
def get_api
 Clickatell::API.authenticate(ENV['AP_ID'], ENV['PASSWORD'])
end

def send_sms(from, message)
 begin
  api = get_api
  api.send_message(from, message)
 rescue Exception => exc
  logger.error(message + " " + "Message for the log file #{exc.message}")
  render :text => "#{exc.message}", :status => 200
 end
end

A: Put it in a class, put this class in the /lib folder. You can then either add it to the autoload path like this:
config.autoload_paths += %W(#{config.root}/lib)

or simply require it where needed.
One alternate approach could also be to write a model if the functionality you wrap is very model like (is part of the business logic). A model does not necessarily have to be related to a database table. (Though I would then use a subfolder below /models for such functionality)
This for simple small things you add on the run. If you have larger things to add, then maybe a plugin or engine would be an option.

A: You could implement the module under "lib" directory or under lib's sub-directory.
In application.rb,if you modify autoload_paths to:
 config.autoload_paths += Dir["#{config.root}/lib/**/"]

It will be automatically loaded.
If you don't want to change the config, you can require the the file at the beginning of your model file.
require "relative_path_under_lib"


text:
Q: How to remap Super/Windows(left) key to control key in linux Could anyone please tell me how to remap my Super(left) key to Ctrl key in Ubuntu Linux?
I mean Super(left) should work as control key..

A: Save the following (untested) code to a file and use it as an argument for the xmodmap command:
clear Control
clear Mod4
keysym Super_L = Control_L
add    Control = Control_L Control_R
add    Mod4    = Super_L Super_R

A: I assume you are using GNOME 3.
in terminal write
$ gnome-control-center

click on "keyboard" then click on "layout settings" then "options..." then "Alt/Win key behavior" then choose "control is mapped to Win keys( and the usual CTRL keys)
UPDATE: if you want to disable the original CTRL key then from "options.." choose "compose key position" and check both left/right CTRL.


text:
Q: Splitting and Appending by Name across two columns in pandas Hello I have a csv file of sports results for the english premier league that I am wanting to manipulate a single team that is located either in a home or away column. I then want to be able to create a series of columns which are sorted by that team and then return the results as per below. I have been able to do this in a loop but would love to know the pandas method. I have attempted to group by team- arsenal, but am finding it difficult to do that with two column options, where i would need to flip subsets of the opposing team.
df = pd.read_csv(
    'http://www.football-data.co.uk/mmz4281/1516/E0.csv',
    sep=',')

result= df[(df['HomeTeam'] == "Arsenal") | (df.AwayTeam == "Arsenal")]

for index, row in result.iterrows():
    if row['HomeTeam'] == "Arsenal":
        if row['FTR'] == "H":
            print ('Win' , 'Home', row['FTHG'], '-', row['FTAG'])
        elif  row['FTR'] == "D":
            print ('Draw' , 'Home', row['FTHG'], '-', row['FTAG'])
        else:
            print ('Lose' , 'Home', row['FTHG'], '-', row['FTAG'])

# we dont need to put the conditons for else because we know if arsenal are not the home team they must be the away team,
# this is because we already set out dataframe filter above to show only games where arsenal is home or away, if we didnt
# do this we would do an elif and then do an improper result print for else
    else:
        if row['FTR'] == "H":
            print ('Win' , 'Home', row['FTHG'], '-', row['FTAG'])
        elif  row['FTR'] == "D":
            print ('Draw' , 'Home', row['FTHG'], '-', row['FTAG'])
        else:
            print ('Lose' , 'Home', row['FTHG'], '-', row['FTAG'])

A: You can use double numpy.where:
df = pd.read_csv('http://www.football-data.co.uk/mmz4281/1516/E0.csv')
#print (df)

#add copy - http://stackoverflow.com/a/42439031/2901002
result= df[(df['HomeTeam'] == "Arsenal") | (df.AwayTeam == "Arsenal")].copy()

#get output to Series, necessary convert numeric to string
splitted = ' ' + result['FTHG'].astype(str) + ' - ' + result['FTAG'].astype(str)
#boolean masks
mask = (result['HomeTeam'] == "Arsenal")
mask1 = (result['FTR'] == "H")
mask2 = (result['FTR'] == "D")

#for new column as output
result['out'] = np.where(mask & mask1, 'Win home' + splitted,
                np.where(mask & mask2, 'Draw home' + splitted, 'Lose home' + splitted))

print (result[['HomeTeam', 'AwayTeam', 'out']])
           HomeTeam        AwayTeam              out
6           Arsenal        West Ham  Lose home 0 - 2
17   Crystal Palace         Arsenal  Lose home 1 - 2
29          Arsenal       Liverpool  Draw home 0 - 0
35        Newcastle         Arsenal  Lose home 0 - 1
40          Arsenal           Stoke   Win home 2 - 0
52          Chelsea         Arsenal  Lose home 2 - 0
60        Leicester         Arsenal  Lose home 2 - 5
77          Arsenal      Man United   Win home 3 - 0
86          Watford         Arsenal  Lose home 0 - 3
90          Arsenal         Everton   Win home 2 - 1
104         Swansea         Arsenal  Lose home 0 - 3
117         Arsenal       Tottenham  Draw home 1 - 1
127       West Brom         Arsenal  Lose home 2 - 1
137         Norwich         Arsenal  Lose home 1 - 1
140         Arsenal      Sunderland   Win home 3 - 1
156     Aston Villa         Arsenal  Lose home 0 - 2
169         Arsenal        Man City   Win home 2 - 1
176     Southampton         Arsenal  Lose home 4 - 0
180         Arsenal     Bournemouth   Win home 2 - 0
190         Arsenal       Newcastle   Win home 1 - 0
204       Liverpool         Arsenal  Lose home 3 - 3
218           Stoke         Arsenal  Lose home 0 - 0
228         Arsenal         Chelsea  Lose home 0 - 1
230         Arsenal     Southampton  Draw home 0 - 0
248     Bournemouth         Arsenal  Lose home 0 - 2
257         Arsenal       Leicester   Win home 2 - 1
267      Man United         Arsenal  Lose home 3 - 2
273         Arsenal         Swansea  Lose home 1 - 2
284       Tottenham         Arsenal  Lose home 2 - 2
295         Everton         Arsenal  Lose home 0 - 2
303         Arsenal         Watford   Win home 4 - 0
319        West Ham         Arsenal  Lose home 3 - 3
330         Arsenal  Crystal Palace  Draw home 1 - 1
338         Arsenal       West Brom   Win home 2 - 0
344      Sunderland         Arsenal  Lose home 0 - 0
346         Arsenal         Norwich   Win home 1 - 0
364        Man City         Arsenal  Lose home 2 - 2
370         Arsenal     Aston Villa   Win home 4 - 0

For Series as output:
out = pd.Series(np.where(mask & mask1, 'Win home' + splitted,
                np.where(mask & mask2, 'Draw home' + splitted, 'Lose home' + splitted)),
                index=result.index)

print (out)
6      Lose home 0 - 2
17     Lose home 1 - 2
29     Draw home 0 - 0
35     Lose home 0 - 1
40      Win home 2 - 0
52     Lose home 2 - 0
60     Lose home 2 - 5
77      Win home 3 - 0
86     Lose home 0 - 3
90      Win home 2 - 1
104    Lose home 0 - 3
117    Draw home 1 - 1
127    Lose home 2 - 1
137    Lose home 1 - 1
140     Win home 3 - 1
156    Lose home 0 - 2
169     Win home 2 - 1
176    Lose home 4 - 0
180     Win home 2 - 0
190     Win home 1 - 0
204    Lose home 3 - 3
218    Lose home 0 - 0
228    Lose home 0 - 1
230    Draw home 0 - 0
248    Lose home 0 - 2
257     Win home 2 - 1
267    Lose home 3 - 2
273    Lose home 1 - 2
284    Lose home 2 - 2
295    Lose home 0 - 2
303     Win home 4 - 0
319    Lose home 3 - 3
330    Draw home 1 - 1
338     Win home 2 - 0
344    Lose home 0 - 0
346     Win home 1 - 0
364    Lose home 2 - 2
370     Win home 4 - 0
dtype: object


text:
Q: How to execute a command when the user opens the DatePicker calendar in WPF? I'm using a DatePicker in a WPF window and I need to execute a command to refresh the MVVM data when the user tries to open the calendar window. The DatePicker does not have a Command property.
Is there a way to accomplish this?
Thanks.

A: You could create an attached behavior for that or use an available framework like this to link events with commands. From that you can expose and bind your command in your viewmodel and place your update logic there.
Also this question really belongs to these kind of questions.

A: OK, if you really want to attach a command to an event you can use a pattern like this: http://petebarber.blogspot.com/2011/06/getting-wpf-sizechanged-events-at-start.html
Basically you define (in a separate file) an attached property which hooks up to an event. So in your case this would be the CalendarOpened event of the DatePicker. So the attached property would be called CalendarOpenedCommand and you would then use the property on your actual DatePicker like this:
<DatePicker mvvm:CalendarOpenedCommand="{Binding MyCalendarOpenedCommand}" ...

However, I personally think this is overkill if this is the only place you will use this feature. It might upset some MVVM purists, but in this case I would just put a one line event handler for CalendarOpened in the code behind, which could then call a method (or even a command if you prefer) on the view model to notify it of the calendar opening. It could then do its business and update the bound properties for DisplayDateStart and DisplayDateEnd (as I suggested in the comments above) accordingly.


text:
Q: Weird behavior of CAST with 0 in rails Sorry for long query but its what im working with.
I got this query in rails
@posts = Cama::PostType.first.posts.joins(:custom_field_values).where("(status = ?) AND (cama_custom_fields_relationships.custom_field_slug = ? AND
CAST(cama_custom_fields_relationships.value AS INTEGER) >= ? AND
CAST(cama_custom_fields_relationships.value AS INTEGER) <= ? ) OR
(cama_custom_fields_relationships.custom_field_slug = ? AND
CAST(cama_custom_fields_relationships.value AS INTEGER) >= ? AND
CAST(cama_custom_fields_relationships.value AS INTEGER) <= ? ) AND
(LOWER(title) LIKE ? OR LOWER(content_filtered) LIKE ?)","published", "filtry-
powierzchnia", params['size-start'].to_i, params['size-end'].to_i,"filtry-
cena", params['price-start'].to_i, params['price-end'].to_i
,"%#{params[:q]}%",
"%#{params[:q]}%").group("cama_posts.id").having("COUNT(cama_custom_fields_rel
ationships.objectid) >= 2")

that make this sql
CamaleonCms::Post Load (0.9ms)  SELECT  "cama_posts".* FROM "cama_posts"
 INNER JOIN "cama_custom_fields_relationships" ON
"cama_custom_fields_relationships"."objectid" = "cama_posts"."id" AND
"cama_custom_fields_relationships"."object_class" = $1 WHERE
"cama_posts"."post_class" = $2 AND "cama_posts"."taxonomy_id" = $3 AND
((status = 'published') AND
(cama_custom_fields_relationships.custom_field_slug = 'filtry-powierzchnia'
AND CAST(cama_custom_fields_relationships.value AS INTEGER) >= 1 AND
CAST(cama_custom_fields_relationships.value AS INTEGER) <= 10000 ) OR
(cama_custom_fields_relationships.custom_field_slug = 'filtry-cena' AND
CAST(cama_custom_fields_relationships.value AS INTEGER) >= 0 AND
CAST(cama_custom_fields_relationships.value AS INTEGER) <= 10000000 ) AND
(LOWER(title) LIKE '%%' OR LOWER(content_filtered) LIKE '%%')) GROUP BY
cama_posts.id HAVING (COUNT(cama_custom_fields_relationships.objectid) >= 2)
 ORDER BY "cama_posts"."post_order" ASC, "cama_posts"."created_at" DESC LIMIT
 $4 OFFSET $5  [["object_class", "Post"], ["post_class", "Post"],
["taxonomy_id", 2], ["LIMIT", 6], ["OFFSET", 0]]

As you can see Im using CAST, I can't change column just to integer, because its CMS. I created custom_field that suppoust to be integer but table in db is still text so im forced to do it that way.
Now everything is ok if my
..CAST(cama_custom_fields_relationships.value AS INTEGER) >= 1..

but when this value will be 0
so when my query will look like
CamaleonCms::Post Load (0.9ms)  SELECT  "cama_posts".* FROM "cama_posts"
     INNER JOIN "cama_custom_fields_relationships" ON
    "cama_custom_fields_relationships"."objectid" = "cama_posts"."id" AND
    "cama_custom_fields_relationships"."object_class" = $1 WHERE
    "cama_posts"."post_class" = $2 AND "cama_posts"."taxonomy_id" = $3 AND
    ((status = 'published') AND
    (cama_custom_fields_relationships.custom_field_slug = 'filtry-powierzchnia'
    AND ****CAST(cama_custom_fields_relationships.value AS INTEGER) >= 0**** AND
    CAST(cama_custom_fields_relationships.value AS INTEGER) <= 10000 ) OR
    (cama_custom_fields_relationships.custom_field_slug = 'filtry-cena' AND
    CAST(cama_custom_fields_relationships.value AS INTEGER) >= 0 AND
    CAST(cama_custom_fields_relationships.value AS INTEGER) <= 10000000 ) AND
    (LOWER(title) LIKE '%%' OR LOWER(content_filtered) LIKE '%%')) GROUP BY
    cama_posts.id HAVING (COUNT(cama_custom_fields_relationships.objectid) >= 2)
     ORDER BY "cama_posts"."post_order" ASC, "cama_posts"."created_at" DESC LIMIT
     $4 OFFSET $5  [["object_class", "Post"], ["post_class", "Post"],
    ["taxonomy_id", 2], ["LIMIT", 6], ["OFFSET", 0]]

Im getting error:
ActionView::Template::Error (PG::InvalidTextRepresentation: ERROR:  invalid input syntax for integer: "/media/1/asd.jpg"
: SELECT  "cama_posts".* FROM "cama_posts" INNER JOIN "cama_custom_fields_relationships" ON "cama_custom_fields_relationships"."objectid" = "cama_posts"."id" AND "cama_custom_fields_relationships"."object_class" = $1 WHERE "cama_posts"."post_class" = $2 AND "cama_posts"."taxonomy_id" = $3 AND ((status = 'published') AND (cama_custom_fields_relationships.custom_field_slug = 'filtry-powierzchnia' AND CAST(cama_custom_fields_relationships.value AS INTEGER) >= 0 AND CAST(cama_custom_fields_relationships.value AS INTEGER) <= 10000 ) OR (cama_custom_fields_relationships.custom_field_slug = 'filtry-cena' AND CAST(cama_custom_fields_relationships.value AS INTEGER) >= 0 AND CAST(cama_custom_fields_relationships.value AS INTEGER) <= 10000000 ) AND (LOWER(title) LIKE '%%' OR LOWER(content_filtered) LIKE '%%')) GROUP BY cama_posts.id HAVING (COUNT(cama_custom_fields_relationships.objectid) >= 2) ORDER BY "cama_posts"."post_order" ASC, "cama_posts"."created_at" DESC LIMIT $4 OFFSET $5):

and @posts return it on the query lvl so its not error that occurs somewhere else.
I tried CASTing to numeric, same problem.  It only happens when its starting condition, when there is another condition before it, it accepts 0 like in my example, the second condition after this one works with >= 0


text:
Q: Java Stream Updating running total I have following java lines of code, i am wondering if it can be totally converted to Java 8 Stream fashion?
long totalSum = list.parallelStream().mapToLong(ExpenseInfo::getCurrCount).sum();

// LOOP ALL COLLECTION
for (ExpenseInfo info : list) {
    totalSum -= info.getCurrCount();
    info.setBurnCount(totalSum);
}

A: The thing is that your task is sequential by default. For example, the first element will have its burn count set to the total sum minus its own count while the second element will have its burn count set to the total sum minus its own count and the count of the previous elements and so on.
That is, if you would have to turn this sequence of instructions using a stream and that the stream would be parallel (using .stream() or .parallelStream() should have no consequence on the result you compute), the totalSum variable would be shared and every element in the ordered stream would have to wait the updated value of the total sum computed by every previous element, which would defeat entirely the purpose of using parallelism.
That said, you can use another approach that would first map each instance to its own curr count and then use Arrays.parallelPrefix to compute the cumulated sum into an array.
Finally, you can use an IntStream to set the burr count of each element by subtracting the total sum and the cumulated sum for that element.
long[] sums = list.stream().mapToLong(ExpenseInfo::getCurrCount).toArray();
Arrays.parallelPrefix(sums, Long::sum);
IntStream.range(0, sums.length).forEach(i -> list.get(i).setBurnCount(sums[sums.length - 1] - sums[i]));

Of course, it supposes that the list is random access so that get(int i) is not an expensive operation, but everything can be parallelized without problems (in fact parallelPrefix is already parallelized, as its name suggests).
I would still keep your approach in first place, it seems clearer to me.


text:
Q: Twitter oauth_token and oauth_token_secret only? Is it possible to use twitter API having just oauth_token and oauth_token_secret on client?
I'm getting these tokens via a standard oauth flow on server-side part of my app, but I wonder if I can send requests from the client using just oauth_token and oauth_token_secret, keeping oauth_consumer_key and oauth_consumer_secret secure on the server.
The idea is that once I've got the tokens, I've confimed my identity and should be allowed to use just them(for some time, at least, refreshing them eventually).


text:
Q: How can I set dialog style in my custom theme? I tried in many ways but I can't change the AlertDialog style from xml.
The result I would is to define an XML style for dialogs extending and overriding the default and then bind it in my theme, so all the alertDialogs will looks the same.
I tried:
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    <item name="android:alertDialogStyle">@style/pippo</item>
</style>
<style name="pippo" parent="@android:style/Theme.Dialog">
    <item name="android:bottomBright">@android:color/holo_orange_dark</item>
    <item name="android:bottomDark">@android:color/holo_orange_dark</item>
    <item name="android:bottomMedium">@android:color/holo_orange_dark</item>
    <item name="android:centerBright">@android:color/holo_orange_dark</item>
    <item name="android:centerDark">@android:color/holo_orange_dark</item>
    <item name="android:centerMedium">@android:color/holo_orange_dark</item>
    <item name="android:fullBright">@android:color/holo_orange_dark</item>
    <item name="android:fullDark">@android:color/holo_orange_dark</item>
    <item name="android:topBright">@android:color/holo_blue_dark</item>
    <item name="android:topDark">@android:color/holo_blue_dark</item>
</style>

and then I put in the manifest "AppTheme" as activity theme, but I still see normal alertdialogs.
Where I do wrong?

A: You can try something like this to apply the desired style:
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style. pippo));


text:
Q: Cannot get my Brother printer to work after reinstalling Ubuntu Studio I've been running Ubuntu Studio for a while and my printer was working when I followed instructions from Brother (HL-L2320D) before formatting.
Short story, formatted my computer after trying to install Windows 10 on a separate HDD; my printer is working under Windows 10 but I cannot get it back to working under Ubuntu Studio. I've tried many times, and the installation looks to be going fine, but I get no joy when I try to print. When I check the printer it says:

inactive sending data to printer

Any idea? thank you.

A: Ok, I solved my self-induced problem; I replaced the toner and the printer works now. I had the toner light on and for some reason the machine was working ok under Windows but not Ubuntu. Go figure!!

A: Bonjour Stephane; if you go here http://support.brother.com/g/b/downloadend.aspx?c=us&lang=en&prod=hll2320d_us_as&os=128&dlid=dlf006893_000&flang=4&type3=625 and click to download and SAVE what will be linux-brprinter-installer-2.2.0-1.gz
then open a terminal; copy each line below; paste into the terminal; hit the ENTER key after each paste
cd Downloads

gunzip linux-brprinter-installer-2.2.0-1.gz

sudo bash linux-brprinter-installer-2.2.0-1 HL-2320D

that last command unleashes the install script; watch the terminal as it runs; it may ask you questions; if it says "Do you want to specify Device URI?" for a usb connection, say NO


text:
Q: Content disappears from jQuery autocomplete when focus on field is lost my autocomplete works fine, but problem appears when I want to skip to another field in my form. When autocomplete lose focus its value disappears (also value of span that I render after this autocomplete disappears).
function initCaAutocomplete() {
    $(".caSelector").autocomplete({
        source: "/core/index/search-ca/ajax/1",
        minLength: 2,
        select: function (event, ui) {
            var descId = 'desc_' +  $(this).attr('id');
            if ($('span#' + descId).length) {
                $('span#' + descId).html(ui.item.desc);
                $('span#' + descId).attr('title', ui.item.fullDesc);
            } else {
                $(this).after(''
                    + ui.item.fullDesc + '');
            }

            ui.item.value = ui.item.code;

            $('.tooltip', $(this).parent()).hide();
        },
        change: function (event, ui) {
            var descId = 'desc_' +  $(this).attr('id');
            var inputId = $(this).attr('id');
            var source = $(this).val();
            $.ajax({
                type   : 'POST',
                url    : '/core/index/search-ca/ajax/1',
                dataType: "text",
                async  : true,
                data   : {
                    term: source
                },
                success: function (response) {
                    var codes = $.parseJSON(response);
                    if (codes.length == 0) {
                        $('#' + inputId).val('');
                        $('span#' + descId).html('');
                    }
                },
                error: function (response) {
                    $('#' + inputId).val('');
                    $('span#' + descId).html('');
                }
            });
        },
        position: { my : "left top", at: "left bottom" }
    });
}


text:
Q: jQuery :checked getting value of last element For some reason even if i set the checked attribute to the radio button my jQuery code always defaults to the last button in the list why is that?
HTML
<input class=t type=radio name=drop value=1 checked>one
<input class=t type=radio name=drop value=2>two

jQuery
var dropResult;
$(function (){
    $(".t").click(function(){
        dropResult = $("input[name=drop]:checked").val();
    });
});

A: Alright so it seems i was losing my mind i didn't give dropresult a defualt value. The checked attribute is purely aesthetic until the radio button is changed and the new value is updated to the variable. It's very strange you would think since there is no value that any code checking it for a value to use would break
Fixed with
var dropResult = 1;

A: This is because you are using radio buttons with the same name. Radio buttons with the same name can only have one checked at a time.
It seems when multiple radio buttons with the same name are checked, the actual one checked defaults to the last one
So when you use :checked, it will only apply to the one that is actually selected(in this case the last one)

console.log($(':checked').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input class=t type=radio name=drop value=1 checked>one
<input class=t type=radio name=drop value=2 checked>two
<input class=t type=radio name=drop value=3 checked>three

A: It's working fine try this

var dropResult;
$(function (){
    $(".t").click(function(){
        dropResult = $("input[name=drop]:checked").val();
      alert(dropResult);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class=t type=radio name=drop value=1 checked>one
<input class=t type=radio name=drop value=2>two


text:
Q: ModelMultipleChoiceField passing request.user I want to use forms.ModelMultipleChoiceField in a form. I know it takes a queryset, however the query set I will be using take the param user which I normally pass in a view using request.user. However this is in a form, how do I pass request.user? do I need to?
Entry.objects.filter(request.user)

A: You should override your form's init method:
class MyForm(forms.ModelForm):

    class Meta:
        model = Entry

    def __init__(self, user=None, *args, **kwargs):
        super(MyForm, self).__init__(*args,**kwargs)
        if user is not None:
            form_choices = Entry.objects.filter(user)
        else:
            form_choices = Entry.objects.all()

        self.fields['my_mfield'] = forms.ModelMultipleChoiceField(
                                       queryset=form_choices
                                   )

and in your views, when it's time to instantiate the form:
form = MyForm(request.user)

or
form = MyForm()


text:
Q: How can I stop System.Uri from converting UNC paths to File:/// paths? I am trying to set a WPF image control's source to a UNC path image.
My current code goes similar to the following
Button.Content = new Image
{
    Source = new BitmapImage(new Uri(UncPathAsString)),
    VerticalAlignment = VerticalAlignment.Center
};

However, instead of loading the UNC path of the format:
\\Machine\Folder\Subfolder\Image.jpg

Uri returns the path of:
File:///Machine/Folder/Subfolder/Image.jpg

I have tried creating a bitmap for the UNC path and then converting the Bitmap to a BitmapImage but the performance was too slow for the application. I.E. There are up to several hundred of these buttons being created, and converting the bitmap made load times horrible.


text:
Q: How to render random objects from a table in React Native? I want to render random objects from table in React Native.
I use React Native EasyGrid for my table.
I try to build a memory game in React Native.
I need this code for shuffle cards.
This is the code that I make for test all functions.
They want me to give more informations, but I don't have more.
The code:

import React from 'react'
import { StyleSheet, View, TextInput, Button, Text, TouchableOpacity, FlatList, ActivityIndicator,} from 'react-native'
import { Col, Row, Grid } from "react-native-easy-grid";

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
  color: "red",
  card: "this.refs.card",
  cards: "[...card]"
  }
  }

_code to randomized (Like shuffle(array) in JS, but not this function !) {

// I need the code here

}

componentDidMount() {

  this.setState({cards: this._shuffle(this.state.cards)});

}

  _test = () => {

 this.setState({color: this.state.color === "red" ? "blue" : "red"});

 }

  render() {
    return (
      <View style={styles.container}>

 <Grid ref="deck">
  <Col>
   <Row>

   <TouchableOpacity ref="card" onPress={this._test}>
    <Text style={{ height: 15 }}>1</Text>
   </TouchableOpacity>

   </Row>
   <Row>

   <TouchableOpacity ref="card" onPress={this._test}>
    <Text style={{ height: 15 }}>2</Text>
   </TouchableOpacity>

   </Row>
   <Row>

   <TouchableOpacity ref="card" onPress={this._test}>
    <Text style={{ height: 15 }}>3</Text>
   </TouchableOpacity>

   </Row>
   <Row>

   <TouchableOpacity ref="card" onPress={this._test}>
    <Text style={{ height: 15 }}>4</Text>
   </TouchableOpacity>

   </Row>
  </Col>
 </Grid>

   <View><Text style={{color: this.state.color}}>XXX</Text></View>

</View>

    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Can somebody help me please ?


text:
Q: strange behavior in imageManipulation for cropVariants As a source file I have a square image (500x500).
As soon as I use the cropArea, the preview shows that the entire area has been selected (500x500px)
'cropVariants' => [
        'default' => [
            'title' => 'LLL:EXT:core/Resources/Private/Language/locallang_wizards.xlf:imwizard.crop_variant.default',
            'allowedAspectRatios' => [
                '1:1' => [
                    'title' => 'LLL:EXT:core/Resources/Private/Language/locallang_wizards.xlf:imwizard.ratio.1_1',
                    'value' => 1.0
                ]
            ],
            'selectedRatio' => '1:1',
            'cropArea' => [
                'x' => 0.0,
                'y' => 0.0,
                'width' => 1.0,
                'height' => 1.0,
            ],
        ],
    ],

But in the database, however, the following data (sys_file_reference) is stored: (problem y-coordinate)
{"default":{"cropArea":{"height":1,"width":1,"x":0,"y":-0.002},"selectedRatio":"1:1","focusArea":null}}
In Fluid this is my code:
<f:image src="{item.image.0.reference.uid}" alt="{item.image.0.reference.description}" treatIdAsReference="1" />

As a result that image is rendered in fluid with 500 x 499 pixels. (1px is missing)

Any idea how I can adjust the behavior? so that the y-coordinate is also set to 0 and the whole selection is rendered?


text:
Q: Split Address field I have a address column that contains street address along with the PO Box no.I would like to extract street address and postcode into a separate column, how can I do that?
Sample Data
     1 ABC CDE PO BOX 650
       15 N. MAIN STREET P.O. BOX 009
       (ABC)PO BOX 5909
        1 TAKEWAY PLAZA
       PO BOX 146012  Parkway STREET

DESIRED OUTPUT:-

STREET ADDRESS               ADDRESS2

  1 ABC CDE                    P.O. BOX 650
  15 N. MAIN STREET            P.O. BOX 009
  ABC                          P.O. BOX 5909
  1 TAKEWAY PLAZA
  Parkway STREET               P.O. BOX 146012

A: Parsing addresses can be a slippery slope.  That said, you seem to be keying off of PO Box, so that makes it a little more managable,
That said, you may want to consider using the GOOGLE API to normaize your address Address standardization within a database
This will produce the desired results by normalizing and cleaning the string.  Then it is a simple matter of parsing the string, and then reconstructing it via XML and Stuff().
There are many parse/split functions available, I did provide mine below
Example
Declare @YourTable table (address varchar(250))
Insert Into @YourTable values
('1 ABC CDE PO BOX 650'),
('15 N. MAIN STREET P.O. BOX 009'),
('(ABC)PO BOX 5909'),
('1 TAKEWAY PLAZA'),
('PO BOX 146012  Parkway STREET')

Select A.*
      ,C.*
 From  @YourTable A
 Cross Apply (
               Select CleanString = replace(replace(replace(replace(replace(replace(replace(A.Address,'  ',' '),'P. O','P.O'),'P.','P'),'O. ','O'),'O BOX','OBOX'),'BOX ','BOX'),'POBOX',' POBOX')+' '
             ) B
 Outer Apply (
                Select Address1 = Stuff((Select ' ' +RetVal
                                         From  [dbo].[udf-Str-Parse](B.CleanString,' ')
                                         Where RetVal Not Like 'POBOX%'
                                         For XML Path ('')),1,1,'')
                      ,Address2 = (Select replace(RetVal,'POBOX','P.O. Box ') From  [dbo].[udf-Str-Parse](B.CleanString,' ') Where RetVal Like 'POBOX%')
             ) C

Returns
address                         Address1            Address2
1 ABC CDE PO BOX 650            1 ABC CDE           P.O. Box 650
15 N. MAIN STREET P.O. BOX 009  15 N. MAIN STREET   P.O. Box 009
(ABC)PO BOX 5909                (ABC)               P.O. Box 5909
1 TAKEWAY PLAZA                 1 TAKEWAY PLAZA     NULL
PO BOX 146012  Parkway STREET   Parkway STREET      P.O. Box 146012

The UDF if Interested
CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From  (Select x = Cast('<x>' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
    Cross Apply x.nodes('x') AS B(i)
);
--Thanks Shnugo for making this XML safe
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
--Select * from [dbo].[udf-Str-Parse]('this,is,<test>,for,< & >',',')


text:
Q: RestFULL Api with many Models (Android) I Have problem with understanding some questions about Rest API's.
I made 2 apps using JSON and POJO. In this case I had one BIG JSON file and it was enough to use Retrofit and go ahead with app.
Today I found another challenge. I want To use Api From HitBTC :
https://api.hitbtc.com/api/2/explore/
I don't know which repositories I need to use to display basic currency information in the application. Could You help me to understand this library?
thanks for any tips ;)

A: First of all, you'd write a module behaving as a WS Client of that HitBTC API. To do so, I'd follow DTO design pattern.

A: These endpoints seems to return currency info: GET /public/currency and GET /public/currency/{currency}
so for a JSON listing all the currencies, try to query
https://api.hitbtc.com/api/2/public/currency

and for a specific currency
https://api.hitbtc.com/api/2/public/currency/{currency}

so for example for Ethereum
https://api.hitbtc.com/api/2/public/currency/ETH


text:
Q: database in phone gap for blackberry I am using javascript for creating database in phonegap for blackBerry os4.6
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
    db.transaction(populateDB, errorCB, successCB);
}

function populateDB(tx) {
     tx.executeSql('DROP TABLE IF EXISTS DEMO');
     tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
     tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
     tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}

function errorCB(tx, err) {
    alert("Error processing SQL: "+err);
}

function successCB() {
    alert("success!");
}
</script>

but am not getting it.Please tell me the solution how to do .
Thanks in Advance

A: use try-catch construction to intercept exceptions which may occur upon opening the database.
Check this link


text:
Q: DBSet<> not working on .net core? I want to ask for help on returning DBSet<> on .net core WEB API.
Here is my code on the ADO.NET Entity Model DBSet tbl_employee :
public virtual DbSet<tbl_employee> tbl_employee { get; set; }

I am having an error on this code (.Net Core) :
return db.tbl_employee.ToList();

This is the error :

But on my MVC 5 project :
return db.tbl_employee.ToList();

This does not return any error on DBSet on my MVC 5 Web API project. How could the MVC5 version does not return any error but returns on .NET Core?
I installed "EntityFramework" package on the MVC 5 project. But I cannot install "EntityFramework" on .Net Core project. Upon researching, I found out that "Microsoft.EntityFrameworkCore" is the EF for .net core.
I think it's about the nuget package but I can't figure out which version / package should I install.
I would highly appreciate suggestions / comments. Thank you in advance and have a great day!


text:
Q: add onPress to first component and call it on second component I'm a beginner in react-native I  want to make add ( + ) button on the header of the first component when user click on onPress it will create a new form and the form is the second component

A: In App.js SetUp Navigation like below:
import { createAppContainer, createStackNavigator } from "react-navigation";
import MainScreen from "./screens/MainScreen";
import SecondScreen from "./screens/SecondScreen";

const AppNavigator = createStackNavigator({
   MainScreen: {
  screen: MainScreen
},

SecondScreen: {
  screen: SecondScreen,
},
})

const App = createAppContainer(AppNavigator);

export default App;

In Main Screen
import React, { Component } from "react";
import {
  View,
  Button,
} from "react-native";

class MainScreen extends Component {

  handleOnPress = () => {
    this.props.navigation.navigate("SecondScreen");
  };

  render() {
    return (
      <View>
        <Button
  onPress={this.handleOnPress}
  title="Button"
  color="#841584"
/>
      </View>
    );
  }
}

export default MainScreen;

It will redirect you to second screen

A: You can set ref of Form component
<FormsComponent
          ref={ref => {
            this.formComponent = ref;
          }}
        />

You should pass function as prop for Header component
<HeaderComponent addNewForm={this.addNewForm} />

Parent component will call function of form component when click in header component using ref
addNewForm = () => {
    this.formComponent.addNewForm();
  };

App Preview

Complete Code
import React, { Component } from "react";
import { View, Text, FlatList } from "react-native";

class HeaderComponent extends Component {
  render() {
    return (
      <View style={{ height: 80, backgroundColor: "red", paddingTop: 24 }}>
        <Text style={{ padding: 20 }} onPress={this.props.addNewForm}>
          Call Function of Form Component
        </Text>
      </View>
    );
  }
}

class FormsComponent extends Component {
  addNewForm = () => {
    alert("add new form");
  };

  render() {
    return (
      <FlatList
        data={[{ key: "Form1" }, { key: "Form2" }]}
        renderItem={({ item }) => <Text>{item.key}</Text>}
        style={{ flex: 1 }}
      />
    );
  }
}

export default class App extends Component {
  addNewForm = () => {
    this.formComponent.addNewForm();
  };

  render() {
    return (
      <View style={{ flex: 1 }}>
        <HeaderComponent addNewForm={this.addNewForm} />
        <FormsComponent
          ref={ref => {
            this.formComponent = ref;
          }}
        />
      </View>
    );
  }
}


text:
Q: Single page application using AngularJS I am working at a SPA using Flask(with jinja) and AngularJS. Everything works fine, but when the application is in a given state and I try to refresh the page in browser, the server responds with 404 response: "error": "Not found". Is there a way to make this work in a proper way when trying to access a page of the SPA application through the URL?

A: This may depend on how your dev http server is setup:

*

*It should be set to always load the default page which is index.html such that the angular engine will load and run and only then it will serve the other routes (states) like localhost/state, otherwise the angular router would not be able to resolve the url since it is not loaded (letting the http server handle the request, serving a 404 Page Not Found)

*The http servers sometimes serve only one level deep url's like localhost/state, not localhost/state/param and you need to change some settings to make it work, but I think this is beyond the scope of your question :)

A: You can use a hasher in SPA. You need to parse hash string before initializing view model and based upon the value of hash set your current visible page and then bind the view mode.

A: You need to have a rule to always return your SPA index.html page for any routes that match your angular routes.  I'm not sure what your web server is, apache or nginx or whatever but you should be able to find instructions on how to match those requests back to index.html.

A: You must have enabled html5 mode to true in in your angular js app. Set that to false will solve your problem.


text:
Q: React and useState implementaion I'm new here to React. So the code here updates the value of height(whenever the screen size changes) after every refresh. Really confused as to why is it happenning since setHeight is not being used to update the value of height.
 import React, { useState } from "react";

 import "./styles.css";

 export default function App() {
 const [height, setHeight] = useState(window.innerHeight);

 return (

        {height}

    );
 }

A: A React component only rerender when a prop or its state got updated.
In your example, window.innerHeight is read at component initialization and placed in the state height. The only way to rerender your component is to have a listener on your variable (window.addEventListener) that will trigger an update by setting the state.
A working example following Rerender view on browser resize with React
 export default function App() {
   const [height, setHeight] = useState(window.innerHeight);

   useLayoutEffect(() => {
    function updateHeight() {
      setHeight(window.innerHeight);
    }
    window.addEventListener('resize', updateHeight);
    updateSize();
    return () => window.removeEventListener('resize', updateHeight);
   }, []);

   return (

        {height}

    );
}


text:
Q: Properties of sum Compact Sets Prove that if A and B are two compact subsets of R, then A + B is compact. Where
A + B = {x + y; x ∈ A, , y ∈ B}.

A: $f:\mathbb R^2 \to \mathbb R $ given by addition is continuous, and so $f (A\times B) $ is compact.


text:
Q: PHP: Need to close STDIN in order to read STDOUT? I recently tried to communicate with a binary on my Ubuntu webserver [1] using the PHP function proc_open. I can establish a connection and define the pipes STDIN, STDOUT, and STDERR. Nice.
Now the bimary I am talking to is an interactive computer algebra software - therefore I would like to keep both STDOUT and STDIN alive after the first command such that I can still use the application a few lines later in an interactive manner (direct user inputs from a web-frontend).
However, as it turns out, the PHP functions to read the STDOUT of the binary (either stream_get_contents or fgets) need a closed STDIN before they can work. Otherwise the program deadlocks.
This is a severe drawback since I can not just reopen the closed STDIN after closing it. So my question is: why does my script deadlock if I want to read the STDOUT when my STDIN is still alive?
Thanks
Jens
[1] proc_open returns false but does not write in error file - permissions issue?
my source:
$descriptorspec = array(
    0 => array("pipe","r"),
    1 => array("pipe","w"),
    2 => array("file","./error.log","a")
) ;

// define current working directory where files would be stored
$cwd = './' ;

// open reduce
$process = proc_open('./reduce/reduce', $descriptorspec, $pipes, $cwd) ;

if (is_resource($process)) {

    // some valid Reduce commands
    fwrite($pipes[0], 'load excalc; operator x; x(0) := t; x(1) := r;');

    // if the following line is removed, the script deadlocks
    fclose($pipes[0]);

    echo "output: " . stream_get_contents($pipes[1]);

    // close pipes & close process
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    proc_close($process);

}

EDIT:
This code kind of works. Kind of because it uses usleeps to wait for the non-blocked STDOUT to be filled with data. How do I do that more elegantly?
@ Elias: By polling the $status['running'] entry you can only determine if the overall process is still running, but not if the process is busy or idling... That is why I have to include these usleeps.
define('TIMEOUT_IN_MS', '100');
define('TIMEOUT_STEPS', '100');

function getOutput ($pipes) {
    $result = "";
    $stage = 0;
    $buffer = 0;
    do {
        $char = fgets($pipes[1], 4096);
        if ($char != null) {
            $buffer = 0;
            $stage = 1;
            $result .= $char;
        } else if ($stage == "1") {
            usleep(TIMEOUT_IN_MS/TIMEOUT_STEPS);
            $buffer++;
            if ($buffer > TIMEOUT_STEPS) {
                $stage++;
            }
        }
    } while ($stage < 2);
    return $result;
}

$descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w") ) ;

// define current working directory where files would be stored
$cwd = './' ;

// open reduce
$process = proc_open('./reduce/reduce', $descriptorspec, $pipes, $cwd);

if (is_resource($process)) {

    stream_set_blocking($pipes[1], 0);

    echo "startup output:

" . getOutput($pipes) . "
";

    fwrite($pipes[0], 'on output; load excalc; operator x; x(0) := t; x(1) := r;' . PHP_EOL);
    echo "output 1:

" . getOutput($pipes) . "
";

    fwrite($pipes[0], 'coframe o(t) = sqrt(1-2m/r) * d t, o(r) = 1/sqrt(1-2m/r) * d r with metric g = -o(t)*o(t) + o(r)*o(r); displayframe;' . PHP_EOL);
    echo "output 2:

" . getOutput($pipes) . "
";

    // close pipes & close process
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    proc_close($process);

}

A: This reminds me of a script I wrote a while back. While it might serve as inspiration to you (or others), it doesn't do what you need. What it does contain is an example of how you can read the output of a stream, without having to close any of the streams.
Perhaps you can apply the same logic to your situation:
$allInput = array(
    'load excalc; operator x; x(0) := t; x(1) := r;'
);//array with strings to pass to proc
if (is_resource($process))
{
    $output = '';
    $input = array_shift($allInput);
    do
    {
        usleep(200);//make sure the running process is ready
        fwrite(
            $pipes,
            $input.PHP_EOL,//add EOL
            strlen($input)+1
        );
        fflush($pipes[0]);//flush buffered data, write to stream
        usleep(200);
        $status = proc_get_status($process);
        while($out = fread($pipes[1], 1024) && !feof($pipes[1]))
            $output .= $out;
    } while($status['running'] && $input = array_shift($allInput));
    //proc_close & fclose calls here
}

Now, seeing as I don't know what it is exactly you are trying to do, this code will need to be tweaked quite a bit. You may, for example, find yourself having to set the STDIN and STDOUT pipes as non-blocking.
It's a simple matter of adding this, right after calling proc_open, though:
 stream_set_blocking($pipes[0], 0);
 stream_set_blocking($pipes[1], 0);

Play around, have fun, and perhaps let me know if this answer was helpful in any way...

A: My guess would be that you're doing everything correctly, except that the binary is never notified that it has received all the input and can start to work. By closing STDIN, you're kicking off the work process, because it's clear that there will be no more input. If you're not closing STDIN, the binary is waiting for more input, while your side is waiting for its output.
You probably need to end your input with a newline or whatever other protocol action is expected of you. Or perhaps closing STDIN is the action that's expected of you. Unless the process is specifically created to stay open and continue to stream input, you can't make it do it. If the process reads all input, processes it, returns output and then quits, there's no way you can make it stay alive to process more input later. If the process explicitly supports that behaviour, there should be a definition on how you need to delimit your input.


text:
Q: How to add 2 more file uploads to Script allowing filenames to be sent to database and files to directory Hey guys ive been trying to change this upload.php around and im quite new to this. I need to add two more file upload fields to the script so that i can upload 3 images at one time to the database where i can echo out the filenames in posts and save to files to a directory and i dont know how to change the code below to suit
     upload.php
     <?php
     $link = mysql_connect('localhost', 'root', '');
      if (!$link) {
      die('Could not connect: ' . mysql_error());
      }

      mysql_selectdb("tutorials_upload");
      if(!is_dir("uploads")){//do we need to make the uploads directory for the files?
     mkdir("uploads");//make the rest of the script safe, though this will only be done       once

    }

     function savedata(){
      global $_FILES, $_POST, $putItAt;
     $sql = "INSERT INTO `tutorials_upload`.`thefiles` (
     `ID` ,
     `Time` ,
     `FileLocation` ,
     `IP` ,
     `Title`
      )
      VALUES (
       NULL , UNIX_TIMESTAMP( ) , '".mysql_real_escape_string($putItAt)."',      '".$_SERVER['REMOTE_ADDR']."', '".mysql_real_escape_string($_POST['Title'])."'
      );";
      mysql_query($sql);

     }
        $putItAt = "uploads/".basename($_FILES['uploadedfile']['name']);

      $putItAt = str_replace("php","txt", $putItAt);
     if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'],$putItAt)){

     savedata();
     header("location: listfiles.php");//redirect them to the listfiles.php page

     }else{
    if(copy($_FILES['uploadedfile']['tmp_name'],$putItAt)){

      savedata();
       header("location: listfiles.php");
    }else{

       echo 'You totally failed. click here to go back and try again.';
     }
     }
   ?>

the database is
      ID,
      Time,
      FileLocation,
      IP and Title

and i would like to add FileLocation2 and FileLocation3 to the database
and the form is
       <form enctype="multipart/form-data" action="upload.php" method="post">
        Choose your file to upload!
        <input name="uploadedfile" type="file" />

         And what would you like to call it? <input name="title" type="text" />

         <input type="submit" value="upload file"/>
        </form>

What i need to do is add 2 more file upload fields to the form and post the file names to 2 more image name fields i will put in the database Thanks Guys

A: This would help.
<form action="file-upload.php" method="post" enctype="multipart/form-data">
      Send these files:

      <input name="userfile[]" type="file" />

      <input name="userfile[]" type="file" />

      <input name="userfile[]" type="file" />

      <input type="submit" value="Send files" />
    </form>

$_FILES['userfile']['name'][0]  would contain the first uploaded file.
$_FILES['userfile']['name'][1]  would contain the second . .  and so on.
You can use a foreach and perform the queries. Something like
foreach ($_FILES['image']['name'] as $i => $name) { }


text:
Q: Disable horizontal scrolling in flutter webview I'm using this flutter WebView plugin https://pub.dartlang.org/packages/flutter_webview_plugin
The app is running perfectly. However, when the webpage loads, there is a horizontal scrolling bar in some websites and if I scroll horizontally those are only white empty spaces in the website. I want to disable this horizontal scrolling feature to keep user experience on point.
Horizontal Scrolling in the screenshot
I want the webview look like this with horizontal scrolling disabled
The test code is given below:
webview.dart
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

class WebViewExample extends StatefulWidget {
  @override
  _WebViewExampleState createState() => _WebViewExampleState();
}

class _WebViewExampleState extends State<WebViewExample> {
  FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
  var urlString = "https://www.prothomalo.com/bangladesh/article/1565521/%E0%A6%B6%E0%A6%A4%E0%A6%AD%E0%A6%BE%E0%A6%97-%E0%A6%B8%E0%A7%81%E0%A6%B7%E0%A7%8D%E0%A6%A0%E0%A7%81-%E0%A6%A8%E0%A6%BF%E0%A6%B0%E0%A7%8D%E0%A6%AC%E0%A6%BE%E0%A6%9A%E0%A6%A8-%E0%A6%B9%E0%A6%AC%E0%A7%87-%E0%A6%A8%E0%A6%BE-%E0%A6%95%E0%A6%AC%E0%A6%BF%E0%A6%A4%E0%A6%BE-%E0%A6%96%E0%A6%BE%E0%A6%A8%E0%A6%AE";

  @override
  void initState() {
    super.initState();
    flutterWebviewPlugin.onStateChanged.listen((WebViewStateChanged wvs) {
      print(wvs.type);
    });
  }

  @override
  Widget build(BuildContext context) {
    return WebviewScaffold(
      appBar: AppBar(
        title: new Text(
          'WebView Test',
          style: new TextStyle(
            color: Colors.white,
          ),
        ),
      ),
      url: urlString,
      withZoom: false,
    );
  }
}

A: In my case it was enough to wrap the WebView in a GestureDetector widget and override onHorizontalDragUpdate() callback.
WebViewController _webViewController;

GestureDetector(
    onHorizontalDragUpdate: (updateDetails) {},
    child: WebView(
      initialUrl: 'about:blank',
      onWebViewCreated: (WebViewController webViewController) {
        _webViewControllerHeader = webViewController;
      },
    ),
)

To disable vertical scrolling in flutter webview you can override onVertivalDragUpdate() correspondingly.
Look for more info here and here.


text:
Q: Why does the value returned from front() exist even after pop() from std::queue? I'm collecting the value returned from queue::front() into a local variable. As per documentation, queue::front() returns the reference.
So if I pop it off from the queue, how can the collected value still exist?
int main()
{
    std::string val;
    {
        std::queue<std::string> q;
        q.push("one");
        q.push("two");
        q.push("three");
        val = q.front();
        q.pop();
        q.pop();
        q.pop();
        std::cout << "is queue empty: " << boolalpha << q.empty() << '\n';
    }

    std::cout << "val: " << val << '\n';
}

The output is:
is queue empty: true
val: one

Why does val still has "one" after pop()'ing

A: Because val is not a reference. Not to the front of the queue or anywhere else.
When you do
val = q.front();

you copy what's currently at the front of the queue into val.
What you do later with the queue will not affect this copy.
If you want a reference then you need to make val a reference.
And remember that by making val a reference, it will only reference one single element in the queue. Once you pop the front once, that reference becomes invalid. Adding new elements will not change your reference, it will still reference the same element in the queue, it will not reference the new front. And you can not rebind a reference once bound.
All in all, using references to elements in a queue is in most use-cases pretty useless.


text:
Q: WinSCP + Tortoise SVN/Merge - compare/diff local and remote files When using WinSCP, we can define customized commands to do task, like to compare file contents.
The built-in one is:
cmd /c fc "^!^" "!" | more && pause

using the Windows fc(file compare) utility.
Now, I use TortoiseMerge of TortoiseSVN to compare file content and it is perfect. I think it is the best free text compare software in Windows, and it allows us to specify the files to compare upon launch. Actually, I use this line in my git-bash config file to use TortoiseMerge to do git diff:difftool.tortoisediff.cmd="C:\some\path\TortoiseSVN\bin\TortoiseMerge.exe" -mine $REMOTE -base $LOCAL.
So, can I combine WinSCP with TortoiseMerge, to enable side-by-side edition? I think with that enabled, WinSCP can beat Beyond Compare, which is licensed and not free.

A: After some time trial-and-error, I find the correct syntax.
For uploading code to remote:
C:\some\random\path\to\TortoiseSVN\bin\TortoiseMerge.exe -base "!^!" -mine "!"

For downloading code to local:
C:\some\random\path\to\TortoiseSVN\bin\TortoiseMerge.exe -mine "!^!" -base "!"

"!^!" represents local file, and "!" represents remote file.
Remember that in TortoiseMerge we define the left side as the "base", and we can only copy code from left side to right side, so for uploading and downloading, we reverse the position of local and remote file.
To use these commands, we open "File" - "File Custom Commands" - "Customize..", and "New" a command, and "Save". At last, we activate the Command toolbar to show buttons above working area. You can define the name of these two commands as you like, like "Diff commit"/"Diff clone", or "Diff push"/"Diff pull".
At last: select the local and remote files at the same time to make the button available.


text:
Q: ReactiveCommand: get command parameter in ThrownExceptions In my scenario I use command to delete something from DB. I have ReactiveCollection bound to DataGrid in WPF and following code for handling delete:
 RemoveProductCommand = ReactiveCommand.CreateFromTask<Product>(async product =>
            {
                await _licensingModel.RemoveProduct(product.Id);
            });

            RemoveProductCommand.ThrownExceptions.Subscribe(async ex =>
            {
                await ShowToUserInteraction.Handle("Could not remove product ");
            });

            Products.ItemsRemoved.Subscribe(async p =>
            {
               await RemoveProductCommand.Execute(p);
            });

My question is, is there a built-in way for getting product (command argument) in ThrownExceptions?
I can of course do something like that:
 RemoveProductCommand = ReactiveCommand.CreateFromTask<Product>(async product =>
            {
                try
                {
                    await _licensingModel.RemoveProduct(product.Id);
                }
                catch (Exception e)
                {
                    throw new ProductRemoveException(product, e);
                }

            });

My reasoning is that I want to notify user with information "Could not remove product X".
EDIT:
Alright, I edited code for pasting here and noticed difference between awaiting command.Execute() and Subscribing.
It is possible to:
  Products.ItemsRemoved.Subscribe(async p =>
            {
                try
                {
                    await RemoveProductCommand.Execute(p);
                }
                catch (Exception e)
                {

                }
            });

but what about ThrownExceptions?

A:
My question is, is there a built-in way for getting product (command argument) in ThrownExceptions?

No, ThrownExceptions is an IObservable<Exception>, i.e. you subcribe to it to get a stream of Exceptions only. It doesn't know about any command arguments that were passed to the command before the actual exception occured.
You will need to store this parameter value yourself somehow, for example by defining and throwing a custom Exception from your Execute method.


text:
Q: Hybrid app using phoneGap to Record video and split every 10min I am trying to record video on iPhone using phoneGap mediaCapture API, which records and saves it to media files with in the application perfectly if I want to split the video and save recording every 10 minutes so as develop a dash cam application.
I tried this code which records for 10 minutes and automatically stops but actually I want this happen every time 10min continuously 5 times as i set limit to 5.
$(document).ready(function(){
$("#rec").click(function(){
var captureSuccess = function(mediaFiles)
{
  var i, path, len;
  for (i = 0,len = mediaFiles.length; i < len; i += 1)
  {
    path =mediaFiles[i].fullPath; // do something interesting with the file
   }
};

// capture error callback
var captureError = function(error) {
navigator.notification.alert('Error code: ' + error.code, null, 'CaptureError');
};

// start video capture
navigator.device.capture.captureVideo(captureSuccess, captureError, {
limit:5, duration:600 });
});

});

A: You should be able to just start another navigator.device.capture.captureVideo(.. ..) in the captureSuccess callback handler
The easiest way would be to put the original one in a function and call that function in the captureSuccess function


text:
Q: reactjs - communication between two components I want to call a function from one component to another. I've tried a few different things after googling, but as I'm new to reactjs I can't seem to work it out. I thought I could import the state and then change it from the other component (see below) but I think I'm barking up the wrong tree?
I want to call showMenu() in header.js from locationform.js
header.js
import React, { Component, PropTypes } from 'react';
import ReactF1 from 'react-f1';

// Styles.
import styles from './Header.css';

// Elements.
import Menu from './elements/Menu';

// Menu states.
import { states, SHOWBUTTON, IDLE, HIDE, OUT } from './elements/Menu/states';

import transitions from './elements/Menu/transitions';

function changeOffset() {
  document.querySelector('svg path').style.strokeDashoffset = 0;
  setTimeout("document.querySelector('svg path').style.strokeDashoffset = 171", 2000);
}

export default class Header extends Component {
  static get propTypes() {
    return {
      children: PropTypes.element,
    };
  }

  constructor(props, context) {
    super(props, context);

    this.state = {
      menuState: OUT,
      hamburgerState: OUT,
    };
  }

  componentDidMount() {
    if (this.props.router.location.pathname === '/') {
      setTimeout(() => this.setState({ hamburgerState: SHOWBUTTON }), 6000);
    } else {
      this.setState({ hamburgerState: SHOWBUTTON });
    }
    // setTimeout(changeOffset, 8000);
  }

  completeF1Handler() {}

  showMenu() {
    this.setState({ menuState: IDLE });
  }

  hideMenu() {
    this.setState({ menuState: HIDE });
  }

  reset() {
    this.setState({ menuState: OUT });
  }

  render() {
    const { stageWidth, stageHeight } = this.props;

    return (
      <ReactF1
        className={styles.Header}
        go={this.state.hamburgerState}
        states={states(stageWidth, stageHeight)}
        transitions={transitions()}
        onComplete={() => this.completeF1Handler()}
      >
        <svg className={styles.hamburger} data-f1="hamburger" width="50" height="50">
          <path
              className={styles.triangle}
              d="M0 0 L50 0 L0 50 Z"
              onClick={this.showMenu.bind(this)}
              fill={this.props.menuColor}
          />
        </svg>
        <Menu
          go={this.state.menuState}
          close={this.hideMenu.bind(this)}
          reset={this.reset.bind(this)}
        />
      </ReactF1>
    );
  }
}

locationform.js
import React, { Component, PropTypes } from 'react';
import { isDesktop } from '../../utils/device';
import LocateSelect from '../LocateSelect';

import styles from './LocationForm.css';
import buttonStyles from '../Button/Button.css';

// Menu states.
import { states, SHOWBUTTON, IDLE, HIDE, OUT } from '../Header/elements/Menu/states';

export default class LocationForm extends Component {
  static get propTypes() {
    return {
      zipCode: PropTypes.string,
      searchRadius: PropTypes.string,
      businessType: PropTypes.string,
      handleChange: PropTypes.func,
      handleGeolocate: PropTypes.func,
      handleSubmit: PropTypes.func,
    };
  }

  constructor(props, context) {
    super(props, context);
  }

  showMenu() {
    console.log("show menu");
      this.setState({ menuState: IDLE });
  }

  renderSelect() {
    const { searchRadius, businessType, handleChange } = this.props;

    return (

        <LocateSelect
          id="searchRadius"
          defaultValue=""
          value={searchRadius}
          handleChange={handleChange}
          options={[
            {
              value: '',
              text: 'SEARCH RADIUS',
            },
            {
              value: '1',
              text: '1 MI',
            },
            {
              value: '5',
              text: '5 MI',
            },
            {
              value: '10',
              text: '10 MI',
            },
            {
              value: '25',
              text: '25 MI',
            },
          ]}
        />
        <LocateSelect
          id="businessType"
          defaultValue=""
          value={businessType}
          handleChange={handleChange}
          options={[
            {
              value: '',
              text: 'BUSINESS TYPE',
            },
            {
              value: 'bar',
              text: 'Bar',
            },
            {
              value: 'restaurant',
              text: 'Restaurant',
            },
            {
              value: 'liquorstore',
              text: 'Liquor Store',
            },
          ]}
        />

    );
  }

  render() {
    const {
      zipCode,
      handleChange,
      handleSubmit,
      handleGeolocate,
      handleFocus,
      handleBlur,
    } = this.props;

    return (
      <form className={styles.LocationForm} onSubmit={handleSubmit}>
        <input
          type="button"
          className={`${buttonStyles.Button} ${buttonStyles.dark} ${styles.geolocate}`}
          value="Use Current Location"
          onClick={handleGeolocate}
        />

OR

        <input
          id="zipCode"
          type="text"
          placeholder="ZIP CODE"
          value={zipCode}
          maxLength="5"
          pattern="[0-9]*"
          onFocus={handleFocus}
          onBlur={handleBlur}
          onChange={event => handleChange(event.target.id, event.target.value)}
        />
        {this.renderSelect()}
        <input
          className={`${buttonStyles.Button} ${buttonStyles.dark}`}
          type="submit"
          value="search"
        />

 this.showMenu()}>
              No

      </form>
    );
  }
}

A: With considering parent child communication in react you have to write a parent for both of these files and passing the function and the state as props .
For example :
app.js
import Header from './header.js'
import LocationForm from './location-form.js'

export default class App extends Component {
  state = {menuState : 'out'}
  showMenu() {
    this.setState({ menuState:'idle' });
  }
  render(){
    return(

        <LocationForm showMenu={this.showMenu} menuState={this.state.menuState}/>

    )
  }
}

I think this concept of thinking will help you to reach the answer

A: So in react in order to pass data from parent to child elements you need to pass them down as props
So using your Menu component as an example you would pass the methods you want to use down to that child component like this: (I would recommend converting those to es6 syntax so you don't have to bother with binding).

//METHODS SECTION
const showMenu = () => {
    this.setState({ menuState: IDLE });
  }

  const hideMenu = () => {
    this.setState({ menuState: HIDE });
  }

  const reset = () => {
    this.setState({ menuState: OUT });
  }

//IN YOUR RENDER METHOD
<Menu
          go={this.state.menuState}
          close={this.hideMenu.bind(this)}
          reset={this.reset.bind(this)}
          showMenu={this.showMenu}
          hideMenu={this.hideMenu}
          reset={this.reset}
        />

Then in your child component you would refer to that method as this.props.showMenu or this.props.hideMenu or this.props.reset:
onClick(() => {this.props.showMenu()})

If you want the method to fire on an event you should wrap it in an anonymous function like I did above. You can also add it to another method within the child component that will get called when that method is called so:
const doSomething = () => {
   count++
   this.props.showMenu()
}

onClick(() => {this.doSomething()})

When you use the method in the child component it is still bound to the parent component. This is the main way of sending data back up to the parent. You could, for instance, have the method simply setState of a value on the parent component, pass the method down to the child as props with parameter requirements, pass the parameters in on the child and send it back up to parent when it is called. (Let me know if that was confusing)
There is a lot in your app that isn't very "React" so I would definitely recommend going through their documentation. Starting with: https://reactjs.org/docs/components-and-props.html and watching some videos on Youtube about state management in React.

A: Communication between parents is best thought of as having two methods of operating:

*

*Parents can pass their children props

*Children can call functions which are passed to them from their parents

This means that the relationship between components is defined via. their props. It's a one way method of communication that makes it much easier to build components as detached modules that happen to be connected in a given context.
So if you have something like:
         Child A
       /
Parent
       \
         Child B

Then you need to communicate via. the Parent. The children will call a function given to them by their parent, and the parent will pass down a new prop to the child components.
You can also do this thing via context, which allows you to avoid having to pass all of these props down manually, but does not affect the streams of communication available to components.

const ButtonComponent = (props) => {
  return (

      Child
      <button onClick={props.handleClick}>
        Do the thing
      </button>

  );
};

const CountDisplay = (props) => {
  return (

{props.count}

  );
};

const Parent = (props) => {
  const parentLog = () => console.log('log from parent');
  const [
    currentCount,
    setCurrentCount,
  ] = React.useState(0);

  return (

      Parent
      <ButtonComponent handleClick={() => setCurrentCount(currentCount + 1)} />
      <CountDisplay count={currentCount} />

  );
};

ReactDOM.render(<Parent />, document.getElementById('app'))


text:
Q: Why when painting one source to another am i getting the wrong colors When I try the following I expect the two images to be the same but they are not!
I'm new to this cairo thing and this is driving me mad.
#!/usr/bin/env python

import cairo

WIDTH, HEIGHT = 256, 256

pat = cairo.LinearGradient (0.0, 0.0,  0.0, 1.0)
pat.add_color_stop_rgb (1,    1,   0,  0) # First stop
pat.add_color_stop_rgb (0.5,  0,   1,  0) # Mid stop
pat.add_color_stop_rgb (0,    0,   0,  1) # Last stop

# A surface

surface0 = cairo.ImageSurface (cairo.FORMAT_RGB24, WIDTH, HEIGHT)
ctx0 = cairo.Context (surface0)
ctx0.scale (WIDTH, HEIGHT)

ctx0.set_source(pat)
ctx0.paint()

# My second surface

surface1 = cairo.ImageSurface (cairo.FORMAT_RGB24, WIDTH, HEIGHT)
ctx1 = cairo.Context (surface1)
ctx1.scale (WIDTH, HEIGHT)

ctx1.set_source_surface(surface0, 0, 0)
ctx1.set_operator (cairo.OPERATOR_SOURCE)
ctx1.paint()

surface0.write_to_png("example0.png")
surface1.write_to_png("example1.png")

A: What you are trying to do:

*

*Create a pattern called pat

*Paint that pattern to surface0 with some scale

*Copy surface0 to surface1
Right?
In this case you should remove the call ctx1.scale (WIDTH, HEIGHT). Due to that, you will only get the top-left pixel(?) of the first surface drawn to the second one.


text:
Q: magento 2 add bundle items into cart dynamically with quantity I want to add bundle products with quantity dynamically into cart.
I am able to add products but quantity is not updated. it is always 1.
Is there any way to solve this issue.
below code i am using for that.
$product = $this->_productRepository->getById(89,false, null, true);

$bundle_option = [ 1 => array(2,8,18) ];  // 2,8,18 are selection ids, 1 is option id
$bundle_qty = [ 1 => array(2,3,4) ]; // 2,3,4 are quantity, 1 is option id

$params = [
    'form_key' => $this->formKey->getFormKey(),
    'product' => 89,
    'bundle_option' => $bundle_option,  // it is working fine
    'bundle_option_qty' => $bundle_qty,  // logically it will work but in my case it is not working.
    'qty' => $totalqty
];

$this->cart->addProduct($product, $params);
$this->cart->save();

Please help. Thanks in advance.

A: $product = $this->_productRepository->getById($id, false, null, true);
$this->_cart->addProduct($product, $data);

where $data is an array as shown below:
$data = [
    'qty' => 1,
    'product' => 45,
    'bundle_option' => [
        1 => 4,
        2 => 8,
        3 => 2,
        4 => 7,
    ],
    'bundle_option_qty' => [
        1 => 1,
        2 => 4,
        3 => 2,
        4 => 14,
    ]
];

the keys inside bundle_option and bundle_option_qty are indexes, not some ID's. I reckon it doesn't matter what these keys are as long as they correspond to the keys in the other array.
Items inside bundle_option array are options ID's and the other contains quantities so in this case we add 1 item ID=4, 4 items ID=8 and so on...

A: $data = [
    'qty' => 1,
    'product' => 45,
    'bundle_option' => [
        1 => 4,
        2 => 8,    // this is selection ids
        3 => 2,
        4 => 7,
    ],
    'bundle_option_qty' => [
        1 => 1,
        2 => 4, // this is qty
        3 => 2,
        4 => 14,
    ]
];
but it is not working, i already tried.
in bundle product, option type is checkbox ( with 5 products selected
) & there is no option e.g User defined quantity [checkbox] ( in magento guide it is mention )
pl. suggest other working solution
pl. help me


text:
Q: Insert a script at the top of HEAD tag in PageMod (Firefox Add-on SDK) I want to insert a script in Firefox Add-on SDK content script added via  page-mod. So, when user goes to page XXX, he gets a page with the inserted script. But, when trying to insert this at the top of HEAD, I got an error that the 1st Node child is not an object.
My content script code with which I insert the <script> is:
script='<script>var d=new Date(2012,2,24); window.Date=function () {return d;}</script>';

var head = document.getElementsByTagName("head")[0];
head.insertBefore(script, head.firstChild);

What's with it?

A: You have not provided a Minimal, Complete, and Verifiable Example. Thus, this answer is based just on the code you have provided.
Issue with how you are using insertBefore():
The first issue I noticed is that you are providing a string as the first argument to insertBefore() when that argument needs to be a node object.
However, you state the error you are getting is "1st Node child is not an object". This does not match what I would expect from an error based on the code provided.  When I put your code in a page-mod content script, the error I got was:
console.error: testpagemodinsertBefore:
Object
    - _errorType = TypeError
    - message = Argument 1 of Node.insertBefore is not an object.
    - fileName = resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/commonjs/sdk/loader/sandbox.js -> resource://testpagemodinsertbefore/data/contentScript.js
    - lineNumber = 26
    - stack = @resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/commonjs/sdk/loader/sandbox.js -> resource://testpagemodinsertbefore/data/contentScript.js:26:1|
    - name = TypeError

This is the error which I would expect from the code in the question.  Thus, you have either not posted the code which is producing the error you have stated, or you have inaccurately reported the error which you saw in the console. In the future, please be exact in what you are reporting. Being more verbose is better than leaving things out.
Inserting HTML text:
Your code:
script='<script>var d=new Date(2012,2,24); window.Date=function () {return d;}</script>';

defines some HTML text which you are trying to insert into the DOM.
If you want to insert HTML text instead of inserting nodes, one way for you to do so is to use insertAdjacentHTML(). One way you could do this in your code is:
head.insertAdjacentHTML('afterbegin',script);

This works well for most HTML. But, does not result in the contents of the <script> tag being executed/evaluated. This is for security reasons. It is much easier for an attacker to get arbitrary text inserted into the DOM than it is for them to insert actual nodes/elements. The HTML specification specifies that a  tag inserted inserted as text will not be executed.
Inserting a <script> tag that is evaluated and executed:
We can do this by creating a <script> element containing the script text desired, then inserting that element into the DOM.
For your code that would look something like:

//Get the first <head> element
let head = document.getElementsByTagName("head")[0];

//The script text desired
let scriptText='var d=new Date(2012,2,24); window.Date=function () {return d;};';

//Add an alert for testing (\n is not needed. But, is more readable when inspecting DOM.)
scriptText = 'window.alert("In inserted script");\n' + scriptText;

//Create a <script> element
let scriptEl = document.createElement( 'script' );
//That is JavaScript
scriptEl.type = 'text/javascript';
//Add the script text
scriptEl.textContent = scriptText;
//Insert it as the firstChild of <head>
head.insertBefore( scriptEl, head.firstChild );

Further reading:
You appear to be desire to interact with page scripts using your content script.  I suggest that you read the MDN page "Interacting with page scripts".


text:
Q: reversing an array in javascript I have a Javascript function called reverseArray that takes an array as the argument and returns a new array which has the same values as the input array in reverse order. I want to create a function called reverseArryInPlace which would change the value of the input array to the reverse order.
function reverseArray(inputArray) {
  var outputArray = [];
  for (var i = inputArray.length - 1; i >= 0; i--)
    outputArray.push(inputArray[i]);
  return outputArray;
}

function reverseArrayInPlace(inPlaceInputArray) {
  inPlaceInputArray = reverseArray(inPlaceInputArray);
  console.log('Inside reverseArrayInPlace: ' + inPlaceInputArray);
  return inPlaceInputArray;
}

var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log('Outside reverseArrayInPlace: ' + arrayValue);
// Expected Value: [5, 4, 3, 2, 1]

Here is the result I get when I execute this chunk of code:
Inside reverseArrayInPlace: 5,4,3,2,1
Outside reverseArrayInPlace: 1,2,3,4,5

Within the reverseArrayInPlace function the arrayValue variable has been reversed as expected. Why is it that when I reference the same variable outside the reverseArrayInPlace function, it is back to the original order?

A: If you want to reverse it in place, you have to reverse it in place.

function reverseArrayInPlace(array) {
  for (let i = 0, j = array.length - 1; i < j; i++, j--)
    [array[i], array[j]] = [array[j], array[i]];
}

const a = [1,2,3,4,5];
reverseArrayInPlace(a);
console.log(a);

A: The underlying problem here is that primitives are passed by value in JavaScript. See the following question for details:
Javascript by reference vs. by value
As a simple example, here is a function that attempts to mutate a string that was passed to it:
var outsideValue = 'foo'

function mutate(value) {
  value = 'fish'
}

mutate(outsideValue);
console.log(outsideValue);

However, the console output is foo.
This happens because the value variable within the mutate function is a variable that has a reference to outsideValue when the function is initially invoked. When it is assigned the new value within the function body, it merely changes the value variable to reference a new string. As a result, the outsideValue is untouched.
Check this answer for an example that reverses in place:
https://stackoverflow.com/a/43486686/249933
Notice, that it does not re-assign the function argument.

A: As others have said, arrays are objects so they're passed by reference. You have to modify the original array, not create a new one.
So here's another version of reverseInPlace, it uses shift to remove the last element from the array and splice to insert it in the new location:

function reverseInPlace(arr) {
  var i = arr.length;
  while (i--) {
    arr.splice(i, 0, arr.shift());
  }
}

var arr = [1,2,3,4,5];
console.log('Before: ' + arr.join());

reverseInPlace(arr);
console.log('After:  ' + arr.join());

For some fun, you can also leverage sort:
NB: this only works in some browsers, it's dependent on the built-in sort algorithm which is implementation dependent.

function reverseInPlace(arr) {
  arr.sort(() => 1);
}

var arr = [47, 95, 80, 62, 8, 34, 31, 17, 62, 17, 85, 72, 51, 20, 68, 60, 30, 84, 7, 34];
console.log('Before: ' + arr.join());

reverseInPlace(arr);
console.log('After : ' + arr.join());

A: function reverseArray(inputArray) {
  var outputArray = [];
  for (var i = inputArray.length - 1; i >= 0; i--)
    outputArray.push(inputArray[i]);
  return outputArray;
}

function reverseArrayInPlace(inPlaceInputArray) {
  inPlaceInputArray = reverseArray(inPlaceInputArray);
  console.log('Inside reverseArrayInPlace: ' + inPlaceInputArray);
  return inPlaceInputArray;
}
var arrayValue = [1, 2, 3, 4, 5];
**arrayValue = reverseArrayInPlace(arrayValue);**
alert('Outside reverseArrayInPlace: ' + arrayValue);
// Expected Value: [5, 4, 3, 2, 1]

//
your code is correct your just need to replace one line and write
 arrayValue = reverseArrayInPlace(arrayValue);
instead of
reverseArrayInPlace(arrayValue);
Then arratValue will print expected values


text:
Q: Add Data from two tables into a bridge table that has two foreign keys from same two tables in SQL Server 2014 I have 2 tables and one bridge table that consist of foreign key of both tables. I am trying to insert data from both table into a bridge table. can anyone please help me out. Following is scenario.

*

*Tb1 Product (id (pk), name) --> column Name consists of 7 rows with different product name

*Tb2 Vendor (id (pk), name)--> column Name consist of 3 rows with different vendor name

*Tb3 VendorProduct (id, productid (fk), vendorid(fk), cost)
Also I would like to include the data for cost too. I have a feeling I have to use FULL OUTER JOIN to insert data for cost.
Thanks in advance for help!