Using and_ in sqlalchemy filter does not work Posted: 14 Jun 2021 08:06 AM PDT When using the notlike filter, the statment works: result = self.session.query(PropMetadata, FloorPlan).join(FloorPlan, FloorPlan.prop_metadata_id == PropMetadata.id).\ filter(FloorPlan.rent_range.notlike('%Call%')) When using the == filter, the statement works (floorplan is being passed into my function): result = self.session.query(PropMetadata, FloorPlan).join(FloorPlan, FloorPlan.prop_metadata_id == PropMetadata.id).\ filter(FloorPlan.layout == floorplan) When combining with and_ , I get this error: result = self.session.query(PropMetadata, FloorPlan).join(FloorPlan, FloorPlan.prop_metadata_id == PropMetadata.id).\ filter(and_( FloorPlan.rent_range.notlike('%Call%'), FloorPlan.layout == floorplan )) sqlalchemy.exc.ArgumentError: Mapped instance expected for relationship comparison to object. Classes, queries and other SQL elements are not accepted in this context; for comparison with a subquery, use FloorPlan.prop_metadata.has(**criteria). How can I fix this? |
Best way to plot this data on the same graph? (R/GGplot2) Posted: 14 Jun 2021 08:06 AM PDT In advance, I apologize for such an easy question, I'm a student and still getting used to things. First, here's an idea of the data I'm working with. Date bfolioTotalInvNZ hpfolioTotalInvNZ lpfolioTotalInvNZ hROATotalInvNZ lROATotalInvNZ hlROAPortfolio 20160502 2016-05-02 58.7403353336499 100 100 100 100 0 20160503 2016-05-03 58.9734161749733 99.8882748824908 100.680353722841 100.38312056174 100.611388876841 -0.228268315100593 20160504 2016-05-04 58.9104350721506 98.8225791351364 99.7285569078393 100.860708831452 99.7567183567618 1.10399047469059 20160509 2016-05-09 58.6927641731177 98.0760852984932 99.2649714247455 99.4017877917418 99.9634937211577 -0.561705929415993 20160510 2016-05-10 58.9986662648295 99.6998217808326 100.21300064583 100.396352403539 101.234588176424 -0.838235772884829 20160511 2016-05-11 58.8137451373407 99.8428365508291 100.043862125597 101.764817682509 102.218770263564 -0.453952581054466 hlPerFolio 20160502 0 20160503 -0.792078840350058 20160504 -0.905977772702926 20160509 -1.18888612625226 20160510 -0.513178864997784 20160511 -0.201025574768337 It's a dataframe of values that goes up/down as time goes, basically portfolio returns. I'm trying to graph them all on the same plot and really can't get it to work. I was thinking about just leaving it off but I really wanted to figure this out. Any help would be appreciated. |
Apache Beam Python gscio upload method has @retry.no_retries implemented causes data loss? Posted: 14 Jun 2021 08:05 AM PDT I have a Python Apache Beam streaming pipeline running in Dataflow. It's reading from PubSub and writing to GCS. Sometimes I get errors like "Error in _start_upload while inserting file ...", which comes from: File "/usr/local/lib/python3.8/site-packages/apitools/base/py/base_api.py", line 603, in __ProcessHttpResponse raise exceptions.HttpError.FromResponse( RuntimeError: apitools.base.py.exceptions.HttpError: HttpError accessing <https://www.googleapis.com/resumable/upload/storage/v1/b/<bucke-name>/o?alt=json&name=tmp%2F.tempaf83360e-673f-4f9a-b15a-5be45081c335%2F3919075269125806430_9535790f-f57d-430f-9631-f121966e5ca4&uploadType=resumable&upload_id=<id>>: response: <{'content-type': 'text/plain; charset=utf-8', 'x-guploader-uploadid': '<id>', 'content-length': '0', 'date': 'Thu, 10 Jun 2021 14:58:51 GMT', 'server': 'UploadServer', 'status': '503'}>, content <> [while running 'Write to GCS/ParDo(_WriteShardedRecordsFn)-ptransform-50705'] passed through: ==> dist_proc/dax/workflow/worker/fnapi_service.cc:631 The underlying issue seems to be that there is no retry logic applied in method _start_upload here, and when there is an HttpError (503 in this case), it's not handled: # TODO(silviuc): Refactor so that retry logic can be applied. # There is retry logic in the underlying transfer library but we should make # it more explicit so we can control the retry parameters. @retry.no_retries # Using no_retries marks this as an integration point. def _start_upload(self): From my point of view, whenever these errors are thrown then there was a failed upload due to a server issue which wasn't even retried, and therefore that data is lost? Am I missing something or this is what's happening? If that's the case what is odd to my is that no-one else found this before. The piece of code that fails is using WriteToFiles from io.fileio. It looks like this (destination_partitioning_naming is a custom method): from apache_beam.io.fileio import WriteToFiles ... | "Write to GCS" >> WriteToFiles( path=output_path, shards=1, max_writers_per_bundle=0, destination=lambda record: record['topic_kafka'], sink=JsonSink(), file_naming=destination_partitioning_naming(extension="json", topics=topics) ) ) I have raised this issue in JIRA as well Here is the full stacktrace: 2021-06-10 16:58:55.104 CEST Error message from worker: generic::unknown: Traceback (most recent call last): File "apache_beam/runners/common.py", line 1239, in apache_beam.runners.common.DoFnRunner.process File "apache_beam/runners/common.py", line 768, in apache_beam.runners.common.PerWindowInvoker.invoke_process File "apache_beam/runners/common.py", line 891, in apache_beam.runners.common.PerWindowInvoker.invoke_process_per_window File "apache_beam/runners/common.py", line 1374, in apache_beam.runners.common._OutputProcessor.process_outputs File "/usr/local/lib/python3.8/site-packages/apache_beam/io/fileio.py", line 620, in process writer.close() File "/usr/local/lib/python3.8/site-packages/apache_beam/io/filesystemio.py", line 220, in close self._uploader.finish() File "/usr/local/lib/python3.8/site-packages/apache_beam/io/gcp/gcsio.py", line 676, in finish raise self._upload_thread.last_error # pylint: disable=raising-bad-type File "/usr/local/lib/python3.8/site-packages/apache_beam/io/gcp/gcsio.py", line 651, in _start_upload self._client.objects.Insert(self._insert_request, upload=self._upload) File "/usr/local/lib/python3.8/site-packages/apache_beam/io/gcp/internal/clients/storage/storage_v1_client.py", line 1154, in Insert return self._RunMethod( File "/usr/local/lib/python3.8/site-packages/apitools/base/py/base_api.py", line 731, in _RunMethod return self.ProcessHttpResponse(method_config, http_response, request) File "/usr/local/lib/python3.8/site-packages/apitools/base/py/base_api.py", line 737, in ProcessHttpResponse self.ProcessHttpResponse(method_config, http_response, request)) File "/usr/local/lib/python3.8/site-packages/apitools/base/py/base_api.py", line 603, in __ProcessHttpResponse raise exceptions.HttpError.FromResponse( apitools.base.py.exceptions.HttpError: HttpError accessing <https://www.googleapis.com/resumable/upload/storage/v1/b/<bucket-name>/o?alt=json&name=tmp%2F.tempaf83360e-673f-4f9a-b15a-5be45081c335%2F3919075269125806430_9535790f-f57d-430f-9631-f121966e5ca4&uploadType=resumable&upload_id=<uploadid>>: response: <{'content-type': 'text/plain; charset=utf-8', 'x-guploader-uploadid': '<id>, 'content-length': '0', 'date': 'Thu, 10 Jun 2021 14:58:51 GMT', 'server': 'UploadServer', 'status': '503'}>, content <> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/apache_beam/runners/worker/sdk_worker.py", line 289, in _execute response = task() File "/usr/local/lib/python3.8/site-packages/apache_beam/runners/worker/sdk_worker.py", line 362, in <lambda> lambda: self.create_worker().do_instruction(request), request) File "/usr/local/lib/python3.8/site-packages/apache_beam/runners/worker/sdk_worker.py", line 606, in do_instruction return getattr(self, request_type)( File "/usr/local/lib/python3.8/site-packages/apache_beam/runners/worker/sdk_worker.py", line 644, in process_bundle bundle_processor.process_bundle(instruction_id)) File "/usr/local/lib/python3.8/site-packages/apache_beam/runners/worker/bundle_processor.py", line 999, in process_bundle input_op_by_transform_id[element.transform_id].process_encoded( File "/usr/local/lib/python3.8/site-packages/apache_beam/runners/worker/bundle_processor.py", line 228, in process_encoded self.output(decoded_value) File "apache_beam/runners/worker/operations.py", line 357, in apache_beam.runners.worker.operations.Operation.output File "apache_beam/runners/worker/operations.py", line 359, in apache_beam.runners.worker.operations.Operation.output File "apache_beam/runners/worker/operations.py", line 221, in apache_beam.runners.worker.operations.SingletonConsumerSet.receive File "apache_beam/runners/worker/operations.py", line 718, in apache_beam.runners.worker.operations.DoOperation.process File "apache_beam/runners/worker/operations.py", line 719, in apache_beam.runners.worker.operations.DoOperation.process File "apache_beam/runners/common.py", line 1241, in apache_beam.runners.common.DoFnRunner.process File "apache_beam/runners/common.py", line 1321, in apache_beam.runners.common.DoFnRunner._reraise_augmented File "/usr/local/lib/python3.8/site-packages/future/utils/init.py", line 446, in raise_with_traceback raise exc.with_traceback(traceback) File "apache_beam/runners/common.py", line 1239, in apache_beam.runners.common.DoFnRunner.process File "apache_beam/runners/common.py", line 768, in apache_beam.runners.common.PerWindowInvoker.invoke_process File "apache_beam/runners/common.py", line 891, in apache_beam.runners.common.PerWindowInvoker._invoke_process_per_window File "apache_beam/runners/common.py", line 1374, in apache_beam.runners.common._OutputProcessor.process_outputs File "/usr/local/lib/python3.8/site-packages/apache_beam/io/fileio.py", line 620, in process writer.close() File "/usr/local/lib/python3.8/site-packages/apache_beam/io/filesystemio.py", line 220, in close self._uploader.finish() File "/usr/local/lib/python3.8/site-packages/apache_beam/io/gcp/gcsio.py", line 676, in finish raise self._upload_thread.last_error # pylint: disable=raising-bad-type File "/usr/local/lib/python3.8/site-packages/apache_beam/io/gcp/gcsio.py", line 651, in _start_upload self._client.objects.Insert(self._insert_request, upload=self._upload) File "/usr/local/lib/python3.8/site-packages/apache_beam/io/gcp/internal/clients/storage/storage_v1_client.py", line 1154, in Insert return self._RunMethod( File "/usr/local/lib/python3.8/site-packages/apitools/base/py/base_api.py", line 731, in _RunMethod return self.ProcessHttpResponse(method_config, http_response, request) File "/usr/local/lib/python3.8/site-packages/apitools/base/py/base_api.py", line 737, in ProcessHttpResponse self._ProcessHttpResponse(method_config, http_response, request)) File "/usr/local/lib/python3.8/site-packages/apitools/base/py/base_api.py", line 603, in __ProcessHttpResponse raise exceptions.HttpError.FromResponse( RuntimeError: apitools.base.py.exceptions.HttpError: HttpError accessing <https://www.googleapis.com/resumable/upload/storage/v1/b/<bucke-name>/o?alt=json&name=tmp%2F.tempaf83360e-673f-4f9a-b15a-5be45081c335%2F3919075269125806430_9535790f-f57d-430f-9631-f121966e5ca4&uploadType=resumable&upload_id=<id>>: response: <{'content-type': 'text/plain; charset=utf-8', 'x-guploader-uploadid': '<id>', 'content-length': '0', 'date': 'Thu, 10 Jun 2021 14:58:51 GMT', 'server': 'UploadServer', 'status': '503'}>, content <> [while running 'Write to GCS/ParDo(_WriteShardedRecordsFn)-ptransform-50705'] passed through: ==> dist_proc/dax/workflow/worker/fnapi_service.cc:631 |
Simple Quiz app & accumulate data in java & android studio Posted: 14 Jun 2021 08:05 AM PDT We have a simple quiz app. We try to accumulate the scores & the attempts user have in the game with the variables: starValue , attempts. But it refreshes the data every time. In addition, the quiz is set by levels. We have another activity that is responsible for the game levels. When the player manages to answer a certain number of questions he rises a level. How do we define it each time it goes level up ,the questions from the selected query pool are refreshed accordingly. Also, we want that whenever it goes levels up a permanent marking of an image with an arrow on the previous step will appear and it will maintain this state. We tried to add code responsible for it but it did not work. The arrow is deleted from screen to screen. we add here the relevant code this is the MainGameActivity.java file package com.example.aquickthinkinggame; import android.app.Dialog; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.CountDownTimer; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import java.util.Collections; import java.util.List; public class MainGameActivity extends AppCompatActivity { Button buttonA, buttonB, buttonC, buttonD, buttonNext, level1Btn, level2Btn, level3Btn, level4Btn, level5Btn; TextView questionText, timeText, resultText, starText; TriviaDbHelper triviaQuizHelper; TriviaQuestion currentQuestion; List<TriviaQuestion> list; int qid = 0; boolean rightOrWrong = false; CountDownTimer countDownTimer; int level = 1; int timeValue = 20; int attempts = 5; int starValue = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.game_q); //Initializing variables questionText = findViewById(R.id.question); buttonA = findViewById(R.id.ans1); buttonB = findViewById(R.id.ans2); buttonC = findViewById(R.id.ans3); buttonD = findViewById(R.id.ans4); level1Btn = findViewById(R.id.level1Btn); level2Btn = findViewById(R.id.level2Btn); level3Btn = findViewById(R.id.level3Btn); level4Btn = findViewById(R.id.level4Btn); level5Btn = findViewById(R.id.level5Btn); // triviaQuizText = (TextView) findViewById(R.id.triviaQuizText); timeText = findViewById(R.id.Timer); resultText = findViewById(R.id.resultText); starText = findViewById(R.id.score); // level2Btn.setEnabled(false); // level3Btn.setEnabled(false); // level4Btn.setEnabled(false); // level5Btn.setEnabled(false); //Our database helper cla`ss triviaQuizHelper = new TriviaDbHelper(this); //Make db writable triviaQuizHelper.getWritableDatabase(); //It will check if the ques,options are already added in table or not //If they are not added then the getAllOfTheQuestions() will return a list of size zero if (triviaQuizHelper.getAllOfTheQuestions().size() == 0) { //If not added then add the ques,options in table triviaQuizHelper.allQuestion(); } //This will return us a list of data type TriviaQuestion list = triviaQuizHelper.getAllOfTheQuestions(); //Now we gonna shuffle the elements of the list so that we will get questions randomly Collections.shuffle(list); //currentQuestion will hold the que, 4 option and ans for particular id currentQuestion = list.get(qid); //countDownTimer countDownTimer = new CountDownTimer(21000, 1000) { public void onTick(long millisUntilFinished) { //here you can have your logic to set text to timeText timeText.setText('[' + (String.valueOf(timeValue)) + ']'); //With each iteration decrement the time by 1 sec timeValue--; //This means the user is out of time so onFinished will called after this iteration if (timeValue == 0) { //Since user is out of time setText as time up resultText.setText(getString(R.string.message_timeup)); //Since user is out of time he won't be able to click any buttons //therefore we will disable all four options buttons using this method disableButton(); } } //Now user is out of time public void onFinish() { //We will navigate him to the time up activity using below method timeUp(); } }.start(); //This method will set the que and four options updateQueAndOptions(); } public void updateQueAndOptions() { //This method will setText for que and options questionText.setText(currentQuestion.getQuestion()); buttonA.setText(currentQuestion.getOptA()); buttonB.setText(currentQuestion.getOptB()); buttonC.setText(currentQuestion.getOptC()); buttonD.setText(currentQuestion.getOptD()); timeValue = 20; //Now since the user has ans correct just reset timer back for another que- by cancel and start onStop(); onRestart(); // if (rightOrWrong == true) { // starValue++; // starText.setText(String.valueOf(starValue)); starText.setText(String.valueOf(starValue)); starValue++; ////the levels part make the app crash if (level == 1) level1Btn.setBackgroundResource(R.drawable.arrow); if (level == 1 && starValue >= 15) { level++; Toast.makeText(this, "You are in level 2", Toast.LENGTH_LONG).show(); level1Btn.setEnabled(false); level2Btn.setEnabled(true); level3Btn.setEnabled(false); level4Btn.setEnabled(false); level5Btn.setEnabled(false); starValue = 0; if (level == 2) { level2Btn.setBackgroundResource(R.drawable.arrow); level1Btn.setBackgroundResource(R.drawable.x); } levelsStatus(); } else if (level == 2 && starValue >= 20) { level++; Toast.makeText(this, "You are in level 3", Toast.LENGTH_LONG).show(); level1Btn.setEnabled(false); level2Btn.setEnabled(false); level3Btn.setEnabled(true); level4Btn.setEnabled(false); level5Btn.setEnabled(false); starValue = 0; if (level == 3) { level3Btn.setBackgroundResource(R.drawable.arrow); level2Btn.setBackgroundResource(R.drawable.x); level1Btn.setBackgroundResource(R.drawable.x); } levelsStatus(); } else if (level == 3 && starValue >= 25) { level++; Toast.makeText(this, "You are in level 4", Toast.LENGTH_LONG).show(); level1Btn.setEnabled(false); level2Btn.setEnabled(false); level3Btn.setEnabled(false); level4Btn.setEnabled(true); level5Btn.setEnabled(false); starValue = 0; if (level == 4) { level4Btn.setBackgroundResource(R.drawable.arrow); level3Btn.setBackgroundResource(R.drawable.x); level2Btn.setBackgroundResource(R.drawable.x); level1Btn.setBackgroundResource(R.drawable.x); } levelsStatus(); } else if (level == 4 && starValue >= 27) { level++; Toast.makeText(this, "You are in level 5", Toast.LENGTH_LONG).show(); level1Btn.setEnabled(false); level2Btn.setEnabled(false); level3Btn.setEnabled(false); level4Btn.setEnabled(false); level5Btn.setEnabled(true); starValue = 0; if (level == 5) { level5Btn.setBackgroundResource(R.drawable.arrow); level4Btn.setBackgroundResource(R.drawable.x); level3Btn.setBackgroundResource(R.drawable.x); level2Btn.setBackgroundResource(R.drawable.x); level1Btn.setBackgroundResource(R.drawable.x); } levelsStatus(); } else if (level == 5 && starValue == 30) { gameWon(); starValue = 0; } } //Now since user has ans correct increment the coinvalue /// starValue++; public void wrongAnswer() { //it will increment the question number qid++; //get the que and 4 option and store in the currentQuestion currentQuestion = list.get(qid); //Now this method will set the new que and 4 options updateQueAndOptions(); //reset the color of buttons back to white resetColor(); //Enable button - remember we had disable them when user ans was correct in there particular button methods // enableButton(); onPause(); Intent intent = new Intent(this, MainGameActivity.class); // // intent.putExtra("starValue", starValue); startActivity(intent); /// receiver // Intent mIntent = getIntent(); // int starValue = mIntent.getIntExtra("starValue", 0); finish(); } //Onclick listener for first button public void buttonA(View view) { if (qid < 30) { if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) { buttonB.setBackgroundColor(Color.GREEN); disableButton(); correctDialog(); // rightOrWrong = true; //set the value of coin text starValue++; starText.setText(String.valueOf(starValue)); //set the value of coin text } else { disableButton(); attempts--; Toast.makeText(this, "You have" + attempts + "attempts left", Toast.LENGTH_LONG).show(); wrongAnswer(); //set the value of coin text if (attempts == 0) { gameLostPlayAgain(); } } } else { updateQueAndOptions(); } } //Onclick listener for sec button public void buttonB(View view) { if (qid < 30) { if (currentQuestion.getOptB().equals(currentQuestion.getAnswer())) { buttonB.setBackgroundColor(Color.GREEN); disableButton(); correctDialog(); // rightOrWrong = true; //set the value of coin text starValue++; starText.setText(String.valueOf(starValue)); //set the value of coin text } else { disableButton(); attempts--; Toast.makeText(this, "You have" + attempts + "attempts left" , Toast.LENGTH_LONG).show(); wrongAnswer(); //set the value of coin text if (attempts == 0) { gameLostPlayAgain(); } } } else { updateQueAndOptions(); } } //Onclick listener for third button public void buttonC(View view) { if (qid < 30) { if (currentQuestion.getOptC().equals(currentQuestion.getAnswer())) { buttonB.setBackgroundColor(Color.GREEN); countDownTimer.cancel(); disableButton(); correctDialog(); // rightOrWrong = true; starValue++; starText.setText(String.valueOf(starValue)); //set the value of coin text //set the value of coin text //set the value of coin text } else { disableButton(); attempts--; Toast.makeText(this, "You have" + attempts + "attempts left", Toast.LENGTH_LONG).show(); wrongAnswer(); //set the value of coin text if (attempts == 0) { gameLostPlayAgain(); } } } else { updateQueAndOptions(); } } //Onclick listener for fourth button public void buttonD(View view) { if (qid < 30) { if (currentQuestion.getOptD().equals(currentQuestion.getAnswer())) { buttonB.setBackgroundColor(Color.GREEN); disableButton(); correctDialog(); onStop(); //set the value of coin text // rightOrWrong = true; //set the value of coin text starValue++; starText.setText(String.valueOf(starValue)); //set the value of coin text } else { disableButton(); attempts--; Toast.makeText(this, "You have" + attempts + "attempts left", Toast.LENGTH_LONG).show(); wrongAnswer(); //set the value of coin text if (attempts == 0) { gameLostPlayAgain(); } } } else { updateQueAndOptions(); } } //This method will navigate from current activity to GameWon public void gameWon() { Intent intent = new Intent(this, GameWon.class); startActivity(intent); finish(); } //This method is called when user ans is wrong //this method will navigate user to the activity PlayAgain public void gameLostPlayAgain() { Intent intent = new Intent(this, PlayAgain.class); startActivity(intent); finish(); } //This method is called when time is up //this method will navigate user to the activity Time_Up public void timeUp() { Intent intent = new Intent(this, Time_Up.class); startActivity(intent); finish(); } //If user press home button and come in the game from memory then this //method will continue the timer from the previous time it left @Override protected void onRestart() { super.onRestart(); countDownTimer.start(); } //When activity is destroyed then this will cancel the timer @Override protected void onStop() { super.onStop(); countDownTimer.cancel(); } //This will pause the time @Override protected void onPause() { super.onPause(); countDownTimer.cancel(); } //On BackPressed @Override public void onBackPressed() { Intent intent = new Intent(this, MainMenu.class); startActivity(intent); finish(); } //This dialog is show to the user after he ans correct public void correctDialog() { final Dialog dialogCorrect = new Dialog(MainGameActivity.this); dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE); if (dialogCorrect.getWindow() != null) { ColorDrawable colorDrawable = new ColorDrawable(Color.WHITE); dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable); } dialogCorrect.setContentView(R.layout.dialog_correct); dialogCorrect.setCancelable(false); dialogCorrect.show(); //Since the dialog is show to user just pause the timer in background onPause(); buttonNext = (Button) findViewById(R.id.btnNextQuestion); } ///nextButton pass 2 next que /dismiss dialog public void NextBtn(View view) { final Dialog dialogCorrect = new Dialog(MainGameActivity.this); //This will dismiss the dialog dialogCorrect.dismiss(); //it will increment the question number qid++; //get the que and 4 option and store in the currentQuestion currentQuestion = list.get(qid); //Now this method will set the new que and 4 options updateQueAndOptions(); //reset the color of buttons back to white resetColor(); //Enable button - remember we had disable them when user ans was correct in there particular button methods enableButton(); ///sender Intent intent = new Intent(this, MainGameActivity.class); // // intent.putExtra("starValue", starValue); startActivity(intent); /// receiver // Intent mIntent = getIntent(); // int starValue = mIntent.getIntExtra("starValue", 0); finish(); } //This method will make button color white again since our one button color was turned green public void resetColor() { buttonA.setBackgroundColor(Color.WHITE); buttonB.setBackgroundColor(Color.WHITE); buttonC.setBackgroundColor(Color.WHITE); buttonD.setBackgroundColor(Color.WHITE); } //This method will disable all the option button public void disableButton() { buttonA.setEnabled(false); buttonB.setEnabled(false); buttonC.setEnabled(false); buttonD.setEnabled(false); } //This method will all enable the option buttons public void enableButton() { buttonA.setEnabled(true); buttonB.setEnabled(true); buttonC.setEnabled(true); buttonD.setEnabled(true); } public void levelsStatus() { Intent intent = new Intent(this, Levels.class); startActivity(intent); finish(); } } here the Levels.java & levels.xml code enter code here package com.example.aquickthinkinggame; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Levels extends BaseActivity { Button level1Btn, level2Btn, level3Btn, level4Btn, level5Btn; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.levels); level1Btn = findViewById(R.id.level1Btn); level2Btn = findViewById(R.id.level2Btn); level3Btn = findViewById(R.id.level3Btn); level4Btn = findViewById(R.id.level4Btn); level5Btn = findViewById(R.id.level5Btn); level1Btn.setEnabled(true); level2Btn.setEnabled(true); level3Btn.setEnabled(true); level4Btn.setEnabled(false); level5Btn.setEnabled(false); } public void btnLevels1(View v) { Intent intent = new Intent(this, MainGameActivity.class); startActivity(intent); finish(); } public void btnLevels2(View v) { Intent intent = new Intent(this, MainGameActivity.class); startActivity(intent); finish(); } public void btnLevels3(View v) { Intent intent = new Intent(this, MainGameActivity.class); startActivity(intent); finish(); } public void btnLevels4(View v) { Intent intent = new Intent(this, MainGameActivity.class); startActivity(intent); finish(); } public void btnLevels5(View v) { Intent intent = new Intent(this, MainGameActivity.class); startActivity(intent); finish(); } } enter code here <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/bu" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/b_steps"> <Button android:id="@+id/level1Btn" android:layout_width="100dp" android:layout_height="100dp" android:layout_marginStart="209dp" android:layout_marginLeft="209dp" android:layout_marginTop="72dp" android:layout_marginEnd="152dp" android:layout_marginRight="152dp" android:background="@color/transparent3" android:onClick="btnLevels1" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.68" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/level2Btn" android:layout_width="100dp" android:layout_height="100dp" android:layout_marginStart="124dp" android:layout_marginLeft="124dp" android:layout_marginTop="196dp" android:layout_marginEnd="237dp" android:layout_marginRight="237dp" android:background="@color/transparent3" android:onClick="btnLevels2" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.56" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/level3Btn" android:layout_width="100dp" android:layout_height="100dp" android:layout_marginStart="209dp" android:layout_marginLeft="209dp" android:layout_marginEnd="152dp" android:layout_marginRight="152dp" android:background="@color/transparent3" android:onClick="btnLevels3" android:padding="@dimen/cardview_default_radius" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/level4Btn" android:layout_width="100dp" android:layout_height="100dp" android:layout_marginStart="125dp" android:layout_marginLeft="125dp" android:layout_marginTop="140dp" android:layout_marginEnd="237dp" android:layout_marginRight="237dp" android:background="@color/transparent3" android:onClick="btnLevels4" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.549" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/level2Btn" /> <Button android:id="@+id/level5Btn" android:layout_width="100dp" android:layout_height="100dp" android:layout_marginStart="210dp" android:layout_marginLeft="210dp" android:layout_marginTop="140dp" android:layout_marginEnd="152dp" android:layout_marginRight="152dp" android:background="@color/transparent3" android:onClick="btnLevels5" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.666" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/level3Btn" /> </androidx.constraintlayout.widget.ConstraintLayout> we will be happy to get help here! Thanks:) |
I have a list 'l' Posted: 14 Jun 2021 08:05 AM PDT l=[(A,B),(A,C),(E,F)] Where A is equal to B and A is equal to C and E is equal to F. I need to group the elements equal to each other in the same tuple. result=[(A,B,C),(E,F)] How can i do that? |
Replace form data for login in spring security Posted: 14 Jun 2021 08:05 AM PDT I'm developing a web app that uses ldap authentication and I have this problem: basically I have to replace user credential from a classical login page with data coming via DTOs.I have a RestController that recives data via Post: @RestController @RequestMapping("/authentication") public class AuthenticationController { @RequestMapping("/ldapAuthentication") public boolean authenticate(@RequestBody UserDto userToAuthenticate) throws JsonProcessingException { // to do method return true; } } userToAuthenticate contains username and password and I should pass this data to my SecurityConfig class (that extends WebSecurityConfigurerAdapter)and then, in the configure method, I know I should somehow replace the formlogin, loginpage part... @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests().antMatchers("/login", "/authentication/**").permitAll().anyRequest() .authenticated().and().formLogin().loginPage("/login").permitAll().and().logout() .invalidateHttpSession(true).clearAuthentication(true) .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl(LOGIN).permitAll(); } The other elements of this class work fine because I tested it standalone with the standard loginpage. Please let me know if you need further info and code snippets. Any help will be appriciated. |
Unable to deep clone Posted: 14 Jun 2021 08:05 AM PDT I want to make a copy of an object. Following that, I plan to modify values within the copy but these modifications should not affect the original object. Thus I want to make a clone and presently using lodash's deepClone. But it keeps throwing the following error: Error!Object(...) is not a function There is no function within my object. It is just in following structure. They are just key values where values are either strings or booleans. const myOriginalObject { "mainKey" : { isMobile: true, data: { id: '', header: '', flag: '', desc1: '', desc2: '', logo: { src: '', alt: '', }, img: { src: '', alt: '', }, } } } Just to test it out created a random object as follows. And even this throws same error. const myOriginalObject = { b: '', c: '' } This is the implementation to deep copy. myOriginalObject can be either one of above objects. import { cloneDeep } from 'lodash/cloneDeep'; const myClone = cloneDeep(myOriginalObject); What am I doing wrong? Pls advice. Thanks. |
How to connect to SQL Server 2017 using Hibernate and Windows Authentication? Posted: 14 Jun 2021 08:05 AM PDT Full MCVE is at the bottom of this post. I am trying to run a very basic Hibernate example as I work through a tutorial. However, I am receiving the following error: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] : Exception in thread "main" java.lang.ExceptionInInitializerError at hibernateTutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:50) at hibernateTutorial.util.HibernateUtil.getSessionFactory(HibernateUtil.java:30) at hibernateTutorial.main.HibernateMain.main(HibernateMain.java:21) Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:176) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:127) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:86) at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:479) at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:85) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:709) at hibernateTutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:47) ... 2 more Caused by: org.vibur.dbcp.ViburDBCPException: java.lang.NullPointerException at org.vibur.dbcp.ViburDBCPDataSource.start(ViburDBCPDataSource.java:233) at org.hibernate.vibur.internal.ViburDBCPConnectionProvider.configure(ViburDBCPConnectionProvider.java:57) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:107) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:246) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ... 15 more Caused by: java.lang.NullPointerException at java.util.Hashtable.put(Hashtable.java:460) at java.util.Properties.setProperty(Properties.java:166) at org.vibur.dbcp.pool.Connector$Builder$Driver.<init>(Connector.java:66) at org.vibur.dbcp.pool.Connector$Builder$Driver.<init>(Connector.java:56) at org.vibur.dbcp.pool.Connector$Builder.buildConnector(Connector.java:48) at org.vibur.dbcp.ViburDBCPDataSource.doStart(ViburDBCPDataSource.java:248) at org.vibur.dbcp.ViburDBCPDataSource.start(ViburDBCPDataSource.java:226) ... 24 more My database is on a Microsoft SQL Server 2017 instance that uses Windows Authentication. I have added both the MSSQL JDBC (v6.4.0) and sqljdbc_auth.dll (required for Windows Authentication) to my classpath. From what I can tell in my research into this ambiguous error message, it could have many different causes, but ultimately boils down to just not being able to connect to the database somehow. Most of the other Q&A I've found seems to be specific to other databases or SQL Server that doesn't use Windows Authentication. I have copied the JDBC URL directly from my datasource config in IntelliJ so I know that it is correct and works properly in the IDE. What else is required to properly configure Hibernate to connect to SQL Server? HibernateMain.java : package hibernateTutorial.main; import hibernateTutorial.model.Employee; import hibernateTutorial.util.HibernateUtil; import org.hibernate.Session; import java.time.LocalDateTime; public class HibernateMain { public static void main(String[] args) { Employee emp = new Employee(); emp.setName("Nathan"); emp.setRole("CEO"); emp.setInsertTime(LocalDateTime.now()); // ********************************************************************************************** // Get Session // ********************************************************************************************** Session session = HibernateUtil.getSessionFactory().getCurrentSession(); // ********************************************************************************************** // Start transaction // ********************************************************************************************** session.beginTransaction(); // ********************************************************************************************** // Save the model object // ********************************************************************************************** session.save(emp); // ********************************************************************************************** // Commit the transaction // ********************************************************************************************** session.getTransaction().commit(); System.out.println("Employee ID: " + emp.getId()); // ********************************************************************************************** // Terminate the session factory or the program won't end // ********************************************************************************************** HibernateUtil.getSessionFactory().close(); } } HibernateUtil.java : package hibernateTutorial.util; import hibernateTutorial.model.Employee1; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import java.util.Properties; public class HibernateUtil { // ********************************************************************************************** // XML-based configuration // ********************************************************************************************** private static SessionFactory sessionFactory; // ********************************************************************************************** // Annotation-based configuration // ********************************************************************************************** private static SessionFactory sessionAnnotationFactory; // ********************************************************************************************** // Property-based configuration // ********************************************************************************************** private static SessionFactory sessionJavaConfigFactory; public static SessionFactory getSessionFactory() { if (sessionFactory == null) sessionFactory = buildSessionFactory(); return sessionFactory; } private static SessionFactory buildSessionFactory() { try { // ********************************************************************************************** // Create the SessionFactory from hibernate.cfg.xml // ********************************************************************************************** Configuration configuration = new Configuration(); configuration.configure("hibernate.cfg.xml"); System.out.println("Hibernate configuration loaded"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); System.out.println("Hibernate serviceRegistry created"); return configuration.buildSessionFactory(serviceRegistry); } catch (Throwable e) { System.err.println("Initial SessionFactory creation failed. " + e); throw new ExceptionInInitializerError(e); } } public static SessionFactory getSessionAnnotationFactory() { if (sessionAnnotationFactory == null) sessionAnnotationFactory = buildSessionAnnotationFactory(); return sessionAnnotationFactory; } private static SessionFactory buildSessionAnnotationFactory() { try { // ********************************************************************************************** // Create the SessionFactory from hibernate-annotation.cfg.xml // ********************************************************************************************** Configuration configuration = new Configuration(); configuration.configure("hibernate-annotation.cfg.xml"); System.out.println("Hibernate Annotation configuration loaded"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); System.out.println("Hibernate Annotation serviceRegistry created"); return configuration.buildSessionFactory(serviceRegistry); } catch (Throwable e) { System.err.println("Initial SessionFactory creationg failed." + e); throw new ExceptionInInitializerError(e); } } public static SessionFactory getSessionJavaConfigFactory() { if (sessionJavaConfigFactory == null) sessionJavaConfigFactory = buildSessionJavaConfigFactory(); return sessionJavaConfigFactory; } private static SessionFactory buildSessionJavaConfigFactory() { try { Configuration configuration = new Configuration(); //Create Properties, can be read from property files too Properties props = new Properties(); props.put("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver"); props.put("hibernate.connection.url", "jdbc:sqlserver://FADBOKT2493V\\KRAFTLAKEODB:51678;database=Dev_RepAssistDB;integratedSecurity=true"); props.put("hibernate.current_session_context_class", "thread"); configuration.setProperties(props); //we can set mapping file or class with annotation //addClass(Employee1.class) will look for resource // com/journaldev/hibernate/model/Employee1.hbm.xml (not good) configuration.addAnnotatedClass(Employee1.class); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); System.out.println("Hibernate Java Config serviceRegistry created"); return configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } } Employee.java : package hibernateTutorial.model; import java.time.LocalDateTime; public class Employee { private int id; private String name; private String role; private LocalDateTime insertTime; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public LocalDateTime getInsertTime() { return insertTime; } public void setInsertTime(LocalDateTime insertTime) { this.insertTime = insertTime; } } Employee1.java : package hibernateTutorial.model; import javax.persistence.*; import java.time.LocalDateTime; @Entity @Table(name = "tmp_employees", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})}) public class Employee1 { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false, unique = true, length = 11) private int id; @Column(name = "name", length = 20, nullable = true) private String name; @Column(name = "role", length = 20, nullable = true) private String role; @Column(name = "insert_time", nullable = true) private LocalDateTime insertTime; } employee.hbm.xml : <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "https://hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="hibernateTutorial.model.Employee" table="tmp_employees"> <id name="id" type="int"> <column name="id"/> <generator class="increment"/> </id> <property name="name" type="java.lang.String"> <column name="name"/> </property> <property name="role" type="java.lang.String"> <column name="role"/> </property> <property name="insertTime" type="java.time.LocalDateTime"> <column name="insert_time"/> </property> </class> </hibernate-mapping> hibernate.cfg.xml : <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "https://hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection properties - Driver, URL, user, password --> <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property> <property name="hibernate.connection.url">jdbc:sqlserver://servername:port; database=test_db;integratedSecurity=true </property> <!-- Connection Pool Size --> <property name="hibernate.connection.pool_size">5</property> <!-- org.hibernate.HibernateException: No CurrentSessionContext configured! --> <property name="hibernate.current_session_context_class">thread</property> <!-- Outputs the SQL queries, should be disabled in Production --> <property name="hibernate.show_sql">true</property> <!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc Hibernate 4 automatically figure out Dialect from Database Connection Metadata --> <property name="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</property> <!-- mapping file, we can use Bean annotations too --> <mapping resource="hibernateTutorial/employee.hbm.xml"/> </session-factory> </hibernate-configuration> hibernate-annotation.cfg.xml : <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "https://hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection properties - Driver, URL, user, password --> <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property> <property name="hibernate.connection.url">jdbc:sqlserver:servername:port;database=test_db;integratedSecurity=true</property> <!-- Connection Pool Size --> <property name="hibernate.connection.pool_size">5</property> <!-- org.hibernate.HibernateException: No CurrentSessionContext configured! --> <property name="hibernate.current_session_context_class">thread</property> <!-- Outputs the SQL queries, should be disabled in Production --> <property name="hibernate.show_sql">true</property> <!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc Hibernate 4 automatically figure out Dialect from Database Connection Metadata --> <property name="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</property> <!-- mapping with model class containing annotations --> <mapping class="hibernateTutorial.model.Employee1"/> </session-factory> </hibernate-configuration> |
C# Picker in Xmarin Posted: 14 Jun 2021 08:05 AM PDT I have written custom picker which list was built from class inherited from Dictionary<string,string>; that is dataStore in code bellow. That has worked ok, but then I needed more data so instead of Dictionary<string,string> I am using Dictionary<int, myObject>. MyObject contains fields like id, name etc. I have managed to properly fill the picker, but I have a problem with SetItemSelection function. Previously I have used as follows. public void SetItemSelection(string value) { string key = ListKeys.Where((string param) => param == value).FirstOrDefault(); if (( key != null) && (key != "") && (dataStore.ContainsKey(key))) selectedItem = dataStore[key]; } ListKeys is actually this function: private List<string> GetListKey() { List<string> keys = new List<string>(); foreach (KeyValuePair<int, SubjectDTO> kvp in dataStore) { keys.Add(kvp.Value.id); } return keys; } My question is. How to reprogram this so I can set picker selection? |
Vue Router cancelling route Posted: 14 Jun 2021 08:05 AM PDT When I click on a link in my Vue app, it returns to the initial route where it is coming from. I do not seem to have found this error/bug anywhere and currently do not know what to do <router-link to="/user/info" > Information </router-link> <router-link to="/user/loan" > Loans </router-link> <router-link to="/user/documents" > Documents </router-link> If I click on Loans, it goes back to Information, if I click Documents, it goes back to Information |
Divide tree to O(log(n)) groups in O(log(n)) phases - distribute algorithm Posted: 14 Jun 2021 08:05 AM PDT There is a syncronic network in a shape of tree with n computers. Every computer has a unique id. The links between the computers is with no direction. There is at least 1 computer with Log(n) neigbours. We need to find a distribute algorithm that's run in O(log(n)) phases and distribute the computers to O(log(n)) distinctive groups (Li,Li+1,…Lt ) between every 2 groups, Li,Li+1 there is at least 1 link between the 2 groups. The rank of of every computer inside Li(its neighbors at Li) is not bigger than 10. |
Pass a file opened in a function to another function to analyze it in python Posted: 14 Jun 2021 08:06 AM PDT I'm using a function to let my user open a file by clicking a button. def open(): global img file = filedialog.askopenfilename(filetypes =(("Text File", "*.txt"),("All Files","*.*")), title = "Select") txt = [] with open(file, "r", encoding='utf-8') as f: [...] outputData = pd.DataFrame(txt) return txt After that by pressing another button should also start some analysis using pandas, but How can I use the dataframe I create in this below function? def analyze(): total = len(outputData) This is the error I'm getting: "Error: NameError: name 'outputData' is not defined" After someone click the analysis button I'd like also to display the result in the "total_label" so that it can be seen by my user. sel_btn = Button(frame, command=open) an_btn = Button(frame, command=analyze) total_label = Label(frame, textvariable='total') sel_btn.pack() an_btn.pack() total_label.pack() Thank you! |
Why does a T-SQL CROSS APPLY sometimes behave like a LEFT JOIN Posted: 14 Jun 2021 08:05 AM PDT Most of the documentation I have read suggests that a CROSS APPLY acts in a similar manner to an INNER JOIN whereby a row is only included in the output if there are matching rows in both source tables. However, this doesn't always seem to be the case, for example if you run the following SQL query the results will contain 3 rows where one of them includes a number of NULLs due to there being no row in the right-hand table: CREATE TABLE #Order ( Id int PRIMARY KEY ) CREATE TABLE #OrderItem ( OrderId int NOT NULL, Price decimal(18, 2) NOT NULL ) INSERT INTO #Order VALUES(1), (2), (3) INSERT INTO #OrderItem VALUES(1, 10), (1, 20), (3,100) SELECT * FROM #Order o CROSS APPLY ( SELECT SUM(Price) AS TotalPrice, COUNT(*) AS Items, MIN(Price) AS MinPrice FROM #OrderItem WHERE OrderId = o.Id ) t DROP TABLE #Order DROP TABLE #OrderItem Does anyone know why that is? |
change content between tags HTML Posted: 14 Jun 2021 08:05 AM PDT I have an xml file as follows <firewall> <custom_list max_entry_num="50"> <id>1</id> <desc>first</desc> <rule>!!!!!</rule> </custom_list> <custom_list max_entry_num="50"> <id>2</id> <desc>seconde</desc> <rule> !!!!!! </rule> </custom_list> </firewall> I want to change the content between the tags, for this I use the following command: xmlstartlet ed -u "/firewall/custom_list/rule' -v "My First Text" old.xml >new.xml but this text is in the two tags, When id =1 and id = 2. <custom_list max_entry_num="50"> <id>1</id> <desc>first</desc> <rule>MY FIRST TEXT</rule> </custom_list> <custom_list max_entry_num="50"> <id>2</id> <desc>second</desc> <rule>MY FIRST TEXT</rule> I want to: - When
id equals 1 I put "MY FIRST TEXT" - when
id equals 2 I put "MY SECOND TEXT" How can I do this in bash? |
Azure DevOps Deploy Release step on Failure Posted: 14 Jun 2021 08:05 AM PDT Our structure for a release in azure devops is to deploy our app to our DEV environment. Kick off my Selenium (Visual Studio) tests against that environment. If passes, moves to our TEST environment. If fails/hard stop. We want to add new piece/functionality, starts same as above, Except instead of hard stop. 5) if default step fails, continue to next step. 6) New detail testing starts (turns on screen recorder) The new detailed step has 'Agent Job' settings/parameters, I have the section "Run this job", set to "Only when previous job has failed". My results have been, that if the previous/default/basic testing passed, the detailed step is skipped. As expected. But if the previous step fails....the following new detailed step does not kick off. Is it possible because the step is set up that if it fails hard stop and does not even evaluate the next step? Or is it because the previous step says 'partially succeeded'. is this basically seen not as a failure? |
Formic always shows that form is invalid Posted: 14 Jun 2021 08:05 AM PDT Here I used formic with yup . Even I defied some schema for validation and even the values in the inputs full fill that rules formic in combination with YUP always says that the form is invalid even the form values are valid. I am a beginner. So I would be much thankful to you if you could provide some in-depth answer. Thank you import React, { useEffect, useState } from 'react' import './index.css' import { Formik, Form, Field, ErrorMessage } from "formik"; import * as Yup from "yup"; import axios from 'axios' const Inedex = () => { const [projects, setProjects] = useState([]) const [memebers, setMemebers] = useState([]) const [formData, setFormData] = useState({ projectId: "", title: "", actualOutcomes: "", expectedOutcomes: "" }) const setData = (key, value) => { setFormData({ ...formData, [key]: value }) console.log(formData, { key, value }) } useEffect(() => { getProjects(); }, []) const getProjects = () => { axios.get("http://localhost:5000/project/all/names").then(res => { console.log(res.data) setProjects([...res.data]) }) } const handleProjectChange = (value) => { setData("projectId", value); axios.post("http://localhost:5000/project/roles", { "projectId": value, "role": "DEV" }).then(res => { console.log(res.data) setMemebers(res.data) }) } const submitForm = (values) => { console.log(values); }; const initialValues = { project:"", developer:"", email: "", title: "", project: "", developer: "", title: "", actualOutcomes: "", expectedOutcomes: "" }; const DynamicProjectOptions = () => { return ( projects.map(project => { return ( <option value={project.id} key={projects.name} >{project.name}</option> ) }) ) } const DynamicMembers = () => { return ( memebers.map(memeber => { return ( <option value={memeber.id} key={memeber.name} >{memeber.name}</option> ) }) ) } const signInSchema = Yup.object().shape({ project: Yup.string().min(1, 'Too Short!').required("Project is required"), developer: Yup.string().min(1, 'Too Short!').required("Developer is required"), title: Yup.string().min(5, 'Too Short!').required("Title is required"), actualOutcomes: Yup.string().min(5, 'Too Short!').required("Actual outcomes is required"), expectedOutcomes: Yup.string().min(5, 'Too Short!').required("Expected outcomes is required"), }); return ( <Formik initialValues={initialValues} validationSchema={signInSchema} onSubmit={(values) => alert(values)} > {({ errors, touched, isValid, dirty }) => { return (<Form> <div className="container"> <h2>Report a bug</h2> {/* Project */} {isValid} <div className="form-row"> <label htmlFor="project">Project</label> <Field name="project" component="select" id="project" className={(errors.email && touched.email ? "is-invalid" : null) + " form-control "} onChange={e => { handleProjectChange(e.target.value) }} value={formData.projectId} > <DynamicProjectOptions /> </Field> {JSON.stringify(formData.selectedProject)} <ErrorMessage name="project" component="span" className="invalid-feedback" /> </div> {/* Developer */} <div className="form-row"> <label htmlFor="developer">Developer</label> <Field name="developer" component="select" id="developer" className={(errors.email && touched.email ? "is-invalid" : null) + " form-control "} > <DynamicMembers /> </Field> <ErrorMessage name="developer" component="span" className="invalid-feedback" /> </div> <div className="form-row"> <label htmlFor="title">Title</label> <Field type="text" name="title" id="email" className={(errors.email && touched.email ? "is-invalid" : null) + " form-control "} onChange={(e) => { setData("title", e.target.value) }} value={formData.title} /> <ErrorMessage name="title" component="span" className="invalid-feedback" /> </div> <div className="form-row"> <label htmlFor="email">Actual outcomes</label> <Field type="text" name="actualOutcomes" id="actualOutcomes" className={(errors.email && touched.email ? "is-invalid" : null) + " form-control "} onChange={(e) => { setData("actualOutcomes", e.target.value) }} value={formData.actualOutcomes} /> <ErrorMessage name="actualOutcomes" component="span" className="invalid-feedback" /> </div> <div className="form-row"> <label htmlFor="email">Expected outcomes</label> <Field type="text" name="expectedOutcomes" id="expectedOutcomes" className={(errors.email && touched.email ? "is-invalid" : null) + " form-control "} onChange={(e) => { setData("expectedOutcomes", e.target.value) }} value={formData.expectedOutcomes} /> <ErrorMessage name="expectedOutcomes" component="span" className="invalid-feedback" /> </div> {JSON.stringify({dirty , isValid , touched})} {/* {JSON.stringify(Object.keys(errors))} */} <button type="submit" className={!(dirty && isValid) ? "disabled-btn" : ""} disabled={!(dirty && isValid)} > Sign In </button> </div> </Form> ); }} </Formik> ); }; export default Inedex; |
Share one y axis for four different boxplots Posted: 14 Jun 2021 08:05 AM PDT I work with the iris dataset, the aim is to get 4 boxplots next to each other and make them all share an y-axis that goes from 0 to 8 par(mfrow=c(1,4)) boxplot(iris$Sepal.Length, width = 3) boxplot(iris$Sepal.Width, width = 3) boxplot(iris$Petal.Length, width = 3) boxplot(iris$Petal.Width, width = 3) I have the 4 plots next to each other now but they all have their own y-axis, suited to their own min and max. How can i make them share a y-axis? I also want to have a x-axis where I can label them with "Sepal.Length", "Sepal.Width" and so on. Solutions without the ggplot if possible, thanks. |
Angular in Kubernetes failing to pull image Posted: 14 Jun 2021 08:05 AM PDT I created an image and pushed to dockerHub, from an angular project. I can see that if I will go to localhost:80 it will open the portal. This are the steps: ng build docker build -t tiberiu1234/template:v1 . docker run -rm -d -p 80:80 tiberiu1234/template:v1 Now I tried to do the same thing but in kubernetes. I created deployment and service and trigger it using the same image: apiVersion: apps/v1 kind: Deployment metadata: name: portal-deployment labels: app: portal spec: replicas: 3 selector: matchLabels: app: portal template: metadata: labels: app: portal spec: containers: - name: portal image: tiberiu1234/portal:v1 ports: - containerPort: 80 --- apiVersion: v1 kind: Service metadata: name: portal-service spec: selector: app: portal ports: - protocol: TCP port: 80 targetPort: 80 Now If I will go and check I will see: portal-deployment 0/3 3 0 4m1s portal-service ClusterIP 10.2.0.114 <none> 80/TCP 3m56s portal-deployment-67c6d9bb6c-88cvn 0/1 ImagePullBackOff 0 23m portal-deployment-67c6d9bb6c-jrmjz 0/1 ImagePullBackOff 0 23m portal-deployment-67c6d9bb6c-wm65h 0/1 ImagePullBackOff 0 23m Error is: kubectl logs -f portal-deployment-67c6d9bb6c-88cvn Error from server (BadRequest): container "portal" in pod "portal-deployment-67c6d9bb6c-88cvn" is waiting to start: trying and failing to pull image and I don't understand why, can you help me with this? |
How to graph the count of multiple responses on the y-axis with age as the x-axis Posted: 14 Jun 2021 08:06 AM PDT I am having issues trying to graph some data. I have a survey question which asks the individual to select up to 3 answers. I want to graph the age on the x-axis with the answer count on the y-axis. This way I am able to see the answers compared to age and see if there is a correlation. However, I can not wrap my head around this and my graphs are coming out wrong. I first wrangled the data and put it into this dataframe. This is just a snippet as an example. age answer count 1 86 4 3 2 15 12 1 3 36 8 2 4 10 6 1 5 8 3 5 6 63 6 5 7 77 14 3 8 33 19 5 9 64 16 4 10 84 10 4 With it like this I have access to each age that responded with each answer plus the count of responses. So if a single 20 year old responded to this survey with 2 answers then the table would look like this. age answer count 1 20 2 1 2 20 5 1 This issue that comes up is that I don't have a column for all the answers that were left blank so when I go to graph it I end up with a mess. I believe if I were able to add all the missing rows it would work but I'm not sure how to do this. Here is a mock-up of what I mean below age answer count 1 20 1 0 2 20 2 1 1 20 3 0 2 20 4 0 1 20 5 1 Any ideas or thoughts on how to proceed from here? My approach might and is probably entirely wrong so any help in pointing me in the right direction would be a life saver. Thank you for your time |
I would like to highlight the background of a cell based on a text from another column Posted: 14 Jun 2021 08:05 AM PDT as said above, i would like to highlight the background of certain cells from another column based on the text that is on the "example" picture for example : if the text is "Run" it highlights the cell as green open for any other ways to do it will reply to any questions thank you for your time example |
React component with react-router inside an app with react-router Posted: 14 Jun 2021 08:05 AM PDT I am developing a react component with its own react-router-dom to be able to handle paths like /post and /post/123 . I need to package this component as npm module so it can be embedded inside another React app with its own react-router-dom. Hosting app: <Router> <Switch> <Route path="/posts" exact={true}> <Blog /> </Route> </Switch> </Router and in the Blog component: <Router basename="/posts"> <Switch> <Route path="/"> <p>Display all posts</p> </Route> <Route path="/post/:id"> <p>Display details for post with id</p> </Route> </Switch> </Router> When I visit the /posts path I get the Display all posts message. However when I visit /post/123 path I don't see the Display details for post with id message. How can I get the inner router paths work with the outside router? |
typeError: this.form._updateTreeValidity is not a function angular form Posted: 14 Jun 2021 08:05 AM PDT I'm trying to make a crud method with anguler and json-server, almost everything works fine but I have errors that I didn't know at first,When I click on the add data button and my dialog opens I get two errors this.data is null in my dialogComponent typeError: this.form._updateTreeValidity is not a function I have a dialog angular material with an ant in it, then I have a table that also comes angular material to show me the data dialog.html <mat-dialog-content> <form [formGroup]="productForm" (ngSubmit)="onSubmit()"> <div class="from-group"> <label for="name">Nom</label> <input id="name" type="text" formControlName="name" class="form-control"> </div> <div class="from-group"> <label for="price">Prix</label> <input id="price" type="number" formControlName="price" class="form-control"> </div> <div class="from-group"> <label for="comment">Commentaire</label> <input id="comment" type="text" formControlName="comment" class="form-control"> </div> <div class="from-group"> <label for="expiration">date de péremption</label> <input id="expiration" type="date" formControlName="date" class="form-control"> </div> <mat-dialog-actions> <button>Valider</button> </mat-dialog-actions> </form> </mat-dialog-content> dialog.ts export class DialogFormComponent implements OnInit { productForm: any = FormGroup; constructor(private fb: FormBuilder, public dialogRef: MatDialogRef<DialogFormComponent>, @Inject(MAT_DIALOG_DATA) public data:any) { } ngOnInit() { this.initDialogForm(); } initDialogForm() { this.productForm = this.fb.group({ id: [this.data.id], name: [this.data.name , Validators.required], price: [this.data.price , Validators.required], comment: [this.data.comment , Validators.required], date : [this.data.date] }); } onSubmit() { this.dialogRef.close(this.productForm.value); console.log(this.productForm.value); } } produits.html <table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <!-- Name Column --> <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef>Nom</th> <td mat-cell *matCellDef="let element"> {{element.name}} </td> </ng-container> <!-- Price Column --> <ng-container matColumnDef="price"> <th mat-header-cell *matHeaderCellDef>Prix</th> <td mat-cell *matCellDef="let element"> {{element.price}} </td> </ng-container> <!-- Comment Column --> <ng-container matColumnDef="comment"> <th class="text" mat-header-cell *matHeaderCellDef>Commentaire</th> <td class="text2" mat-cell *matCellDef="let element"> {{element.comment}} </td> </ng-container> <!-- Expiration Column --> <ng-container matColumnDef="expiration"> <th mat-header-cell *matHeaderCellDef>date de <br> péremption</th> <td mat-cell *matCellDef="let element"> {{element.expiration}} </td> </ng-container> <!-- Action Column--> <ng-container matColumnDef="actions"> <th mat-header-cell *matHeaderCellDef> Action </th> <td mat-cell *matCellDef="let row"> <button mat-raised-button color="primary" (click)="editFormDialog(row)">Edit</button> <button mat-raised-button color="warn" (click)="delete(row)">Supprimer</button> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> <div class="demo-button-container"> <button mat-raised-button (click)= "openFormDialog()" class="demo-button"> Add data </button> </div> produits.ts export class ProduitsComponent implements OnInit { displayedColumns: string[] = ['name', 'price', 'comment', 'expiration', "actions"]; public dataSource: MatTableDataSource<Produit>; constructor(private produitService: ProduitService, public dialog: MatDialog) { } ngOnInit() { this.getLatestProduct(); } createNewProduct(product: any) { this.produitService.createProduct(product).subscribe((response: Produit) => { let t = this.dataSource.data; t.push(response); this.dataSource.data = t; }); } updateLatestProduct(product: Produit) { this.produitService.updateProduct(product).subscribe(response => { let index = this.dataSource.data.findIndex((value) => {value.id === product.id}); this.dataSource.data.splice(index, 1, response); }); } getLatestProduct() { let resp = this.produitService.getAllProduct(); resp.subscribe(result => { this.dataSource = new MatTableDataSource<Produit>(); this.dataSource.data = result as Produit[]; }); } delete(product: Produit) { this.produitService.deleteProduct(product).subscribe(resp => { this.dataSource.data.filter((value) => { return value.id != product.id; }); }); this.getLatestProduct(); } editFormDialog(row: Produit) { const dialogRef = this.dialog.open(DialogFormComponent, { data: row }); dialogRef.afterClosed().subscribe(result => { this.updateLatestProduct(result); this.getLatestProduct(); }); } openFormDialog() { const dialogRef = this.dialog.open(DialogFormComponent, {}); dialogRef.afterClosed().subscribe(result => { this.createNewProduct(result); }); } } service export class ProduitService { private urlProductApi = environment.urlApi; constructor(private httpClient: HttpClient) { } public createProduct(product: Produit): Observable<Produit> { return this.httpClient.post<Produit>(`${this.urlProductApi}produits`, product); } public updateProduct(product: Produit): Observable<Produit> { return this.httpClient.put<Produit>(`${this.urlProductApi}produits/${product.id}`, product); } public getAllProduct(): Observable<Produit[]> { return this.httpClient.get<Produit[]>(`${this.urlProductApi}produits`); } public deleteProduct(product: Produit) { return this.httpClient.delete(`${this.urlProductApi}produits/${product.id}`); } } |
program unable to write in output file (StreamWrite issue) Posted: 14 Jun 2021 08:05 AM PDT I'm a student and I made a program where I would read data from one file (dimension.txt ), make a calculation out of it, then write the output on another file (result.txt ). The program can read dimension.txt , but couldn't write in the output file result.txt . Thanks to anyone who can help. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace AreaofRectangle { class Program { static void Main(string[] args) { String path = AppDomain.CurrentDomain.BaseDirectory; StreamReader sr = new StreamReader(path + "/dimensions.txt"); StreamWriter sw = new StreamWriter(path + "//result.txt"); Console.WriteLine("Content of the File"); sr.BaseStream.Seek(0, SeekOrigin.Begin); string str = sr.ReadLine(); int rectangleCount = 1; while (str != null) { Console.WriteLine("\n\nRectangle " + rectangleCount); string[] number = str.Split(','); Console.WriteLine(str); string[] s = str.Split(','); int length = Int32.Parse(number[0]); int width = Int32.Parse(number[1]); int area = length * width; Console.WriteLine("Length: " + length); Console.WriteLine("Width: " + width); Console.WriteLine("Area: " + area); str = sr.ReadLine(); rectangleCount++; sw.WriteLine("Length:" + length + " Width:" + width + " Area: " + " " + area); } Console.ReadKey(); sw.Flush(); sw.Close(); sr.Close(); } } } |
Flutter Streambuilder based on returned data from futurebuilder Posted: 14 Jun 2021 08:05 AM PDT I'm trying to build a basic flutter app with a firebase backend. I do one first query on a "users" db to find the userName (and other info), and then I need to show a list of data from another collection based on this first result. So basically I need to create a streambuilder based on the result of a first futureBuilder- I provide a basic example just to avoid misunderstanding. With the first query I retrieve the userinfo. Thanks to this, I find out user's name which is "John". Then I have to search in all the documents which one has "John" in his allowed names field, and populate a listview. So here is the question: how to use a streambuilder based on the result given by a futurebuilder? (I hope I was clear enough) ----- Edit: I hope to not create a huge post, but I need to post the code to give more info: class StrutturaPage extends StatefulWidget { @override _StrutturaPageState createState() => _StrutturaPageState(); } class _StrutturaPageState extends State<StrutturaPage> { bool isLogged; User loggedUser = FirebaseAuth.instance.currentUser; final usersCollection = FirebaseFirestore.instance.collection('users'); final matches = FirebaseFirestore.instance.collection('matches'); Future<InfoUtente> userInfo; String userName; @override void initState() { syncUserInfo(); findName().then((result) { print("result: $result"); setState(() { userName = result; }); }); super.initState(); } void syncUserInfo() async { userInfo = fetchInfoUtente(); } // here I get the user Info in the users collection Future<InfoUtente> fetchInfoUtente() async { final response = await usersCollection .where( 'uid', isEqualTo: loggedUser.uid, ) .get(); return InfoUtente.fromFireStore(response.docs.first); } // Since I'm not able to use the userInfo later, // I use this function which returns directly the string I need (the user's name) Future<String> findName() async { final response = await usersCollection .where( 'uid', isEqualTo: loggedUser.uid, ) .get(); return response.docs.first.data()['nome']; } @override Widget build(BuildContext context) { return Scaffold( body: Container( color: Colors.lightBlue[50], child: Column( children: [ SizedBox( height: 30, ), Padding( padding: const EdgeInsets.symmetric( horizontal: 20, vertical: 10, ), child: Row( children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Ciao', style: TextStyle( color: Colors.brown[900], fontSize: 16, ), ), FutureBuilder( future: userInfo, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) return CircularProgressIndicator(); final userInfo = snapshot.data as InfoUtente; print(userInfo); return userInfo != null ? Text('${userInfo.nome} ${userInfo.cognome}', style: TextStyle( fontSize: 20, color: Colors.brown[900], fontWeight: FontWeight.bold)) : Text( 'User not authenticated', style: TextStyle(fontSize: 20), ); }, ), ], ), ], ), ), // if I print userName here, it shows the correct value, // but the streambuilder here below it does not work StreamBuilder<QuerySnapshot>( stream: matches .where('nome', isEqualTo: userName) // filtro in base al campo sport .snapshots(), builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (snapshot.hasError) { return Text('Something went wrong'); } if (snapshot.connectionState == ConnectionState.waiting) { return Text("Loading"); } return Text(snapshot.data.docs.first['sport']); }, ), //MatchesListPerStruttura(), ], ), ), ); } } |
About Firebase console errors Posted: 14 Jun 2021 08:06 AM PDT When I try to create an Audience in the Firebase console, the following message appears and the creation is not executed. One or more of your fields contain invalid characters. I could not find any information about this message in the official documentation. Do you have any idea why the message is displayed? |
Find all possible combinations of paired elements between two arrays, without repeating any of the elements from either array? Posted: 14 Jun 2021 08:05 AM PDT I'm trying to figure out the logic for a function that will find all possible combinations of the elements between two source arrays, without repeating any of the elements from either array. In other words, the elements in each source array are treated as finite resources. From this, a combination of pairs is built until either source array runs out of elements, then the next combination of pairs, then the next, until all permutations have been accounted for. So for example, get_combinations( [1, 2, 3], ["a", "b", "c"] ); should return [ [1, "a"], [2, "b"], [3, "c"] ], [ [1, "a"], [2, "c"], [3, "b"] ], [ [1, "b"], [2, "a"], [3, "c"] ], [ [1, "b"], [2, "c"], [3, "a"] ], [ [1, "c"], [2, "a"], [3, "b"] ], [ [1, "c"], [2, "b"], [3, "a"] ] ] (formatted for clarity) I will be using this for a PHP based project, but I am primarily looking for an algorithm, not a language-specific implementation. As an example with arrays of inequal sizes, get_combinations( [1, 2, 3, 4] and ["a", "b"] ); would return [ [1, "a"], [2, "b"] ], [ [1, "a"], [3, "b"] ], [ [1, "a"], [4, "b"] ], [ [2, "a"], [1, "b"] ], [ [2, "a"], [3, "b"] ], [ [2, "a"], [4, "b"] ], [ [3, "a"], [1, "b"] ], [ [3, "a"], [2, "b"] ], [ [3, "a"], [4, "b"] ], [ [4, "a"], [1, "b"] ], [ [4, "a"], [2, "b"] ], [ [4, "a"], [3, "b"] ] ] |
Automatically create new row when checkbox is ticked in Google Sheets Posted: 14 Jun 2021 08:05 AM PDT I have a dataset of jobs for a gardening company. status # ID Date Name Frequency ☐ 4 340 09/06/20 Jack Once Off ☐ 1 543 22/05/20 Sarah Weekly ☐ 3 121 01/05/20 Emily Fortnightly ☐ 3 577 11/06/20 Peter Once Off When a booking is complete I want to check the box in the first column which will then create a new row with the following conditions - row is created only for jobs that are "weekly" or "fortnighly". Once off jobs wont create a row when the box is checked
- The date in the new row is a week or a fortnight in the future of the original row depending on its frequency value
- The job # goes up by one from the original row #
- The ID, name and frequency rows remain the same
For example if I ticked the checkbox for the 3rd row it would create a new row like this: ☐ 4 121 15/05/20 Emily Fortnightly Is this possible? Thanks! |
How to export a Crypto key in python? Posted: 14 Jun 2021 08:05 AM PDT I want to encrypt files fore secure storage, but the problem is, I don't know how to store the key to decrypt the files afterwards. Code: from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto import Random import ast random_generator = Random.new().read key = RSA.generate(1024, random_generator) encrypteds = str() for text in open('passwords.log', 'rb').readlines(): publickey = key.publickey() encryptor = PKCS1_OAEP.new(publickey) encrypted = encryptor.encrypt(text) decryptor = PKCS1_OAEP.new(key) decrypted = decryptor.decrypt(ast.literal_eval(str(encrypted))) print(publickey) encrypteds+=str(encrypted)+'--|--' with open('passwords_encrypted.log', 'w') as out: out.write(str(encrypted)) |
function "get_header" doesn't work in certain pages Posted: 14 Jun 2021 08:05 AM PDT I am a beginner coder working on a WordPress website and have come across a critical error: I have created a header.php file and tried using the get_header() function to import the header into all of my pages. In my index.php page, it works perfectly, but in all of my other pages, I get an error message saying "Fatal error: Uncaught Error: Call to undefined function get_header()". For experimental purposes, the code in my "index.php" page is the same as in all of my other ".php" pages. What am I doing wrong? Here is the code for one of my pages "feedback.php": <!DOCTYPE html> <html> <head> <!-- Import Header from header.php --> <?php get_header(); ?> <!-- Basic Responsivness --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width", initial-scale=1.0> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> Home </title> <link href="https://fonts.googleapis.com/css2?family=Notable&display=swap" rel="stylesheet"> <style type="text/css"> h2 { font-family: 'Notable', sans-serif; } </style> </head> <body> <h2> Hello World </h2> </body> </html> |
How to align Hint Text into centre in Text Filed? Posted: 14 Jun 2021 08:05 AM PDT i am trying to add alignment to the hint-text inside Text-field.but it is not working. How to bring it to centre?? How to write text in curved shape??? Container( child: new TextFormField( controller: _pass, textAlign: TextAlign.center, decoration: new InputDecoration.collapsed( hintText: " PASSWORD", ), )), |
No comments:
Post a Comment