text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Why does ruby define variables even if it never executes the variable assignment code? Given the following code:
a = true # let's assign `a` a value
# and let's test if calling `b`, an unassigned variable, throws an error
begin
puts "The value of b is: #{b.inspect}"
rescue NameError => e
puts "Caught an error: #{e}"
end
a || b = true # the assignment should never be executed because `a` is `true`
puts "The value of b is: #{b.inspect}" # will calling `b` still raise an error?
We get the following result:
Caught an error: undefined local variable or method `b' for main:Object
The value of b is: nil
Even though we expected calling b to raise an error the second time, we see that b is now, in fact, nil.
Why is that? Why does b get assigned nil? Since the || never reached the assignment, I would expect b to remain undefined. How can it be defined, but not assigned a value?
A: Some of the docs explain how variables are created; the explanation as I understand it is that's just how the parser works:
The local variable is created when the parser encounters the assignment, not when the assignment occurs:
a = 0 if false # does not assign to a
p local_variables # prints [:a]
p a # prints nil
You can see other examples of this:
b = true if false # b is nil
"test" || c = true # c is nil
And others it doesn't get assigned:
puts d if false # d generates a NameError
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56518433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: scroll-snap-align and scroll-snap-type not enough? I'm trying to use this :
https://developer.mozilla.org/docs/Web/CSS/scroll-snap-type
https://developer.mozilla.org/docs/Web/CSS/scroll-snap-align
Example I want to reproduce: https://codepen.io/mykiwi/pen/xxwPKJr?editors=1100
<div class="scroller">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
.scroller {
text-align:left;
height:250px;
width:270px;
overflow-y:scroll;
display:flex;
flex-direction:column;
box-sizing:border-box;
border:1px solid #000;
scroll-snap-type:y mandatory
}
.scroller>div {
flex:0 0 250px;
background-color:#663399;
color:#fff;
font-size:30px;
display:flex;
align-items:center;
justify-content:center;
scroll-snap-align:start;
}
.scroller>div:nth-child(even) {
background-color:#fff;
color:#663399
}
My code: https://codepen.io/mykiwi/pen/mdeqePo?editors=1100
I have Bulma in background too
What is wrong/missing from my CSS to reproduce the example ?
Thanks
A: This is a bit tricky to get it working and since the MDN does not describe it very well, this makes it harder.
What is the problem exactly?
The wrapping element you provided does not meet the expectation for doing such an action. So what does it mean?
To ensure the scroll-snap-type is working correctly we should make sure the only available scrollbar in our window is our wrapping element scrollbar, which is in your case it is a division by class name screen.
How to fix it?
So all you have to do is to make sure the scroll element is exactly related to your parent wrapping element which in your case its indicated by screen class name. To make sure the scrollbar you seeing in the right one you should make the body and html, overflow to hidden to prevent them from scrolling. just like this:
html,
body {
overflow: hidden;
}
Then you need to enable the right scrollbar, which belongs to the screen division.
.screen {
height: 100vh;
overflow-y: scroll;
scroll-snap-type: y mandatory;
}
So it will work like a charm.
Here is the live working example: codepen.io
Also, there is a similar issue in SO, that you can find here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61566412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Moved Xcode project has missing files from other libraries I moved the folder of a project in Xcode to another computer, and I"m having some issues. I'm using NMSSH framework, and the libz.dylib file is missing from the project, and I'm unable to locate it, since the Inspector button for it is grayed out. The file is not on my system either. Shouldn't it have been inside my project folder?
Also, I'm using MBProgressHUD, and I'm using it by dragging its Xcode project in, and setting the appropriate links. One of the libraries libMBProgressHUD.a is missing, and I can't locate that either.
Everything was working fine on my other computer, so I'm guessing there's a problem with search paths, etc? Any help would be much appreciated. The errors are as follows:
ld: warning: directory not found for option '-F/Users/ramesh/Documents/CodeDump_Temp/iOS/RasbPiController/../../.Trash'
Undefined symbols for architecture i386:
"_OBJC_CLASS_$_NMSSHSession", referenced from:
objc-class-ref in UserPi.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
A: you can download the missing file from the link below
https://www.dropbox.com/s/au2irnctslcpjih/libz.dylib
and paste it in your iOS Simulator folder. I hope it will work .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17257401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pass Button Name from XAML to ViewModel using MVVM In my XAML, I have defined a button as such:
<DataTemplate x:Key="ItemTemplate">
<WrapPanel Orientation="Vertical" Width="Auto">
<Button Width="200" Height="300" Click="SelectMovie_Click" >
<Button.Template>
<ControlTemplate >
<Image Source="{Binding image}"/>
</ControlTemplate>
</Button.Template>
<i:Interaction.Behaviors>
<local:UniqueNameBehavior ID="{Binding id}"/>
</i:Interaction.Behaviors>
</Button>
<TextBlock Text="{Binding title}" HorizontalAlignment="Center"/>
</WrapPanel>
</DataTemplate>
I use the Behaviour to dynamically assign a name to my button.
public class UniqueNameBehavior : Behavior<FrameworkElement>
{
public UniqueNameBehavior() : base() { }
public String ID
{
get { return (String)this.GetValue(IDProperty); }
set { this.SetValue(IDProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
//Assign unique name to the associated element
AssociatedObject.Name = "movie" + ID;
}
public static readonly DependencyProperty IDProperty = DependencyProperty.Register(
"ID", typeof(String),
typeof(UniqueNameBehavior));
}
When this button is clicked, I would like to pass this Name to my ViewModel.
This is my Behind-Code
private void SelectMovie_Click(object sender, RoutedEventArgs e)
{
// _moviePanelVM is an instance of my ViewModel
_moviePanelVM.GetSelectedMovieDetails();
}
So I understand I could retrieve the button name here and pass it to the ViewModel but I feel this might not be the right way to do this if using the MVVM model.
Could anyone please suggest as to how I might achieve this the correct way?
Thank you for your help.
A: You could add a Command in your ViewModel: For example the Commands Section here could help: Implementing the MVVM Pattern Using the Prism Library 5.0 for WPF .
And add a parametrized Command with the help of the Prism library and as the parameter you commit the Name of your button (Internet is full of help). And bind the command to your button.
A: Use command parameters in XAML file. This is simple sintax to pass object with button "CommandParameter={Binding senderObject}" add this at the end of the button tag.
Access the same in the
private void SelectMovie_Click(object sender, RoutedEventArgs e)
{
String buttonId = sender as String;
// _moviePanelVM is an instance of my ViewModel
_moviePanelVM.GetSelectedMovieDetails();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27629624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to scale down Texture in libgdx to fit smaller screens? My app provides two buttons in a table row. Each image has a width of 300 pixel (source). The app shows all parts of both buttons if I provide an initial window width which is greater than 600. Even resizing the window to a smaller size works smoothly. Both buttons are shown fully and they get scaled down if needed when resizing the window. The buttons are cut off once I provide an initial window size which is smaller than 600 pixel. How can I show the whole buttons on small screens by default?
Screenshots:
My code looks like this:
public class LevelChooserState extends GameState {
private Stage stage;
private Texture bgTexture;
private Pixmap bgPixmap;
private Viewport viewportStage;
private Container<Table> container;
private Table table;
public LevelChooserState(final GameStateController gsc) {
super(gsc);
Gdx.app.log(TAG, "Setup Level Chooser State.");
// Setup Background Color
bgPixmap = new Pixmap(1, 1, Pixmap.Format.RGB565);
bgPixmap.setColor(Color.WHITE);
bgPixmap.fill();
bgTexture = new Texture(bgPixmap);
TextureRegionDrawable textureRegionDrawableBg = new TextureRegionDrawable(new TextureRegion(bgTexture));
// Setup viewports
viewportStage = new ExtendViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
viewportStage.setScreenBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
// Setup stage
stage = new Stage(viewportStage);
Gdx.input.setInputProcessor(stage);
// Setup font
int Help_Guides = 12;
int row_height = Gdx.graphics.getWidth() / 12;
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/PatrickHand-Regular.ttf"));
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = 30;
parameter.borderWidth = 1;
parameter.color = Color.BLACK;
BitmapFont myFont = generator.generateFont(parameter);
generator.dispose();
// Setup background pictures
TextureAtlas textureAtlas = new TextureAtlas("atlas/onoff.atlas");
TextureRegion backgroundTR1 = textureAtlas.findRegion("onoff_off");
TextureRegion backgroundTR2 = textureAtlas.findRegion("onoff_on");
// Setup TextButtons
TextureRegionDrawable up1= new TextureRegionDrawable(backgroundTR1);
TextureRegionDrawable down1= new TextureRegionDrawable(backgroundTR2);
TextureRegionDrawable checked1= new TextureRegionDrawable(backgroundTR2);
String text1 = "Deceptive dance in the poultry house.";
ClickListener clickListner1 = new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.log(Constants.TAG, "Button click received.");
gsc.setState(GameStateController.State.PLAY);
}
};
TextButton textButton1 = createTextButton(myFont, text1, up1, down1, checked1, clickListner1);
// ... created some more buttons at this point
// Setup Layout
container = new Container<Table>();
container.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
container.setBackground(textureRegionDrawableBg);
container.align(Align.bottomLeft);
table = new Table();
table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
table.setTouchable(Touchable.enabled);
table.setDebug(true);
table.debugAll();
table.setBackground(textureRegionDrawableBg);
table.setFillParent(true);
table.align(Align.top);
// TODO take care of scaling too when setting padding
float padding = 10;
table.row();
table.add(textButton1).expandX().pad(padding);
table.add(textButton2).expandX().pad(padding);
table.row();
table.add(textButton3).expandX().pad(padding);
table.add(textButton4).expandX().pad(padding);
table.row();
container.setActor(table);
stage.addActor(container);
}
private TextButton createTextButton(BitmapFont font, String text, TextureRegionDrawable up, TextureRegionDrawable down, TextureRegionDrawable checked, ClickListener clickListener) {
Label.LabelStyle labelStyle = new Label.LabelStyle();
labelStyle.font = font;
Label label = new Label(text,labelStyle);
label.setWrap(true);
TextButton.TextButtonStyle style = new TextButton.TextButtonStyle();
style.up = up;
style.down = down;
style.checked = checked;
style.font = font;
TextButton button = new TextButton(label.toString(), style);
//button.setSize(50,100);
button.setLabel(label);
button.getLabelCell().pad(20f);
button.getLabel().setAlignment(Align.topLeft);
button.setPosition(0,0);
button.addListener(clickListener);
return button;
}
@Override
public void update(float delta) {
}
@Override
public void render() {
Gdx.gl.glClearColor(1f,1f,1f,1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
stage.getViewport().apply();
stage.draw();
stage.act();
batch.end();
}
@Override
public void dispose() {
Gdx.app.log(TAG, "dispose(); Level Chooser");
stage.dispose();
bgPixmap.dispose();
bgTexture.dispose();
}
@Override
public void resize(int w, int h) {
Gdx.app.log(TAG, "resize() LevelChooserState;");
stage.getViewport().update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);
container.setFillParent(true); // makes sure the container will expand on resize
}
}
A: LibGDX uses real-pixel-to-screen-pixel mapping.
You're using an ExtendViewport to initialize the game, which takes its minimum height and width from the actual window size in Gdx.graphics.getWidth(), Gdx.graphics.getHeight().
This means that the 'fake screen' you have, which you can then resize as much as you want, is actually determined by the size of the window.
I would advise you start with a fixed size for the ExtendViewport - say, 600 width, 400 height - and later you can change this to suit different sizes if necessary.
ExtendViewport with fixed sizes works fantastically well, even when displaying on extremely large screens.
A: It works smoothly once I calculate and set the desired button manually. Width and height are calculated depending on screen size.
I changed this:
table.add(textButton1).expandX().pad(padding);
to this:
float buttonWidth = Gdx.graphics.getWidth()/2 * 0.9f;
float buttonHeight = buttonWidth * 1.3f;
table.add(textButton1).width(buttonWidth).height(buttonHeight).expandX().pad(padding);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70948200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Extend the response time of the 3rd party URL in netsuite? i.e., to avoid SSS_REQUEST_TIME_EXCEEDED for large requests My POST request to a 3rd party URL is taking about 58 seconds(Checked this by testing it using postman).
But netsuite is giving SSS_REQUEST_TIME_EXCEEDED error if the response time exceeds 45 seconds.What are the settings to be done to make netsuite accept more response time than 45 seconds.
An order has 50 items and so the third party url is taking 57 seconds to process and give response. These kind of cases couldn't be avoided in my requirement.Please help
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55936418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Reverse order of XML using PHP I'm using PHP to output data from an XML file. It's defaulting to chronological order, which I'd like to reverse. Is this possible with PHP? If so, how?
Here's my page and code:
$file = 'http://www.gostanford.com/data/xml/events/m-baskbl/2010/index.xml';
$xml = simplexml_load_file($file);
foreach ($xml as $event_date) {
if(!empty($event_date->event['vn']) && !empty($event_date->event['hn']) && !empty($event_date->event['vs']) && !empty($event_date->event['hs']))
{
echo '<li>';
echo '<h3>', $event_date->event['vn'], ' vs ', $event_date->event['hn'], '</h3>';
echo '<p><strong>', $event_date->event['vs'], ' - ', $event_date->event['hs'], '</strong></p>';
echo '<p>', date('F j, Y', strtotime($event_date['date'])), '</p>';
echo '</li>';
}
}
Thanks for your help!
A: As the first answer notes, this may not be a good idea on big XML documents. The simplest and most portable code for PHP 5.1.2 and above may be to use SimpleXML. It may have been built in to earlier PHP versions, but it is standard after 5.1.2.
<?php
$file = 'http://www.gostanford.com/data/xml/events/m-baskbl/2010/index.xml';
$xml = simplexml_load_file($file);
if ($xml === false) {
echo "Couldn't load file\n";
exit (1);
}
$xmlArray = array();
foreach ($xml as $event_date) $xmlArray[] = $event_date;
$xmlArray = array_reverse($xmlArray);
foreach ($xmlArray as $event_date) {
if(!empty($event_date->event['vn']) && !empty($event_date->event['hn']) && !empty($event_date->event['vs']) && !empty($event_date->event['hs']))
{
echo '<li>';
echo '<h3>', $event_date->event['vn'], ' vs ', $event_date->event['hn'], '</h3>';
echo '<p><strong>', $event_date->event['vs'], ' - ', $event_date->event['hs'], '</strong></p>';
echo '<p>', $event_date['date'], '</p>';
echo '<p>', $event_date->event['local_time'], '</p>';
echo '</li>';
}
}
?>
A: If $xml is just an array, you can use array_reverse($xml) to reverse it:
foreach (array_reverse($xml) as $event_date) {
// etc
}
But, if it's long, that might not be efficient. You could use a manual for-loop with decrementing indices:
for ($i = sizeof($xml) - 1; $i >= 0; --$i) {
// use $xml[$i] to access each element
}
A: Obviously you can read your xml to an array and print in reverse order. However, this might not be a good idea for a long list.
EDIT:
foreach($xml as $event_date){
if(!empty($event_date->event['vn']) && !empty($event_date->event['hn']) && !empty($event_date->event['vs']) && !empty($event_date->event['hs']))
{
$my[]=array (
"vn" => $event_date->event['vn'],
"hn" => $event_date->event['hn']
...
);
}
}
for($i=count($my)-1;$i>=0;$i--) {
echo '<li>';
echo '<h3>', $my[$i]['vn'], ' vs ', $my[$i]['hn'];
...
echo '</li>';
}
Hope this helps, it might need fixes.
A: Can you reverse your output instead of the xml? IE:
$arr = array();
foreach($xml as $event_date){
if(!empty($event_date->event['vn']) && !empty($event_date->event['hn']) && !empty($event_date->event['vs']) && !empty($event_date->event['hs']))
{
$strLine = "";
$strLine .= '<li>';
$strLine .= '<h3>'. $event_date->event['vn']. ' vs '. $event_date->event['hn']. '</h3>';
$strLine .= '<p><strong>'. $event_date->event['vs']. ' - '. $event_date->event['hs']. '</strong></p>';
$strLine .= '<p>'. $event_date['date']. '</p>';
$strLine .= '<p>'. $event_date->event['local_time']. '</p>';
$strLine .= '</li>';
$arr[] = $strLine;
}
}
$arr = array_reverse($arr);
foreach ($arr as $line)
{
echo $line;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5969662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: I'm trying to replace Xpath with jQuery Android browser not support XpathEvaluator Object.
I'm trying to replace with Xpath with JQuery.
For example,
01. oRoot.selectSingleNode("step/person");
-> $(oRoot).find("step person");
02. oRoot.selectSingleNode("step/person[@color='red' and age='20']");
-> $(oRoot).find("step person[color='red'][age=[20]");
But, I don't know how change below code?
01. oRoot.selectSingleNode("step/person[@color='red' or @color='black']");
02. oRoot.selectSingleNode("step/person[taskinfo/status='holding']");
Do you know apply OR operation to jQuery Code?
Do you konw apply one depth attribute to jQuery Code?
or Do you have other good solution?
A: There aren't conditional operators in jquery selectors, you just need to separate the selectors with a comma.
$(oRoot).find('step person[color=red] , step person[color=black]');
More on jQuery selectors http://api.jquery.com/category/selectors/
You can easily apply an attribute using jQuery's .attr():
$('step person', oRoot).attr('foo', 'bar');
More on jQuery attr: http://api.jquery.com/attr/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7656798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Menu always hidden to three dots instead of shown in action bar I have an activity with navigation drawer. The activity contain a view pager that hold 3 fragment. I've inflate the menu successfully. But, instead of showing the icon in action bar, it's hidden in three dots.
I've menu code below :
home_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/search_menu"
android:icon="@drawable/baseline_search_24"
android:title="Search"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView">
</item>
</menu>
onCreateOptionsMenu() code :
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val inflater = MenuInflater(this)
inflater.inflate(R.menu.home_menu, menu)
val searchItem: MenuItem? = menu!!.findItem(R.id.search_menu)
searchItem?.let {
it.actionView?.let {
val searchView: SearchView = it as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(p0: String?): Boolean {
return false
}
override fun onQueryTextChange(p0: String?): Boolean {
return false
}
})
}
}
return true
}
What's wrong ?
Is another menu file will affected to that menu ?
Here's another menu files :
activity_home_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<item
android:id="@+id/admin_menu"
android:visible="true"
android:title="Admin Menu">
<menu>
<item
android:id="@+id/manage_user"
android:icon="@drawable/ic_group_gray_24dp"
android:title="Manage User" />
<item
android:id="@+id/manage_schedule"
android:icon="@drawable/baseline_calendar_today_24"
android:title="Manage Schedule" />
</menu>
</item>
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_edit_profile"
android:icon="@drawable/baseline_edit_24"
android:title="Edit Profile" />
<item
android:id="@+id/nav_logout"
android:icon="@drawable/baseline_exit_to_app_24"
android:title="Logout" />
</group>
</menu>
bottom_navigation_drawer_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/home_menu"
android:icon="@drawable/baseline_home_24"
android:title="Home"/>
<item
android:id="@+id/search_user_menu"
android:icon="@drawable/baseline_search_24"
android:title="Search User"/>
<item
android:id="@+id/schedule_request_menu"
android:icon="@drawable/baseline_inbox_24"
android:title="Request"/>
</menu>
A: If you want to show a menu icon then try this.
you should add showAsAction attribute to always or ifRoom
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_refresh"
android:icon="@drawable/ic_refresh"
android:showAsAction="ifRoom"
android:title="@string/action_refresh"/>
<item
android:id="@+id/action_filter"
android:icon="@drawable/ic_filter"
android:showAsAction="always"
android:title="@string/action_filter"/>
</menu>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55510479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: find the average value of each event type on the day immediately after the event If you have two tables:
"Events"
id int
event_type varchar
event_date Date ("dd/MM/YYYY")
| id | event_type | event_date |
|---------------------|------------------|-----------------|
| 1 | a | 01/01/2001 |
| 2 | b | 01/02/2001 |
| 3 | c | 01/03/2001 |
| 4 | c | 01/04/2001 |
| 5 | a | 01/05/2001 |
| 6 | b | 01/06/2001 |
| 7 | a | 01/07/2001 |
| 8 | b | 01/08/2001 |
|----------------------------------------------------------|
"Values"
object_id int
date Date ("dd/MM/YYYY")
value float
| id | value | date |
|---------------------|--------------------|-----------------|
| 1 | 1.0 | 31/12/2001 |
| 2 | 2.0 | 01/01/2001 |
| 3 | 3.0 | 02/01/2001 |
| 4 | 4.0 | 31/01/2001 |
| 5 | 5.0 | 01/02/2001 |
| 6 | 6.0 | 02/02/2001 |
| 7 | 7.0 | 28/02/2001 |
| 8 | 8.0 | 01/03/2001 |
| 9 | 9.0 | 02/03/2001 |
| 10 | 1.1 | 31/03/2001 |
| 11 | 2.1 | 01/04/2001 |
| 12 | 3.1 | 02/04/2001 |
| 13 | 4.1 | 30/04/2001 |
| 14 | 5.1 | 02/05/2001 |
| 15 | 6.1 | 02/06/2001 |
| 16 | 7.1 | 02/07/2001 |
| 17 | 8.1 | 02/08/2001 |
|------------------------------------------------------------|
How would you find the average value of each event type on the day immediately after the event?
I've tried variations of the following but it doesn't seem to be working,
SELECT events.* FROM
events INNER JOIN (SELECT id,
event_type,
MIN(event_date) AS first_event_date
FROM event
GROUP BY
id,event_type) AS fe
ON events.id = fe.id
AND events.date = fe.first_event_date;
Also, would it help to first select rows in a small date range around each event before finding the post-event averages?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67687005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 503 Service Temporarily Unavailable in Openshift Flask Application I've been struggling to deploy a Flask application in Openshift. First of all, I tried to deploy an application I am developing. As I didn't succeed, I decided to create a sample Hello World and deploy it.
Here is the code of app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html')
if __name__ == '__main__':
app.run()
I do use the install_requirements in setup.py file:
from setuptools import setup
setup(name='SweetyPro',
version='1.0',
description='OpenShift App',
author='Your Name',
author_email='waglds@gmail.com',
url='http://www.python.org/sigs/distutils-sig/',
install_requires=['Django>=1.3',
'Flask==0.11.1'], )
I also set up flask and a requirement in requirements.txt. However, Openshift only says it is a Service Temporarily Unavailable.
I checked out the log through rhc tail -a my_application, and it prompts me this:
==> app-root/logs/python.log <==
Traceback (most recent call last):
File "app.py", line 10, in <module>
app.run()
File "/var/lib/openshift/57976d4c7628e1a34e000179/python/virtenv/lib/python2.7/site-packages/Flask-0.11.1-py2.7.egg/flask/app.py", line 843, in run
run_simple(host, port, self, **options)
File "/var/lib/openshift/57976d4c7628e1a34e000179/python/virtenv/lib/python2.7/site-packages/Werkzeug-0.11.10-py2.7.egg/werkzeug/serving.py", line 694, in run_simple
inner()
File "/var/lib/openshift/57976d4c7628e1a34e000179/python/virtenv/lib/python2.7/site-packages/Werkzeug-0.11.10-py2.7.egg/werkzeug/serving.py", line 656, in inner
fd=fd)
File "/var/lib/openshift/57976d4c7628e1a34e000179/python/virtenv/lib/python2.7/site-packages/Werkzeug-0.11.10-py2.7.egg/werkzeug/serving.py", line 550, in make_server
passthrough_errors, ssl_context, fd=fd)
File "/var/lib/openshift/57976d4c7628e1a34e000179/python/virtenv/lib/python2.7/site-packages/Werkzeug-0.11.10-py2.7.egg/werkzeug/serving.py", line 464, in __init__
HTTPServer.__init__(self, (host, int(port)), handler)
File "/opt/rh/python27/root/usr/lib64/python2.7/SocketServer.py", line 419, in __init__
self.server_bind()
File "/opt/rh/python27/root/usr/lib64/python2.7/BaseHTTPServer.py", line 108, in server_bind
SocketServer.TCPServer.server_bind(self)
File "/opt/rh/python27/root/usr/lib64/python2.7/SocketServer.py", line 430, in server_bind
self.socket.bind(self.server_address)
File "/opt/rh/python27/root/usr/lib64/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 13] Permission denied
Could anyone help me out, please? I already did what I could. Thank you!
A: Because you have supplied an app.py file, it will be run to start your application. This will use the builtin Flask development server with the way the code is setup. In doing that though, you need to tell the Flask development server which port to listen on, you can't use the default port that the Flask development server users. The port is available in the OPENSHIFT_PYTHON_PORT environment variable. See:
*
*https://developers.openshift.com/managing-your-applications/environment-variables.html#informational-variables
You may also need to use OPENSHIFT_PYTHON_IP environment variable and tell the Flask development server what host interface to bind to if by default it only listens on localhost.
An alternative to all that is to rename your app.py file to wsgi.py and add:
application = app
after the Flask application object is created. By making that change then OpenShift will host the application with Apache/mod_wsgi instead and it will worry about how to host it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38596033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Zooming axes in CorePlot I have an app where I use CorePlot to plot a graph. I have implemented the zooming of the graph itself with pinch gestures, but I still can't make the labels near the axis (which contain numbers like 1, 2 etc.) zoom properly, so instead of 1 the major interval changes to 5 or 0.5 (or any other number) depending on the pinch gesture.
-(void) viewDidAppear
{
UIPinchGestureRecognizer* rec = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scalePiece:)];
// set options for this recognizer.
[self.view addGestureRecognizer:rec];
...
xMajorInterval = 1;
yMajorInterval = 1;
axisSet = (CPXYAxisSet *)graph.axisSet;
axisSet.xAxis.majorIntervalLength = CPDecimalFromFloat(xMajorInterval);
axisSet.xAxis.minorTicksPerInterval = 4;
axisSet.xAxis.minorTickLength = 4.0f;
axisSet.xAxis.majorTickLength = 8.0f;
axisSet.xAxis.labelOffset = 1.0f;
axisSet.yAxis.majorIntervalLength = CPDecimalFromFloat(yMajorInterval);
axisSet.yAxis.minorTicksPerInterval = 4;
axisSet.yAxis.minorTickLength = 4.0f;
axisSet.yAxis.majorTickLength = 8.0f;
axisSet.yAxis.labelOffset = 1.0f;
...
}
- (void)scalePiece:(UIPinchGestureRecognizer *)gestureRecognizer {
//Here I tried to change xMajorInterval and yMajorInterval and redraw axes
}
Here's how I zoom the plot
- (void)scalePiece:(UIPinchGestureRecognizer *)gestureRecognizer {
if (PlotSpaceX > -0.1) {
if ([gestureRecognizer scale] > 1) {
PlotSpaceY = PlotSpaceY - 0.1;
PlotSpaceX = PlotSpaceX - 0.1;
}
}
if (PlotSpaceY >= -0.1) {
if ([gestureRecognizer scale] < 1){
PlotSpaceY = PlotSpaceY + 0.1;
PlotSpaceX = PlotSpaceX + 0.1;
}
}
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:plotSpace.xRange.location length:CPDecimalFromFloat(PlotSpaceX * 2.0)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:plotSpace.yRange.location length:CPDecimalFromFloat(PlotSpaceY * 2.0)];
majorInterval = majorInterval*PlotSpaceX/4;
intMajorInterval = majorInterval;
NSLog(@"%i", intMajorInterval);
axisSet.xAxis.majorIntervalLength = CPDecimalFromInt(intMajorInterval);
axisSet.yAxis.majorIntervalLength = CPDecimalFromInt(intMajorInterval);
}
In the scalePiece method I tried to change xMajorInterval and yMajorInterval and redraw axes but, unfortunately, this method is called so often during the pinch gesture that the labels just display huuuge numbers.
Can you help me, please?
A: It seems like the answer to this question depends on how you're doing the zooming of the graph itself.
You'll basically want to scale the majorIntervalLength in the same way you're scaling the ranges for your plot space. That is, if you expand the range by a factor of 2 then you want to also change the value of majorIntervalLength to twice it's current value. If you expand by 1.1, you'll multiply the current value of majorIntervalLength by 1.1 and then set majorIntervalLength to that new value.
If you post your code for the graph scaling I can provide a more detailed answer with some code.
[UPDATE]
After looking at your code. I would recommend the following changes
before you update PlotSpaceX do this:
intervalScale = (PlotSpaceX + 0.1 / PlotSpaceX)
then update majorInterval like this
majorInterval = majorInterval*intervalScale
This should scale your axis interval in exactly the same way as your x coordinate.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5044509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Capistrano and Git, Ruining my life. "Unable to resolve revision for [HEAD] on repository ..." I searched all of the relevant Capistrano issues, but couldn't find something that even elucidated anything here for me.
git version 1.6.4.2
Capistrano v2.5.10
Basically, when I run my cap deploy.rb script, it connects to the server, starts executing the deploy:update task, then in the deploy:update_code task:
*** [deploy:update_code] rolling back
* executing "rm -rf /home/user_name/public_html/project_name/releases/20091223094358; true"
servers: ["project_name.com"]
It fails with the following error:
/Library/Ruby/Gems/1.8/gems/capistrano-2.5.10/lib/capistrano/recipes/deploy/scm/git.rb:231:in `query_revision': Unable to resolve revision for 'master' on repository 'ssh://git@slice_ip:path_to_git_repository'. (RuntimeError)
Here's my deploy script, I've tried including and omitting:
set :branch 'master'
I also just thought my path to the repository was off, but i've tried just about every permutation (absolute, not absolute, .git suffix, no suffix). There's definitely a bare git repository at the path i'm pointing to.
**I do have multiple projects being hosted on one slice. The other projects is also a rails project, but is running SVN. Capistrano deployments work fine.
Any pointers in the right direction or any ideas would help reduce the amount of drinking I am planning on doing if I can't figure this out. (Paths / IPs obfuscated, dont hack me bro!)
set :application, "project1"
set :user, "username"
set :repository, "ssh://git@67.24.9.133/home/git/project1.git"
set :branch, "master"
set :port, 696969
set :deploy_to, "/home/username/public_html/#{application}"
set :scm, :git
role :app, application
role :web, application
role :db, application, :primary => true
# deployment via remote client (workstation)
set :deploy_via, :copy
set :runner, user
# mod_rails
namespace :deploy do
desc "Restarting mod_rails with restart.txt"
task :restart, :roles => :app, :except => { :no_release => true } do
run "touch #{current_path}/tmp/restart.txt"
end
[:start, :stop].each do |t|
desc "#{t} task is a no-op with mod_rails"
task t, :roles => :app do ; end
end
end
This was the most relevant post (extremely relevant even), but I couldn't really figure out what they were saying the fix is. I'm pretty new with git / capistrano configs.
https://capistrano.lighthouseapp.com/projects/8716/tickets/56-query_revision-unable-to-resolve-revision-for-head-on-repository
A: Ok I seemed to have fixed it.
Basically, since I have 2 separate repositories on the remote server, I think the "git" user was failing because I hadn't registered an ssh keypair for the git user. That explains why one of my deploy.rb scripts was working properly, while this one wasn't.
In the link I posted in the question, one of the commenters pointed out the issue:
https://capistrano.lighthouseapp.com/projects/8716/tickets/56-query%5Frevision-unable-to-resolve-revision-for-head-on-repository
Note this error is also displayed if
you are using multiple github keys per
http://capistrano.lighthouseapp....
and you do not have these keys and a
corresponding entry in your
.ssh/config on the workstation you're
running the deploy from. so the
ls-remote is run locally. is there a
way to reference the repository at
github.com for this request while the
remote deploy uses
git@github-project1:user/project1.git
Also, see the following link for more details, since the whole ssh issue would apply even if you're not using github.
http://github.com/guides/multiple-github-accounts
A: Both your workstation and your server must be able to reach the repository at the address specified, if not then you may have to set :local_repository to how you access it from your workstaion, and :repository to be how your servers should access it.
A: For me Capistrano deployments with Git only seem to work when setting set :copy_cache, true
A: I've only used capistrano with git once, but never used or seen the use of ssh:// in the repository definition.
Try using set :repository, "git@67.24.9.133/home/git/project1.git" instead
A: Make sure the branch you are deploying from exists.
set :branch, "upgrade-to-2013.4.3"
is not equal to
set :branch, "upgrade-to-2013.3.4"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1951838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Realm DB - exception thrown for no apparent reason I have a refresh command in a Xamarin page, and for some reason, Realm throws a RealmInvalidTransactionException when it finishes. In their documentation they wrote:
An exception, thrown when trying to write data to the Realm outside a Transaction or when trying to create a transaction on a Realm that is opened as read-only.
This is my refresh command:
ICommand refreshCommand = new Command(async () =>
{
refreshView.IsRefreshing = true;
// Refresh everything
var w = summaryViewModel.Articles[0];
WebArticlesListView.RefreshCommand.Execute(null);
summaryViewModel.UpdateSummaryCommand.Execute(null);
// wait for articles to finish loading to stop loading indicator
await Task.Run(() =>
{
try
{
while (w == summaryViewModel.Articles[0]) ;
}
catch (ArgumentOutOfRangeException e)
{
while (summaryViewModel.Articles.Count < 5) ;
}
});
refreshView.IsRefreshing = false;
});
While debugging, I noticed that the exception is only thrown right after the refresh command finishes (I went step by step with VS's debugger and it was thrown right after I pressed F10 [step] on the last curly brackets). No object is trying to access the DB after it, and nothing happens from my code after the command finishes its job, so I don't understand why the exception would be thrown. Moreover, the stack trace of the exception is [External Code] based on the Call Stack column in VS's debugger.
Edit: I'm using Xamarin for Android and iOS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61563228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SDL OpenGL smooth camera movement I am trying to implement a camera motion system into the program I am currently working on. I cant figure out how to move the camera in non-discrete units so when I move the camera it "jumps" to the next position. how can I move the camera smoothly without jumps.
CameraControlls Function:
void CameraControlls()
{
while (SDL_PollEvent(&e))
{
if (e.type == SDL_QUIT)
{
exit(0);
}
switch (e.type)
{
case SDL_KEYDOWN:
switch (e.key.keysym.sym)
{
case SDLK_w:
cam.MoveForward(0.3f);
break;
case SDLK_s:
cam.MoveBackward(0.3f);
break;
case SDLK_d:
cam.MoveRight(0.2f);
break;
case SDLK_a:
cam.MoveLeft(0.2f);
break;
case SDLK_ESCAPE:
exit(0);
break;
case SDLK_RIGHT:
cam.Yaw(-0.01f);
break;
case SDLK_LEFT:
cam.Yaw(0.01f);
break;
case SDLK_DOWN:
cam.Pitch(0.01f);
break;
case SDLK_UP:
cam.Pitch(-0.01f);
break;
}
}
}
}
Camera Structure:
struct Camera
{
public:
Camera(glm::vec3& pos, float fov, float aspect, float zNear, float zFar)
{
this->pos = pos;
this->forward = glm::vec3(0.0f, 0.0f, 1.0f);
this->up = glm::vec3(0.0f, 1.0f, 0.0f);
this->projection = glm::perspective(fov, aspect, zNear, zFar);
}
inline glm::mat4 GetViewProjection() const
{
return projection * glm::lookAt(pos, pos + forward, up);
}
void MoveBackward(float amt)
{
pos -= forward*amt;
}
void MoveForward(float amt)
{
pos += forward * amt;
}
void MoveRight(float amt)
{
pos -= glm::cross(up, forward) * amt;
}
void MoveLeft(float amt)
{
pos += glm::cross(up, forward) * amt;
}
void Pitch(float angle)
{
glm::vec3 right = glm::normalize(glm::cross(up, forward));
forward = glm::vec3(glm::normalize(glm::rotate(angle, right) * glm::vec4(forward, 0.0)));
up = glm::normalize(glm::cross(forward, right));
}
void Yaw(float angle)
{
static const glm::vec3 UP(0.0f, 1.0f, 0.0f);
glm::mat4 rotation = glm::rotate(angle, UP);
forward = glm::vec3(glm::normalize(rotation * glm::vec4(forward, 0.0)));
up = glm::vec3(glm::normalize(rotation * glm::vec4(up, 0.0)));
}
private:
glm::mat4 projection;
glm::vec3 pos;
glm::vec3 forward;
glm::vec3 up;
};
A: I guess the key event of sdl is not firing every frame so you shouldn't change the camera position directly from there because camera wont update every frame.
I would create a boolean variable MOVE_FORWARD that will represent if the forward key is pushed or not
*
*In the key event you update the MOVE_FORWARD variable.
while (SDL_PollEvent(&e))
{
..........
case SDL_KEYDOWN:
switch (e.key.keysym.sym)
{
case SDLK_w:
MOVE_FORWARD=true;
break;
*In every frame you update the position of the camera
if (MOVE_FORWARD){pos+=0.3}
This way the camera updates its position every frame and not only when the key event fires
You could also avoid creating key state variables using SDL_GetKeyboardState(NULL) instead of SDL_PollEvent(&e):
Uint8* keystate = SDL_GetKeyState(NULL);
if(keystate[SDL_SCANCODE_W])
{
pos+=0.3;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44425539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Open a EEG EDF file using mne python I need to use mne python for my master degree project, but i'm new in python programming. So i'm trying to open a single EEG edf file, i have tried several codes and none of them worked. The last code i tried:
import mne
from google.colab import drive
drive.mount ('/gdrive')
cd /gdrive/drive/MyDrive/EDFfiles
fname = 'chb01_01.edf'
raw = mne.io.read_raw_edf(fname, preload=True)
and i get this message:
Extracting EDF parameters from /content/chb01_01.edf...
EDF file detected
FileNotFoundError Traceback (most recent call last)
in ()
----> 1 raw = mne.io.read_raw_edf(fname, preload=True)
4 frames
/usr/local/lib/python3.7/dist-packages/mne/io/edf/edf.py in read_raw_edf(input_fname, eog, misc, stim_channel, exclude, infer_types, preload, verbose)
1331 return RawEDF(input_fname=input_fname, eog=eog, misc=misc,
1332 stim_channel=stim_channel, exclude=exclude,
-> 1333 infer_types=infer_types, preload=preload, verbose=verbose)
1334
1335
in init(self, input_fname, eog, misc, stim_channel, exclude, infer_types, preload, verbose)
/usr/local/lib/python3.7/dist-packages/mne/io/edf/edf.py in init(self, input_fname, eog, misc, stim_channel, exclude, infer_types, preload, verbose)
132 info, edf_info, orig_units = _get_info(input_fname, stim_channel, eog,
133 misc, exclude, infer_types,
--> 134 preload)
135 logger.info('Creating raw.info structure...')
136
/usr/local/lib/python3.7/dist-packages/mne/io/edf/edf.py in _get_info(fname, stim_channel, eog, misc, exclude, infer_types, preload)
374 misc = misc if misc is not None else []
375
--> 376 edf_info, orig_units = _read_header(fname, exclude, infer_types)
377
378 # XXX: tal_ch_names to pass to _check_stim_channel should be computed
/usr/local/lib/python3.7/dist-packages/mne/io/edf/edf.py in _read_header(fname, exclude, infer_types)
361 logger.info('%s file detected' % ext.upper())
362 if ext in ('bdf', 'edf'):
--> 363 return _read_edf_header(fname, exclude, infer_types)
364 elif ext == 'gdf':
365 return _read_gdf_header(fname, exclude), None
/usr/local/lib/python3.7/dist-packages/mne/io/edf/edf.py in _read_edf_header(fname, exclude, infer_types)
578 edf_info = {'events': []}
579
--> 580 with open(fname, 'rb') as fid:
581
582 fid.read(8) # version (unused here)
FileNotFoundError: [Errno 2] No such file or directory: '/content/chb01_01.edf'
A: just a suggestion:
Firstly try to insert 'chb01_01.edf' in python working directory. Python will find the file or c:\temp_edf\chb01_01.edf. It is easier to find.
best
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72208810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Nested select from different tables I'm trying to do a nested select but with different tables. Here's my query:
SELECT contact_profile.name, main_app.fk_lkp_app, main_app.id as main_id,
(
-- if the main_app.fk_lkp_app value is 1 then do this
SELECT SUM(translation_app.amount)
FROM translation_app
WHERE translation_app.fk_main_app = main_app.id
AND translation_app.status = 2
AND main_app.srf_number is not null
AND main_app.fk_invoice is not null
-- if the main_app.fk_lkp_app value is 2 then do this
SELECT SUM(interpretation_app.amount)
FROM interpretation_app
WHERE interpretation_app.fk_main_app = main_app.id
AND interpretation_app.status =2
AND main_app.srf_number is not null
AND main_app.fk_invoice is not null
-- if the main_app.fk_lkp_app value is 3 then do this
SELECT SUM(course_app.amount)
FROM course_app
WHERE course_app.fk_main_app = main_app.id
AND course_app.status =2
AND main_app.srf_number is not null
AND main_app.fk_invoice is not null
) as amount
FROM contact_profile
LEFT JOIN main_app ON main_app.fk_contact_profile = contact_profile.id
WHERE main_app.fk_lkp_app in (1,2,3)
AND main_app.srf_number is not null
AND main_app.fk_invoice is not null
GROUP BY contact_profile.name
ORDER BY amount DESC
As you can see, the "amount" field is selected from different tables based on main_app.fk_lkp_app value. The problem is how is the best way to do this query? I'm stuck with the "main_app.fk_lkp_app" value parameter part.
I even tried using CASE as suggested but it keeps giving me error code #1064
SELECT contact_profile.name, main_app.fk_lkp_app, main_app.id as main_id,
(
CASE
WHEN main_app.fk_lkp_app = '1'
THEN (
SELECT SUM(translation_app.amount)
FROM translation_app
WHERE translation_app.fk_main_app = main_app.id
)
WHEN main_app.fk_lkp_app = '2'
THEN (
SELECT SUM(interpretation_app.amount)
FROM interpretation_app
WHERE interpretation_app.fk_main_app = main_app.id
)
WHEN main_app.fk_lkp_app = '3'
THEN (
SELECT SUM(course_app.amount)
FROM course_app
WHERE course_app.fk_main_app = main_app.id
)
ELSE 0
END CASE
) as amount
FROM contact_profile
LEFT JOIN main_app ON main_app.fk_contact_profile = contact_profile.id
WHERE main_app.fk_lkp_app in (1,2,3)
AND main_app.srf_number is not null
AND main_app.fk_invoice is not null
GROUP BY contact_profile.name
ORDER BY amount DESC
The weird thing is if I don't use case and only use 1 select from the 3 variant(for example I only select from the translation_app table) the query is working.
A: You could check the value of main_app.fk_lkp using a CASE expression
http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#operator_case
and perform a query based on that value.I could not test it but something like this should work
SELECT contact_profile.name, main_app.fk_lkp_app, main_app.id as main_id,
CASE
WHEN main_app.fk_lkp_app = 1 THEN (/* your query here */)
WHEN main_app.fk_lkp_app = 2 THEN (/* your query here */)
WHEN main_app.fk_lkp_app = 2 THEN (/* your query here */)
ELSE 0
END AS amount ....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38740547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Remotely install Linux on Windows xp using TeamViewer Our customer has about 800+ computers running Windows XP distributed across the country. Each computer can be accessed using TeamViewer. The goal is to replace XP by a Linux distribution remotely.
Does anybody know if this is possible, and where to start?
Thanks!
A: PXE is your only realistic hope:
Some on-site assistance is needed to press F12 at Bios before Windows XP boot:
A) On PC-A, setup DHCP server that refer DHCP-client to PXE server that download Linux ISO from a web server (of course all three can be a Windows machine in the same LAN segment onsite)
B) reboot PC-B onsite to reboot machine and press F10-F12 to choose Boot-options
C) then choose network-boot (PXE-Boot)
further reading : https://www.vercot.com/~serva/
guide: https://youtu.be/nnxgFpUr1Og?t=39
Note: Make sure you have enabled proxyDHCP and not DHCP Server
A: I would try with something like these:
*
*Clonezilla, which works by replicating a previously prepared disk image to one or more computers booted inside a network segment
*Cobbler, which works like a provisioning server for Linux based machines
Of those options, I have used Clonezilla with success. As long as the prepared base image doesn't change too frequently, the main time consuming tasks would be related with configuring the Clonezilla server and building that seed image.
I did a basic test of Cobbler and it worked fine in my environment, being this a way that would be more apt to deal with requirement changes.
Please also note that both options require some network configuration, like DHCP server settings that work with the PXE protocol.
Also, for your requirement, someone, a human being, would be needed to execute one or more of these tasks:
*
*Properly enable network booting in the BIOS of each of the 800+ machines, unless it has already be done before
*Boot the machines to install the new operating system
The network booting option, based on the PXE specification, should be supported by the motherboard of those machines and have higher booting priority than other devices, like CD drives, hard drives, etc.
Another thing to consider for the couple of options I'm suggesting, is how are those 800+ distributed across the country. The more disperse they are, the more cumbersome this task will be. Quite contrary, if there are few places were those machines are located, the more feasible this task will be; for example, by preparing and testing a server, computer or laptop that you then carry to each of those few places and installing the new operating system.
Regarding the option to boot using the public Internet to reach a remote deployment server, I don't know about how that could be done; in fact, for me that would be something quite interesting to learn about. If something like this is possible, another variable to note is the hardware compatibility of the destination machines, because as far as I know, protocols like PXE do some kind of multicast or broadcast in the local network segment and I presume those 800+ machines don't have recent motherboards with advanced firmware that could support more modern boot protocols.
That's all for now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44687189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to show Bottom tab navigation in specific screens only I have react native app which I am using react navigation and my navigation stack looks like the following:
<AppStack.Navigator screenOptions={{
headerStyle: {
backgroundColor: COLORS.primary2,
elevation: 0,
shadowOpacity: 0,
},
headerTintColor: '#fff',
}}>
<AppStack.Screen
name="Home"
component={HomeScreen}
options={{
headerShown: false
}}
/>
<AppStack.Screen
name="qr"
component={qr}
options={{
headerShown: false
}} />
<AppStack.Screen
name="Profile"
component={ProfileScreen}
options={{ headerShown: false }}
/>
<AppStack.Screen
name="Notifications"
component={NotificationScreen}
options={{ headerShown: false }}
/>
<AppStack.Screen
name="Support"
component={ChatScreen}
options={{ headerShown: false }}
/>
</AppStack.Navigator>
I want to create createBottomTabNavigator but to be displayed in all screen in the AppStack except the following home screen
<AppStack.Screen
name="Home"
component={HomeScreen}
options={{
headerShown: false
}}
/>
May I know what the best practice to implement that.
A: You can use tabBarVisible(boolean) prop for this purpose.
<AppStack.Screen
name="Home"
component={HomeScreen}
options={{
headerShown: false
}}
navigationOptions:()=>{
return {
tabBarVisible:false,
}
}
/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66583184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to pass an element onclick? Actually i'm trying to pass a td element with which i have to do some operations on a td click or better i have a function where i use the following code
var tr = document.getElementById($('#tavolo').val());
$(`td:eq(${inizio})`, tr).css('background-color', 'red') .attr("onclick","Elimina('" + tr + "');");
when the user will click a td it will open a modal and then in that modal there is a button that call another function which will delete some elements from that td.
The issue is that "[object HTMLTableRowElement]" is passed as tr element so i'm unable to make any operation on it.
If it's usefull here is the function Elimina
function Elimina(tr) {
$('#del').attr("onclick", "eliminaPrenotazione('" + tr + "');");
}
While here is the function eliminaPrenotazione
function eliminaPrenotazione(tr) {
var start = 1;
for (i = 0; i <= 8; i++) {
$(`td:eq(${start})`, tr).css('background-color', 'white').removeAttr("class").find('span').remove();
}
}
Here is html code of what td looks like ( i can't post all html as it has 96 similar td's)
<td style="padding: 0px; position: relative; background-color: red;" class="48:15" data-inizio="12:00" data-fine="16:00" onclick="Elimina('48:15','Ihor','12:00','16:00','[object HTMLTableRowElement]');"><span class="tag" style="width: 160px; overflow: hidden;" onmouseover="highlight(this);" onmouseout="unhighlight(this)">Ihor</span></td>
A: I'm just going to give you an indication to try to put you on the right way.
You can to do something looks like that :
$("#yourBtnID").click(function(elem){
$("#yourDivID").append("<td>" + elem + "</td>");
});
it will add a line td to the each click basically
Now you can try to modify your own code and come back if you don't succeed
Good luck ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55496796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I regroup 'sublists' in a list with Python? How can I regroup 'sublists' in a list with Python? For example, I want to regroup the following list:
[[0, 3], [1, 3], [1, 2], [1, 2], [0, 1], [0, 3]].
I want [0, 1] to be grouped with [2, 3]; [0, 2] with [1, 3]; [0, 3] with [1, 2], and left all the rest "coordinates" as single tuple. For example, in this case, I want
the output be:
[[[0, 3], [1, 2]], [[0, 3], [1, 2]], [0, 1], [1, 3]].
(The last two tuples here are "rest")
Is there a way I can achieve this goal? Thanks!!
A: Assuming you have a list of lists (like in the example, and not actual tuples):
problem = [[0, 3], [1, 3], [1, 2], [1, 2], [0, 1], [0, 3]]
You want to pair these pairs so that each pair contains each of the values in (0, 1, 2, 3) exactly once?
target = [0, 1, 2, 3]
And all the pairs that cannot be matched remain by themselves? This is one way of doing it:
answer = []
while problem:
# take the first element from problem
x1 = problem.pop()
# construct what the paired element should look like
x2 = [x for x in target if x not in x1]
try:
# attempt to remove it from problem
problem.remove(x2)
# if the remove succeeds, both x1 and x2 have now been removed, add the pair
answer.append([x1, x2])
except ValueError:
# when trying to remove a non-existent value, a ValueError is raised
# in that case, there is no matching pair, just add a single
answer.append(x1)
That's assuming:
*
*you never have values in the pairs that don't appear in the target
*the values in the pairs are always ordered like they are in the target
*you don't mind that the singles are mixed with the combinations
*you don't mind that the original problem is modified during the process
Put together:
problem = [[0, 3], [1, 3], [1, 2], [1, 2], [0, 1], [0, 3]]
target = [0, 1, 2, 3]
answer = []
while problem:
x1 = problem.pop()
x2 = [x for x in target if x not in x1]
try:
problem.remove(x2)
answer.append([x1, x2])
except ValueError:
answer.append(x1)
print(answer)
Result:
[[[0, 3], [1, 2]], [0, 1], [[1, 2], [0, 3]], [1, 3]]
A: Since the entries are only 0, 1, 2, 3 and the values are unique in every tuple, it means that the sum of the tuple can be generated by only one pair, except for 3, I mean:
[0, 1] is the only tuple wich the sum of values return 1, by the same way [0, 2] is the only one to return 2, but [0,3] and [1,2] return 3, so them require to check if it is a tuple containing one specific value, such as 3
a = [[0, 3], [1, 3], [1, 2], [1, 2], [0, 1], [0, 3]]
b = []
c = []
d_03 = []
d_12 = []
e = []
f = []
list_of_pairs = []
for tuples in a:
if sum(tuples) == 1:
b.append(tuples)
elif sum(tuples) == 2:
c.append(tuples)
elif sum(tuples) == 4:
e.append(tuples)
elif sum(tuples) == 5:
f.append(tuples)
#testing if there is a 3 in that tuple as suggested above
elif sum(tuples) == 3 and 3 in tuples:
d_03.append(tuples)
else:
d_12.append(tuples)
#one way to figure out the perfect range would be compare the len of the lists that match and use the smaller one, so you don not need the else statement
for i in range(5):
#compare len with i+1 because python starts counting from 0
#if there is any element in those lists, their len will be bigger than 0
if len(b) >= i+1 and len(f) >= i+1:
#b have [0, 1] only as tuples
#f have [2, 3] only as tuples
#so when you append one after the other, they will always match
list_of_pairs.append(b[i])
list_of_pairs.append(f[i])
#pop it so at the end will only be in those lists the ones wich don't have their pair
b.pop(i)
f.pop(i)
#insert blank spaces just so you do not modify the indexes of any elements in the list
b.insert(i-1, '')
f.insert(i-1, '')
else:
#break it because if you run the conditional above it will return IndexError
#the following i values would also return this error
break
for i in range(5):
#same principle for c and e
#and after for d
if len(c) >= i+1 and len(e) >= i+1:
list_of_pairs.append(c[i])
list_of_pairs.append(e[i])
c.pop(i)
e.pop(i)
c.insert(i-1, '')
e.insert(i-1, '')
else:
break
for i in range(5):
if len(d_12) >= i+1 and len(d_03) >= i+1:
list_of_pairs.append(d_03[i])
list_of_pairs.append(d_12[i])
d_12.pop(i)
d_03.pop(i)
d_12.insert(i-1, '')
d_03.insert(i-1, '')
else:
break
#this final list must have the pairs and also the rest
final_list = []
#append the pairs so it will be presented first and as a list inside the final list
final_list.append(list_of_pairs)
#extend by all the previous lists except for list of pairs and a
#this will put any rest in the final list as separate therms from the pairs
final_list.extend(b)
final_list.extend(c)
final_list.extend(d_03)
final_list.extend(d_12)
final_list.extend(e)
final_list.extend(f)
#now the final list might have some '' as rest
#so you can loop through it removing them
while '' in final_list:
final_list.remove('')
print(final_list)
This is the output:
[[[0, 3], [1, 2], [0, 3], [1, 2]], [0, 1], [1, 3]]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63350869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to make flutter searchDelagate a separate screen that can be navigated to independently? i have a page called searchUsersSCreen which is this:
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:myApp/models/otherUser.dart';
import 'package:myApp/ui/widgets/user_profile.dart';
import 'database.dart';
class SearchUsersScreen extends StatefulWidget {
@override
_SearchUsersScreenState createState() => _SearchUsersScreenState();
}
class _SearchUsersScreenState extends State<SearchUsersScreen> {
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => showSearch(
context: context,
delegate: SearchUsers(
DatabaseService().fetchUsersInSearch(),
),
));
}
@override
Widget build(BuildContext context) {
return Container(
color: Theme.of(context).primaryColor,
);
}
}
and inside the same dart file is have this searchDelegate :
//Search delegate
class SearchUsers extends SearchDelegate<OtherUser> {
final Stream<QuerySnapshot> otherUser;
final String hashtagSymbol = 'assets/svgs/flaticon/hashtag_symbol.svg';
SearchUsers(this.otherUser);
@override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = '';
},
),
];
}
@override
Widget buildLeading(BuildContext context) {
return Container(
width: 0,
height: 0,
);
}
@override
Widget buildResults(BuildContext context) {
return Container(
width: 0,
height: 0,
color: Theme.of(context).primaryColor,
);
}
@override
Widget buildSuggestions(BuildContext context) {
showUserProfile(String userId) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UserProfileView(
userUid: userId,
)));
}
return StreamBuilder<QuerySnapshot>(
stream: DatabaseService().fetchUsersInSearch(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
final handlesResults = snapshot.data.documents
.where((u) => u['username'].contains(query));
if (!snapshot.hasData) {
return Container(
color: Theme.of(context).primaryColor,
child: Center(
child: Text(
'',
style: TextStyle(
fontSize: 16, color: Theme.of(context).primaryColor),
),
),
);
}
if (handlesResults.length > 0) {
return Container(
color: Theme.of(context).primaryColor,
child: ListView(
children: handlesResults
.map<Widget>((u) => GestureDetector(
child: Padding(
padding: const EdgeInsets.all(0.1),
child: Container(
padding: EdgeInsets.symmetric(vertical: 5),
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
border: Border(
bottom: BorderSide(
width: 0.3, color: Colors.grey[50]))),
child: ListTile(
leading: CircleAvatar(
backgroundColor:
Theme.of(context).primaryColor,
backgroundImage:
NetworkImage(u['userAvatarUrl']),
radius: 20,
),
title: Container(
padding: EdgeInsets.only(left: 10),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(u['username'],
style: TextStyle(
fontSize: 16,
color: Theme.of(context)
.accentColor),
overflow: TextOverflow.ellipsis),
SizedBox(
height: 5,
),
Text(u['name'],
style: TextStyle(
fontSize: 16,
color: Colors.grey[500],
),
overflow: TextOverflow.ellipsis),
],
),
),
trailing: Container(
padding: EdgeInsets.only(left: 10),
height: 43.0,
width: MediaQuery.of(context).size.width / 2,
),
),
),
),
onTap: () {
showUserProfile(u['id']);
},
))
.toList(),
),
);
} else {
return Container(
color: Theme.of(context).primaryColor,
child: Center(
child: Text(
'No results found',
style: TextStyle(
fontSize: 16,
color: Theme.of(context).accentColor,
),
),
),
);
}
});
}
}
i wanted to user the class SearchUsers as a separate screen that i can navigate to independently...but couldn't achieve that as SearchUsers doesn't evaluate to a widget.
so i built SearchUsersScreen statefulWidget and inside it's initState() i called this:
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => showSearch(
context: context,
delegate: SearchUsers(
DatabaseService().fetchUsersInSearch(),
),
));
}
as to make the search feature starts automatically when the user navigates to SearchUsersScreen.
and i ended up into two problems:
*
*SearchUsers is being displayed in full screen ontop of SearchUsersSCreen (which i don't want this behavior), i want it to be displayed inside of it.
actually its covering the BottomNavigationBar i built for navigation between screens.
*after SearchUsers is being displayed (and its doing its job well), when i tap the device back button...i leave SearchUsers and get back to SearchUsersScreen....which is indeed a blank screen.
so to wrap it up...all i want is to use SearchUsers class as a widget that i can navigate to and navigate from independently...thats it.
any help would be much appreciated.
thanks for your time reading.
A: Instead of trying to create a separate widget SearchUsers, try to create a dialog and show it when anyone wants to search users. You can also use the navigator and the back button in this case and get arguments passed from the next screen to the previous screen.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66132201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Gradle fails to build after clean (depends on AAR with native libraries) I have an Android library project (projA) that depends on another library project (projB). I also have an internal Maven server (Archiva). projA contains these lines:
dependencies {
maven { url 'http://company.com/internal/repository' }
compile 'com.company:projB:2.0.7@aar'
...
}
projB is an AAR that was built with the Android library plugin, published to the company.com Archiva server, and it contains native code. Extracting the AAR shows the .so files exist where they should be, and the wrapper JAR file exists as well. If I run: ./gradlew clean build
the build fails with unresolved symbols. However, if I run
./gradlew clean build
./gradlew build
then the second build will succeed!
This is a problem, for example, on build servers that always use clean, or get a fresh copy from source control.
Why is this happening, and how do I fix it?
A: The reason this happened was because the dependency line changed, and was no longer right. I cannot figure out why it would work after one build, but not after a clean. The error message isn't clear! Even though the artifact didn't exist according to the dependency declaration, it would pass through that build step and attempt to compile.
In the end, fixing the dependency fixed this issue.
The artifact is named like this:
com.company:artifact:1.2.0.0.+@aar
That artifact exists. However, someone mistakenly changed it to:
com.company:artifact:1.2.0.0.0.+@aar
That does not exist. I had a copy of this artifact in my local ~/.m2 that fits the first, but not the second.
So, strangely, the dependency resolution had a false positive, and then the build would fail. To make matters worse, the second build (without a clean) would succeed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30654583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Visual Studio 2008 creating new classes? I upgraded to Visual Studio 2008 and for some reason when I create new class files, it loads a completely blank file as opposed to giving me the basic using code and the list of the class name (being the file name).
So if I create a new code file called Order.cs, it is no longer put in by default:
using system;
public class Order
{
}
Is this a Visual Studio user preference?
A: If you ARE using Add -> Class OR Add -> New Item and then selecting Class, and you're still only getting an empty code file, then your default "class" template is missing or messed up. If you are using Add -> Code OR Add -> New Item and selecting Code, the "Code" template is simply an empty ".cs" file, and will be given to you empty as such.
In C# Express, this file should be located at "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress\ItemTemplates\1033\". The template for the full (paid) version of Visual Studio will be the exact same file, only the folder location will differ. The file should be a standard zip file named "Class.zip". This zip file should contain two files, as follows:
First file should be named "Class.cs" and contain:
using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ == 3.5)using System.Linq;
$endif$using System.Text;
namespace $rootnamespace$
{
class $safeitemrootname$
{
}
}
Second file should be named "Class.vstemplate" and contain:
<?xml version="1.0" encoding="utf-8"?>
<VSTemplate Version="3.0.0" Type="Item" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
<TemplateData>
<Name Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="2245" />
<Description Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="2262" />
<Icon Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="4515" />
<TemplateID>Microsoft.CSharp.Class</TemplateID>
<ProjectType>CSharp</ProjectType>
<RequiredFrameworkVersion>2.0</RequiredFrameworkVersion>
<NumberOfParentCategoriesToRollUp>1</NumberOfParentCategoriesToRollUp>
<DefaultName>Class.cs</DefaultName>
</TemplateData>
<TemplateContent>
<References>
<Reference>
<Assembly>System</Assembly>
</Reference>
<Reference>
<Assembly>System.Data</Assembly>
</Reference>
<Reference>
<Assembly>System.Xml</Assembly>
</Reference>
</References>
<ProjectItem ReplaceParameters="true">Class.cs</ProjectItem>
</TemplateContent>
</VSTemplate>
If you put all of this in place, and you still get a blank code file, consider reinstalling Visual Studio.
A: Check you have the following file on your system.
C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
If not check out this Blog Post which has a brief explaination on running devenv /installvstemplates or google with bing
devenv /installvstemplates
I once had a similiar issue when I had visual webdeveloper installed and then upgraded to full visual studio pro.
If the files are in fact there I am sorry I have not had that issue and you might want to search T4 templates as I think this is what Visual Studio uses to take the template file and make it your new class file complete with class name etc.
A: You mentioned in the comments you were pressing "New->Code", dont, thats supposed to be blank. click Add>NewItem>Class , Make sure its a "Class" you select not just a code file.
A: Just to cover all bases...
The template for "Code File" is blank and the template for "Class" has what you expect.
Are you sure you're selecting the template for Class and not Code File?
A: It could be possible that your default language has not been set.
This link should help you change the default language to c# (which I am assuming from your question is the language you are going to use in Visual Studio).
A: try on the vs command prompt:
devenv.exe /installvstemplates
A: try to run devenv /resetsettings it has to be run from the Visual Studio command prompt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1491920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Call to super needs try/catch I am working on an assignment where I am told that I need to create a class (Call it ClassB) that must extend a given class (Call it ClassA). The only problem is that the code inside of the constructor of ClassA may throw an exception, so when I create my constructor for ClassB, I am trying to wrap a try/catch block around the call to super(), but of course, that doesn't work since super has to be the first call.
How can I work around this?
A: public ClassB extends ClassA {
public ClassB() throws MyClassAException {
super();
}
}
A: You can add your exception in the throws clause of your sub class constructor: -
class ClassA {
ClassA() throws Exception {
}
}
public class Demo extends ClassA {
Demo() throws Exception {
super();
}
public static void main(String[] args) {
try {
Demo d = new Demo(); // Handle exception here.
} catch (Exception e) {
e.printStackTrace();
}
}
}
A: ClassB should have a static method
public static ClassB makeClassB() {
try {
return new ClassB();
}
catch(Exception exc) {
// whatever logic you are currently performing to swallow
// presumably you have some default ClassB to return as part of this logic?
}
that will wrap the construction of ClassB with a try/catch. Client code will call makeClassB() and the constructor to ClassB will be private and throwing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13481943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: want to stop users entering invalid email addresses into form I would like to be able to run a php validate script to stop users form entering gibberish as their email address. I know we can have the form input type as email but that can be easily bypassed in developer tools and the database integrity damaged.
My insert page looks like this:
$email = $conn->real_escape_string($_POST['emailpost']);
$password = $conn->real_escape_string($_POST['passpost']);
$firstname = $conn->real_escape_string($_POST['firstnamepost']);
$lastname = $conn->real_escape_string($_POST['lastnamepost']);
$phonenumber = $conn->real_escape_string($_POST['phonenumberpost']);
$education = $conn->real_escape_string($_POST['institutionpost']);
$facebook = $conn->real_escape_string($_POST['facebookpost']);
$twitter = $conn->real_escape_string($_POST['twitterpost']);
$instagram = $conn->real_escape_string($_POST['instagrampost']);
$filename = $_FILES['uploadprofileimg']['name'];
$filename = $ran.$filename;
$filetmp = $_FILES['uploadprofileimg']['tmp_name'];
$filetype = $_FILES['uploadprofileimg']['type'];
move_uploaded_file($filetmp, "../userimages/".$filename);
$insertuser = "INSERT INTO elmtree_users (user, email, pw, firstName, lastName, profileimg, learninginstitute, phone, facebook, twitter, instagram) VALUES
('$username', '$email', '$password', '$firstname', '$lastname', '$filename', '$education', '$phonenumber', '$facebook', '$twitter', '$instagram')";
$resultinsert = $conn -> query($insertuser);
if(!$resultinsert){
echo $conn->error;
}else{
echo "<h2> Account successfully registered!</h2>
<h4>Please <a href='login.php'> <font class='text-success'><strong>login.</strong></font></a></h4><br><br><br><br>";
A: Like everyone is pointing out
making your own logging system is tricky. it required you to do additional steps to make the content secured. Not only to hackers but you as administrator of the database shouldn't have access to see your customers password in PlainText Most users will use the same password on your site as they used for there email password they registered with on your site..
It is more advisable to create login tools like laravel, Or simply research how to build a secure login system, because what we are seeing here in your code, is BAD, Not syntactically, but from a security stand point.
Me knowing you store passwords like that, I wouldn't register onto your website.
Any how not only that, But you really should have a look into mysqli binding
Or even, and something I like better is PDO_Mysql
Your code will not only be more clear to read, but will bind values directly to a a field within mysql ( no need to use real_escape_string no more )
Now to actually answer your question.
You probably should make some kind of javascript live validator on the field of your form directly.
then on PHP side, You can do a simple condition with REGXP and preg_match()
Have a look at https://regex101.com/r/SOgUIV/1 this is a regex that will validate EMAILs.
With this link, You should then experiment a bit with it, it has not only documentation on the side but also possibles quantifier and such.
if(preg_match("/^((?!\.)[\w-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$/i",trim($_POST['Email']))){
//What ever is in here will get process when $_POST['emailpost'] is valid.
}
Edited ----
As some user pointed out in comments.
You would probably be better of using
if(filter_var($_POST['emailpost'],FILTER_VALIDATE_EMAIL){
//What ever is in here will get process when $_POST['emailpost'] is valid
}
Also if you want to make sure user has access to the email address account, You could also add two column within your users table, isConfirmed,ConfirmationCode
When the user register, You create a unique code and put it into ConfirmationCode then send the user an email with something along those line "Please click the following link to activate account www.yourWebSite.com/confirmationPage.php?Code=$TheActualCodeYouCreatedForThatUser"
Then once user get to that page, Change the field isConfirmed to '1' or true.
Once there on your website, you will be able to assume that only emails with isConfirmed is a real user.
A: To validate email you need to check a lot of stuff like
*
*if the email already exists
*if its a real email i.e check for presence of @
*check for funny characters which are not supposed to be in an email.
then always encrypt your password
if ($_POST['submit']) {
$errors = array();
$email = $conn->real_escape_string($_POST['emailpost']);
$password = $conn->real_escape_string($_POST['passpost']);
$firstname = $conn->real_escape_string($_POST['firstnamepost']);
$lastname = $conn->real_escape_string($_POST['lastnamepost']);
$phonenumber = $conn->real_escape_string($_POST['phonenumberpost']);
$education = $conn->real_escape_string($_POST['institutionpost']);
$facebook = $conn->real_escape_string($_POST['facebookpost']);
$twitter = $conn->real_escape_string($_POST['twitterpost']);
$instagram = $conn->real_escape_string($_POST['instagrampost']);
$filename = $_FILES['uploadprofileimg']['name'];
$filename = $ran.$filename;
$filetmp = $_FILES['uploadprofileimg']['tmp_name'];
$filetype = $_FILES['uploadprofileimg']['type'];
move_uploaded_file($filetmp, "../userimages/".$filename);
if (strlen($email) && strlen($password) && strlen($firstname) && strlen($lastname) && strlen($phonenumber) && strlen($education) && strlen($facebook) && strlen($twitter) && strlen($instagram)) {
//check for a valid email
if(preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^",$email))
$errors['email'] = 'invalid email address';
//check for presence of @ in email
if (!stristr($em,"@") OR !stristr($em,".") $errors['email'] = 'please enter an email';
//echeck if email already exists in database
$checkemail = $conn->get_row("SELECT * FROM elmtree_users WHERE email=".$email);
if( $conn->num_rows( $checkemail ) > 0 ) $errors['email'] = "User already exists with the email: " . $email;
//validate password
$minpasslen = 8;
if (strlen($password) < $minpasslen)
$errors['email'] = 'password is too short';
$finalpassword = MD5($password);
if (empty($errors)) {
$insertuser = "INSERT INTO elmtree_users (user, email, pw, firstName, lastName, profileimg, learninginstitute, phone, facebook, twitter, instagram) VALUES
('$username', '$email', '$finalpassword', '$firstname', '$lastname', '$filename', '$education', '$phonenumber', '$facebook', '$twitter', '$instagram')";
$resultinsert = $conn -> query($insertuser);
if(!$resultinsert){
echo $conn->error;
} else {
echo "<h2> Account successfully registered!</h2>
<h4>Please <a href='login.php'> <font class='text-success'><strong>login.</strong></font></a></h4><br><br><br><br>";
} else {
echo implode('<br>', $errors);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55349091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sort the hashset based on date How can i sort the data inside a hashset based on date
I have a program in which i will get the data from mongodb in this format 2015-01-17 and later i will convert it to MMM dd yyyy format and now how can i sort the data here ??
This is my program
public class MyObject {
public static void main(String args[]) {
String sym = "BAC";
Set<String> set = myDAO.getInstance().getMeAllExpirationDates(sym);
for (String String : set) {
System.out.println(String);
}
}
public Set<String> getMeAllExpirationDates(String sym) throws Exception {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMM dd yyyy");
Set<String> set = new HashSet<String>();
BasicDBObject query = new BasicDBObject();
query.put("symbol", sym);
Security sec = null;
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
sec = (Security) cursor.next();
Date date = sdf1.parse(sec.getTkExpirationDate());
String result = sdf2.format(date);
set.add(result);
}
return set;
}
}
A: HashSet is an unordered collection - its elements are not stored in any particular order. You can regard HashSet as a bag that contains items - the items are all in the bag, but not in any particular order.
If you want a Set that contains elements in a specific order, use an implementation of SortedSet, for example TreeSet, instead of HashSet.
TreeSet by default stores its elements in "natural order", if you want a different order you can use the TreeSet constructor that takes a Comparator; supply your own Comparator that defines the order you want the elements to be sorted in.
A: The easiest was is to use a Comparator. You will need to implement the Comparable interface in your objects to tell them how dates relate to each other. See Telling HashSet how to sort the data for a concrete answer to your question.
A: You should use the implmentation LinkedHashSet to keep the order of insertion
replace
Set<String> set = new HashSet<String>();
with
Set<String> set = new LinkedHashSet<String>();
Better yet, use a TreeSet with a custom Comparator and sort the entries while adding them right away.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18891876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Make div stick at the bottom even if scroll it I am implementing a footer which should stick at the bottom of the window even if I scroll. And the scroll bar for the content above footer should be within content itself (not extending to footer).
Is there a way of doing this? Thanks.
A: Set CSS for your footer element:
.footer{
position: fixed;
bottom: 0;
left: 0;
width: 100%;
}
A: .footer{
position: fixed;
bottom: 0;
left: 0;
width: 100%;
}
works mostly fine! BUT, if you really want in to be sticky, you should use for example iScroll (http://iscrolljs.com) With iScroll you have only one area to scroll and headers and footers can't be scrolled!
A: You have a viewport in which you can draw (layout) your page, and you can't draw outside of it. The scroll bar is a control/decoration on the window itself, and you can't cover it.
What you can do is avoid having a scrollbar on the window, and have one on your main content instead.
Set both the footer and the main content positions, and make the main content scrollable with overflow: scroll — that way the scroll bar is attached to the content div instead of the browser window.
The footer won't have the scroll bar next to it then, but there may be reserved space on the right. That is out of your control — it is up to the browser vendor.
It will look like this (I'm using IDs in place of Classes):
#content {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 90%;
overflow: scroll;
}
#footer {
background: white;
position: fixed;
bottom: 0;
left: 0;
width: 100%;
height: 10%;
}
<div id="content">
This is the content area. It will have lots of vertical space so that it can scroll.<br>
<br>
a<br><br>
b<br><br>
c<br><br>
d<br><br>
e<br><br>
f<br><br>
g<br><br>
h<br><br>
i<br><br>
j<br><br>
k<br><br>
l<br><br>
m<br><br>
n<br><br>
o<br><br>
p<br><br>
</div>
<div id="footer">
This is the footer part and may have <em>the fine print</em> and/or navigation links; whatever you like.
</div>
... or see this fiddle demonstrating it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37795011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Google Sheets: Convert Horizontal Transaction Data into Chronological Statement + Combining Columns of Data On a sheet named, "Performance," I have data concerning stock trades in a row like so:
A B C D E F G H I J
1 TICKER TRADE OPEN DATE TRADE CLOSED DATE SHARES AVG BUY INVESTMENT AVG SALE PROCEEDS PROFIT/LOSS ROIC:
2 ABC 01/05/22 03/31/22 107 $14.22 -$1,521.54 $15.00 $1,605.00 $83.46 5.49%
3 BCA 01/05/22 03/31/22 344 $14.52 -$4,994.88 $15.00 $5,160.00 $165.12 3.31%
4 CAB 01/05/22 03/31/22 526 $12.55 -$6,601.30 $13.00 $6,838.00 $236.70 3.59%
... and so forth ...
Within the same workbook but on a separate sheet named, "Contributions/Withdrawals," I have a list of contributions and withdrawals like so:
A B
1 DATE AMOUNT
2 01/05/22 $700.00
3 02/05/22 $700.00
4 03/05/22 $400.00
5 03/15/22 -$7,000.00
... and so forth ...
I need to convert the first table of trade transactions into a vertical column format exactly like what is in the Contributions/Withdrawals table. (Note that each trade transaction actually represents two transactions, one for opening with its own date, and one for closing with its date.) Finally, I need to stack both tables of transactions in date order to make a combined chronological list of transactions so that I can run an XIRR formula on it.
The resulting table on a sheet named, "Cash Flows," needs to look like this:
A B
1 DATE AMOUNT
2 01/05/22 -$1,521.54
3 01/05/22 -$4,994.88
4 01/05/22 -$6,601.30
5 01/05/22 $700.00
6 02/05/22 $700.00
7 03/05/22 $700.00
8 03/10/22 $400.00
9 03/15/22 -$7000.00
10 03/31/22 $1,605.00
11 03/31/22 $5,160.00
12 03/31/22 $6,838.00
Using the following in cell A2 and B2...
A2 =SORT({Performance!$B$2:$B;Performance!$C$2:$C;'Contributions/Withdrawals'!$A$2:$A})
B2 =SORT({Performance!$F$2:$F;Performance!$H$2:$H;'Contributions/Withdrawals'!$B$2:$B})
...almost gets me there, but the transactions are not lining up with the correct dates. Google Sheets is ordering the amounts from smallest to largest. What I end up with is this:
A B
1 DATE AMOUNT
2 01/05/22 -$7,000.00
3 01/05/22 -$6,602.72
4 01/05/22 -$6,602.39
5 01/05/22 -$6,601.30
6 01/05/22 -$6,596.40
7 01/05/22 -$6,587.10
8 01/05/22 -$4,994.88
9 01/05/22 -$3,315.26
10 01/05/22 -$3,284.91
11 01/05/22 -$1,521.54
12 02/05/22 $400.00
13 03/05/22 $700.00
14 03/10/22 $700.00
15 03/15/22 $700.00
16 03/31/22 $1,605.00
17 03/31/22 $3.249.00
18 03/31/22 $3,731.00
19 03/31/22 $5,160.00
20 03/31/22 $6,348.00
21 03/31/22 $6,532.00
22 03/31/22 $6,786.00
23 03/31/22 $6,838.00
Any help would be appreciated. Thanks!
A: You are very close indeed! You should join both ranges in order to sort them by the first column:
=SORT({Performance!$B$2:$B;Performance!$C$2:$C;'Contributions/Withdrawals'!$A$2:$A,Performance!$F$2:$F;Performance!$H$2:$H;'Contributions/Withdrawals'!$B$2:$B})
(You may need to change that only comma to a inverted slash if you have another locale settings)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75027860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: javasript in angular 8 There's a solution on js -
codepen.io/skovtun/pen/VwLvXPB
Can't make an analog for Angular8+.
I need the center block to have a fixed width (1200px), and it is evaluated and compressed by the left, right and both sidebars immediately when they are opened. They should not overlap with the content.
A: I seen content overlapping when closing sidebars. May be you want to stop overlapping during open and close sidebar. It can be fixed by css. You can use transition in .wrapper class. see bellow code:
.wrapper{
height: 100%;
transition:all .25s;
}
A: You can achieve this with pure CSS.
You haven't specified what the requirements are, but you can use flexbox like the below example to achieve a max-width main container flanked by 2 compressing sidebars.
body {
margin: 0;
}
.wrapper{
display: flex;
}
main {
width: 1200px;
padding: 20px;
background-color: #f1f1f1;
}
.sidebar {
flex-grow: 1;
height: 100vh;
padding: 0 15px;
}
.sidebar-left {
border-right: 1px solid #06A52B;
}
.sidebar-right {
border-left: 1px solid #06A52B;
}
<div class="wrapper">
<aside class="sidebar sidebar-left">
<h2>Left sidebar</h2>
<p>Add content here</p>
</aside>
<main>
<h1>Max width of this block is 1200px</h1>
</main>
<aside class="sidebar sidebar-right">
<h2>Right sidebar</h2>
<p>Add content here</p>
</aside>
</div>
A: You Can Dynamic every css class Using [ngClass] Depending on your logic ..it will render when the value will change..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60297175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Axon Distributed Command Bus on Docker Swarm We use Axon and I am trying to make a distributed command bus for one of our services Deployed on Docker Swarm.
Anyone already have experiance/tips for setting this up?
We are using:
*
*Axon
*Docker Swarm
*Spring-Boot
And I want to use JGroups icw DNSPING for the distributed setup.
Regards,
Johan.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46033125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Recursive Fibonacci using BigInteger in Java I'm trying to solve a project euler 25 problem in java and since I need something to store numbers with 10000 digits, I'm using BigInteger classes.
So I'm working in some recursive fibonacci sequence using BigIntegers and I'm trying to convert this code:
public int fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
from this link: Java recursive Fibonacci sequence
to the same code, but using BigIntegers.
So, this is what I have so far:
public static BigInteger fibonacci(BigInteger index) {
if (index.compareTo(BigInteger.ZERO) == 0)
return BigInteger.ZERO;
else if (index.compareTo(BigInteger.valueOf(1)) == 1)
return BigInteger.ONE;
else
return fibonacci(index.subtract(BigInteger.ONE)).add(fibonacci(index.subtract(BigInteger.valueOf(2))));
}
public static int numberOfDigits(BigInteger fibonacci) {
return Integer.valueOf(fibonacci.toString().length());
}
public static void main(String[] args) {
long startTime = System.nanoTime();
for (BigInteger i = new BigInteger("1"); numberOfDigits(fibonacci(i)) <= 1000; i = i.add(BigInteger.ONE))
System.out.println(" " + i + " - " + fibonacci(i) + " - " + numberOfDigits(fibonacci(i)));
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("Duration: " + duration/1000000 + " ms");
}
When I run it, I get a StackOverFlowError, like this:
Exception in thread "main" java.lang.StackOverflowError
at java.math.BigInteger.subtract(BigInteger.java:1423)
at Problem25Part2.fibonacci(Problem25Part2.java:19)
at Problem25Part2.fibonacci(Problem25Part2.java:19)
at Problem25Part2.fibonacci(Problem25Part2.java:19)
at Problem25Part2.fibonacci(Problem25Part2.java:19)
And it repeats I think 1000 times.
Well, I have no idea what is wrong, so please can you guys help me? Thank you!
A: When you use compare() it returns 1 if argument is higher than actual.
So you should change this piece of code:
else if (index.compareTo(BigInteger.valueOf(1)) == 1)
for this:
else if (index.compareTo(BigInteger.valueOf(1)) == 0)
A: Java doesn't deal too well with deep recursion. You should convert to using a loop instead.
Also see this thread on tail recursion: https://softwareengineering.stackexchange.com/questions/272061/why-doesnt-java-have-optimization-for-tail-recursion-at-all
A: I think You have standard problem with recursion... It's a problem with method fibonacci, because You have no places, when this method must return final result, so please check your condition and more about compare in BigInteger. Recommends also read about tail recursion
A: You could try to use dynamic programming to reduce space complexity. Something like this should work:
public static BigInteger fibonacci(BigInteger n) {
if (n.compareTo(BigInteger.valueOf(3L)) < 0) {
return BigInteger.ONE;
}
//Map to store the previous results
Map<BigInteger, BigInteger> computedValues = new HashMap<BigInteger, BigInteger>();
//The two edge cases
computedValues.put(BigInteger.ONE, BigInteger.ONE);
computedValues.put(BigInteger.valueOf(2L), BigInteger.ONE);
return fibonacci(n, computedValues);
}
private static BigInteger fibonacci(BigInteger n, Map<BigInteger, BigInteger> computedValues) {
if (computedValues.containsKey(n))
return computedValues.get(n);
BigInteger n1 = n.subtract(BigInteger.ONE);
BigInteger n2 = n.subtract(BigInteger.ONE).subtract(BigInteger.ONE);
computedValues.put(n1, fibonacci(n1, computedValues));
computedValues.put(n2, fibonacci(n2, computedValues));
BigInteger newValue = computedValues.get(n1).add(computedValues.get(n2));
computedValues.put(n, newValue);
return newValue;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41284354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Creating a Send Port through BTS Management API I'm trying to create a Send Port using the BizTalk Management API (from BizTalk 2016, feature pack 2).
But I have the following issue: a Send Port has a PrimaryTransport (standard on Send Ports) and a SecondaryTransport (in BizTalk UI: Backup Transport).
The SecondaryTransport will be based on an optional URL.
I can create the Send Port with the SecondaryTransport being null (using both Swagger and C#), showing the following:
But I can't update the Send Port afterwards as I'm getting the following when I try setting the SecondaryTransport/Backup Transport through C# or Swagger or BizTalk's UI
I've tried putting "None", "", "NONE", "" as TransportType, but those aren't valid adapters.
This is the configuration in Swagger for the SecondaryTransport itself:
"SecondaryTransport": {
"Address":"",
"TransportType": "NONE",
"TransportTypeData": null,
"SendHandler": "BizTalkServerApplication",
"RetryCount": 3,
"RetryInterval": 5,
"OrderedDelivery": false,
"Schedule": {
"ServiceWindowEnabled": false,
"FromTime": "2018-07-22T22:00:00",
"ToTime": "2018-07-23T21:59:59"
}
},
Does anyone have any experience on what I could fill in to be able to fill in my Backup Transport afterwards? (And so it doesn't look like it doesn't have any options anymore)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51501639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to prevent a hacker accessing user session from outside? We have a website that use CodeIgniter. We use Facebook SDK to connect and store the token in a session variable. We have controller functions that are called by AJAX code and create entry in our data base. But to create the entry a session variable should be valid.
Recently someone found a way to attack us and pretend that he has a valid session and call these functions and create many data base entries in our website. We are now forced to close the website to make some change to prevent that.
But we are not PHP programmers, we are C/C++ programmers and don't know how the person did that. We know that he used curl library 7.43.0.
Can someone help us please to correct our code? By the way we are not a HTTPS website.
Here is the session configuration for CodeIgniter:
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 1800;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 60;
$config['sess_regenerate_destroy'] = TRUE;
Here is cookies configuration:
$config['cookie_prefix'] = 'liftoffre_';
$config['cookie_domain'] = $domain;
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
Here is the code we use to verify a session before creating an entry on database:
public function create_offer()
{
if($this->session->userdata('token') != null)
{
$titre = "Nouvelle offre";
$data = array(
'userGraph' => $this->session->userdata('userData'),
'titre' => $titre
);
$this->load->view('nouvelle_offre', $data);
}
else
{
redirect('/main/');
}
}
public function ajouter_offre()
{
if($this->session->userdata('token') != null) {
$data = array(
'offre_departure_name' => $this->input->post('offre_departure_name', TRUE),
'offre_departure_adresse' => $this->input->post('offre_departure_adresse', TRUE),
'offre_departure_province' => $this->input->post('offre_departure_province', TRUE),
'offre_departure_city' => $this->input->post('offre_departure_city', TRUE),
'offre_arrival_name' => $this->input->post('offre_arrival_name', TRUE),
'offre_arrival_adresse' => $this->input->post('offre_arrival_adresse', TRUE),
'offre_arrival_province' => $this->input->post('offre_arrival_province', TRUE),
'offre_arrival_city' => $this->input->post('offre_arrival_city', TRUE),
'offre_datetime' => $this->input->post('offre_datetime', TRUE),
'offre_price' => $this->input->post('offre_price', TRUE),
'offre_seats_number' => $this->input->post('offre_seats_number', TRUE),
'offre_userid' => $this->input->post('offre_userid', TRUE),
'offre_commentaire' => $this->input->post('offre_commentaire', TRUE),
);
$this->load->model('Datasource');
$this->Datasource->add_offer($data);
}
else
{
redirect('/main/');
}
}
These two function can be called by using a POST method and calling link like domain.com/index.php/controller/function.
Here a log from the server
209.222.7.236 - - [27/Jun/2016:06:50:33 -0700] "POST /index.php/nouvelleoffre/ajouter_offre/ HTTP/1.1" 200 - "-" "curl/7.43.0"
Does someone know how to help us?
A: CodeIgniter, though unarguably one of the best PHP frameworks to be developed, had a problem of not properly storing sessions, i.e. it was noted for storing the SESSION data in the COOKIE, only in encrypted format. Thus with sufficient knowledge about your system and the hashing algorithm used, an attacker could've transformed all cookie data to session data. This problem was solved, however before CodeIgniter v3 was released.
But I believe the best way to store sessions may be:
1. Do not autoload the session class, but rather load them whenever you need them.
2. Define a basepath or exit, i.e. defined('BASEPATH') or exit('No direct script access allowed')
3. Though an overstretch, I recommend setting an encryption key and encrypting every session value before you store it (remember to set a strong encryption key password)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38061589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MIDI Sequencer stop without flushing For a project I am working on I need to pause the midi sequencer and I want all the sounding notes to sustain and thus make those notes endless. The problem I am facing is that sequencer.stop() apparently not only stops the playback, but also sends MIDI note off messages to all sounding notes, terminating all sounding notes (in some literature refered to as flushing).
I have tried to use sequencer.setTempoInBPM(0) and that gets the job done, but has other unwanted side-effects specific to my project.
The most obvious solution then seems overriding Sequencer.stop(), but how do I do that? And how exactly will that overridden method look like?
Edit:
I would like to edit the question in response to the comment of gpasch.
not only stops the playback, but also sends MIDI note off messages to
all sounding notes: what are you talking about?? isnt this the same
thing??
That is true for audio, but that is not true for MIDI. The MIDI protocol doesnt specify any audio data by itself. It only gives instructions to a musical instruments on what to play. The instrument interprets the MIDI messages and makes the final sound.
In order to let an instrument play a sound of one second, this are the actions:
*
*[Sequencer] MIDI Message Out: note on
*[Instrument] MIDI Message In: note on
*[Instrument] Starts interpreting note on: starts producing sound
*[Sequencer] Waits one second
*[Sequencer] MIDI Message Out: note off
*[Instrument] MIDI Message In: note off
*[Instrument] Starts interpreting note off: stops producing sound
So, if this process gets interrupted on step 4, it would create an "endless note". Because the MIDI instrument got instructions to begin playing a certain note, but never got an instruction to stop playing that note. [*]
Looking back to my question. When I call sequencer.stop() in the middle of a note (step 4), instead of having an "endless note", all notes that are being played on that moment that did not yet have got an note off message, stop sounding. The logical explenation for that, is that sequencer.stop() sends a MIDI All Note Off message under the hood. We can be really thankfull for that, because otherwhise sequencer.stop() would be a real mess. In my particular case though I really need the sequencer to not send the note off message. So the question is: can I make a workaround for that?
*
If it is a piano sound with a natural decay of the sound, the sound will eventually die. But with a synth sound the sound will persist till there has been
A: The way I would do it is. Create a filter which would basically receive everything sent from the sequencer and send it to your midi out. Inside this filter create a condition where if the "pause flag" is true all note offs would be received but not sent.
Create a pause() method which when called first sets your "pause flag" to true and then does sequencer.stop().
Of course you would need some way to keep track of the note offs that have been blocked so that you can actually stop them when you eventually do want to or else they will really stay on for ever.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36454662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DNN9 site expiry date How can I edit site expiry date in a new management panel in DotNetNuke 9? There is a field in the database for it and if it's set to a date passed the site becomes unavailable, as expected. But I haven't found a field to change it in the new interface
A: I haven't found it in the Persona Bar, but you can still get to the old site settings, try throwing this on the URL
/Admin/Site-Settings
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41299160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Asp.Net Treeview ImageSet Trouble http://www.imageupload.co.uk/5JwE
Treeview imageset is broken.
Anyone knows how to solve this? I don't want to create entire project from zero. Help me please :(
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27465790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Columns having nulls are not shown when a row is unpivoted I have come to a rather strange sort of an issue. I have a row as follows in SQL Server:
Row number ITEMTYPE LIFECYCLEPHASE DESCRIPTION ITEMCATEGORY size PRODUCTLINES REV REVINCORPDATE REVRELEASEDATE EFFECTIVITYDATE SHIPPABLEITEM EXCLUDEFROMROLLUP COMPLIANCECALCULATEDDATE OVERALLCOMPLIANCE ITEMGROUPS MODELREF COMMODITY list07 text13 text12 text07 text01 CREATEUSER date01 list10 list09 list13 list24 text17 text24 text25 multiList01 multiList04 list17 numeric01 list03 list06 list25 list14 numeric03 numeric02 text21 list15 text11 text19 text20 date02 multiList02 list01 multiList03 list19 list20 text02 multiList05 list21 list22 text23 text03 text04 text05 money02 list12 list16 list11 list18
1 .6C12PXMZ Fastener, Purchased Obsolete SCREW,PAN, PHI M6X12 Normal MRP Purchased Part PC NS-MISC X1 GOLIVE_0001 NULL 2007-04-25 06:00:00.0000000 2007-04-25 06:00:00.0000000 No 0 NULL NULL NULL NULL Fastener, Purchased No NULL NULL 0 NULL Fallon, Dermot(**dfallon) NULL NULL 0369 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NS-MISC NULL RA RA 2-MS1-7A NULL NULL NULL NULL NULL 0 0 NULL NULL NULL NULL NULL
When I unpivot this row. It should show 66 rows and 3 columns, if the below query is used to unpivot above mentioned row.
Select ROW
,ColumnName
, ColumnValue
--INTO ##TITLE_BLOCK_PARTS_T
FROM
(
Select
ROW,
CAST([number] AS VARCHAR(8000))AS number,
CAST([ITEMTYPE] AS VARCHAR(8000))AS ITEMTYPE,
CAST([LIFECYCLEPHASE] AS VARCHAR(8000))AS LIFECYCLEPHASE,
CAST([DESCRIPTION] AS VARCHAR(8000))AS DESCRIPTION,
CAST([ITEMCATEGORY] AS VARCHAR(8000))AS ITEMCATEGORY,
CAST([size] AS VARCHAR(8000))AS size,
CAST([PRODUCTLINES] AS VARCHAR(8000))AS PRODUCTLINES,
CAST([REV] AS VARCHAR(8000))AS REV,
CAST([REVINCORPDATE] AS VARCHAR(8000))AS REVINCORPDATE,
CAST([REVRELEASEDATE] AS VARCHAR(8000))AS REVRELEASEDATE,
CAST([EFFECTIVITYDATE] AS VARCHAR(8000))AS EFFECTIVITYDATE,
CAST([SHIPPABLEITEM] AS VARCHAR(8000))AS SHIPPABLEITEM,
CAST([EXCLUDEFROMROLLUP] AS VARCHAR(8000))AS EXCLUDEFROMROLLUP,
CAST([COMPLIANCECALCULATEDDATE] AS VARCHAR(8000))AS COMPLIANCECALCULATEDDATE,
CAST([OVERALLCOMPLIANCE] AS VARCHAR(8000))AS OVERALLCOMPLIANCE,
CAST([ITEMGROUPS] AS VARCHAR(8000))AS ITEMGROUPS,
CAST([MODELREF] AS VARCHAR(8000))AS MODELREF,
CAST([COMMODITY] AS VARCHAR(8000))AS COMMODITY,
CAST([list07] AS VARCHAR(8000))AS list07,
CAST([text13] AS VARCHAR(8000))AS text13,
CAST([text12] AS VARCHAR(8000))AS text12,
CAST([text07] AS VARCHAR(8000))AS text07,
CAST([text01] AS VARCHAR(8000))AS text01,
CAST([CREATEUSER] AS VARCHAR(8000))AS CREATEUSER,
CAST([date01] AS VARCHAR(8000))AS date01,
CAST([list10] AS VARCHAR(8000))AS list10,
CAST([list09] AS VARCHAR(8000))AS list09,
CAST([list13] AS VARCHAR(8000))AS list13,
CAST([list24] AS VARCHAR(8000))AS list24,
CAST([text17] AS VARCHAR(8000))AS text17,
CAST([text24] AS VARCHAR(8000))AS text24,
CAST([text25] AS VARCHAR(8000))AS text25,
CAST([multiList01] AS VARCHAR(8000))AS multiList01,
CAST([multiList04] AS VARCHAR(8000))AS multiList04,
CAST([list17] AS VARCHAR(8000))AS list17,
CAST([numeric01] AS VARCHAR(8000))AS numeric01,
CAST([list03] AS VARCHAR(8000))AS list03,
CAST([list06] AS VARCHAR(8000))AS list06,
CAST([list25] AS VARCHAR(8000))AS list25,
CAST([list14] AS VARCHAR(8000))AS list14,
CAST([numeric03] AS VARCHAR(8000))AS numeric03,
CAST([numeric02] AS VARCHAR(8000))AS numeric02,
CAST([text21] AS VARCHAR(8000))AS text21,
CAST([list15] AS VARCHAR(8000))AS list15,
CAST([text11] AS VARCHAR(8000))AS text11,
CAST([text19] AS VARCHAR(8000))AS text19,
CAST([text20] AS VARCHAR(8000))AS text20,
CAST([date02] AS VARCHAR(8000))AS date02,
CAST([multiList02] AS VARCHAR(8000))AS multiList02,
CAST([list01] AS VARCHAR(8000))AS list01,
CAST([multiList03] AS VARCHAR(8000))AS multiList03,
CAST([list19 ] AS VARCHAR(8000))AS list19,
CAST([list20] AS VARCHAR(8000))AS list20,
CAST([text02] AS VARCHAR(8000))AS text02,
CAST([multiList05] AS VARCHAR(8000))AS multiList05,
CAST([list21] AS VARCHAR(8000))AS list21,
CAST([list22] AS VARCHAR(8000))AS list22,
CAST([text23] AS VARCHAR(8000))AS text23,
CAST([text03] AS VARCHAR(8000))AS text03,
CAST([text04] AS VARCHAR(8000))AS text04,
CAST([text05] AS VARCHAR(8000))AS text05,
CAST([money02] AS VARCHAR(8000))AS money02,
CAST([list12] AS VARCHAR(8000))AS list12,
CAST([list16] AS VARCHAR(8000))AS list16,
CAST([list11] AS VARCHAR(8000))AS list11,
CAST([list18] AS VARCHAR(8000))AS list18
from
##TITLE_BLOCK_PARTS_T_ORI
)t
UNPIVOT (ColumnValue for ColumnName
IN (
number,
ITEMTYPE,
LIFECYCLEPHASE,
DESCRIPTION,
ITEMCATEGORY,
size,
PRODUCTLINES,
REV,
REVINCORPDATE,
REVRELEASEDATE,
EFFECTIVITYDATE,
SHIPPABLEITEM,
EXCLUDEFROMROLLUP,
COMPLIANCECALCULATEDDATE,
OVERALLCOMPLIANCE,
ITEMGROUPS,
MODELREF,
COMMODITY,
list07,
text13,
text12,
text07,
text01,
CREATEUSER,
date01,
list10,
list09,
list13,
list24,
text17,
text24,
text25,
multiList01,
multiList04,
list17,
numeric01,
list03,
list06,
list25,
list14,
numeric03,
numeric02,
text21,
list15,
text11,
text19,
text20,
date02,
multiList02,
list01,
multiList03,
list19,
list20,
text02,
multiList05,
list21,
list22,
text23,
text03,
text04,
text05,
money02,
list12,
list16,
list11,
list18
)
)UP
I have tested above scenario in a 2012 instance and in 2008 instance. In 2012 the result set is as expected but somehow all the columns having null values are ignored in SQL Server 2008 instance.
Result set in 2012 is:
Row ColumnName ColumnValue
1 number 000-0267-00
1 ITEMTYPE Assemblies, General
1 LIFECYCLEPHASE Obsolete
1 DESCRIPTION E1 ECHO CANCELLER
1 ITEMCATEGORY Normal MRP Purchased Part
1 size PC
1 PRODUCTLINES NS-MISC
1 REV OB GOLIVE_0001
1 REVINCORPDATE
1 REVRELEASEDATE 25-APR-07
1 EFFECTIVITYDATE 25-APR-07
1 SHIPPABLEITEM No
1 EXCLUDEFROMROLLUP 0
1 COMPLIANCECALCULATEDDATE Dec 30 1899 12:00AM
1 OVERALLCOMPLIANCE 0
1 ITEMGROUPS
1 MODELREF
1 COMMODITY Assemblies, General
1 list07 No
1 text13
1 text12
1 text07 45
1 text01
1 CREATEUSER Fallon, Dermot(**dfallon)
1 date01
1 list10
1 list09 0369
1 list13
1 list24
1 text17
1 text24
1 text25
1 multiList01
1 multiList04
1 list17
1 numeric01 0
1 list03
1 list06
1 list25
1 list14
1 numeric03 0
1 numeric02 0
1 text21
1 list15
1 text11
1 text19
1 text20
1 date02
1 multiList02
1 list01 NS-MISC
1 multiList03 NS
1 list19 RA
1 list20 RA
1 text02 2-MS1-7A
1 multiList05 Yes
1 list21
1 list22
1 text23
1 text03
1 text04 0
1 text05 2
1 money02 0
1 list12
1 list16
1 list11
1 list18
Result set in 2008 is:
ROW ColumnName ColumnValue
1 number .6C12PXMZ
1 ITEMTYPE Fastener, Purchased
1 LIFECYCLEPHASE Obsolete
1 DESCRIPTION SCREW,PAN, PHI M6X12
1 ITEMCATEGORY Normal MRP Purchased Part
1 size PC
1 PRODUCTLINES NS-MISC
1 REV X1 GOLIVE_0001
1 REVRELEASEDATE 2007-04-25 06:00:00.0000000
1 EFFECTIVITYDATE 2007-04-25 06:00:00.0000000
1 SHIPPABLEITEM No
1 EXCLUDEFROMROLLUP 0
1 COMMODITY Fastener, Purchased
1 list07 No
1 text07 0
1 CREATEUSER Fallon, Dermot(**dfallon)
1 list09 0369
1 list01 NS-MISC
1 list19 RA
1 list20 RA
1 text02 2-MS1-7A
1 text04 0
1 text05 0
Can anybody tell me the reason behind such difference in both cases. I am totally lost on this one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38092742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Studio Firebase Notification Device to Device with Topics Sorry if this post was duplicated, but I could not find an answer in here, so I decided to post a new question.
Is there anyway I can do to easily send a notification from a device to other device in a specific topics with a single button ?
I know I successfully push a notification through firebase notification by its website in https://console.firebase.google.com/u/0/project/project/notification but I want to do it within my own device.
a full method would be very helpful for me.
mSendNotificationBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendNotificationToTopic("title","description","latestNews");
}
});
above is the example of my button.
UPDATE
After trying some codes, I decided to combine the notification manager with thread that listens to a firebase database, as follows
DatabaseReference mDatabaseNotification = FirebaseDatabase.getInstance().getReference().child("Notification");
String subscribedTopic = "news";
Thread thread = new Thread(){
@Override
public void run() {
mDatabaseNotification.child(subscribedTopic ).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot != null) {
if(dataSnapshot.child("title").getValue(String.class) != null && dataSnapshot.child("desc").getValue(String.class) != null) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(dataSnapshot.child("abc").child("title").getValue(String.class))
.setContentText(dataSnapshot.child("abc").child("desc").getValue(String.class));
int mNotificationId = 001;
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
}
};
thread.start();
and it works fine, I could subscribe the users by editing the subscribedTopic and listens to that database only even on background.
So, another question is, can this cause something bad later ?
UPDATE 2
I found a bug which the ValueEventListener triggered more than once even though the data changed...
UPDATE 3
Check my answer below
A: First, the user has to generate
String token = FirebaseInstanceId.getInstance().getToken(); and then store it in firebase database with userId as key or you can subscribe the user to any topic by FirebaseMessaging.getInstance().subscribeToTopic("topic");
To send notification you have to hit this api https://fcm.googleapis.com/fcm/send with headers "Authorization" your FCM key and Content-Type as "application/json" the request body should be
{
"to": "/topics or FCM id",
"priority": "high",
"notification": {
"title": "Your Title",
"text": "Your Text"
}
"data": {
"customId": "02",
"badge": 1,
"sound": "",
"alert": "Alert"
}
}
or you can Use okHttp which is not recommended method because your FCM key will be exposed and can be misused.
public class FcmNotifier {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static void sendNotification(final String body, final String title) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
JSONObject dataJson = new JSONObject();
dataJson.put("text", body);
dataJson.put("title", title);
dataJson.put("priority", "high");
json.put("notification", dataJson);
json.put("to", "/topics/topic");
RequestBody body = RequestBody.create(JSON, json.toString());
Request request = new Request.Builder()
.header("Authorization", "key=your FCM key")
.url("https://fcm.googleapis.com/fcm/send")
.post(body)
.build();
Response response = client.newCall(request).execute();
String finalResponse = response.body().string();
Log.i("kunwar", finalResponse);
} catch (Exception e) {
Log.i("kunwar",e.getMessage());
}
return null;
}
}.execute();
}
}
A: This is the simplest way I can achieve notification with android and the help of firebase database.
add this to AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<service android:name="YourNotificationService"></service>
<application>
<receiver android:name=".BootListener">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
</application>
and then make a java class that extends BroadcastReceiver for boot listener
public class BootListener extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
context.startService(new Intent(context, YourNotificationService.class));
}
}
and then make a java class that extends service to run your notification on background
public class YourNotificationService extends Service {
private DatabaseReference mDatabase;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent pIntent, int flags, int startId) {
mDatabase = /*your firebase*/
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
/* your code */
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
return super.onStartCommand(pIntent, flags, startId);
}
}
and you could combine this with SharedPreference or user information to listen to a specific firebase database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47357095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails 5.2.2 (active record) WITH statement I am using Rails 5.2.2 and have a complex query using a 'WITH' statement that I need to create with a left outer join.
How do I do a WITH statement in active record?
My TOTAL_PROFILES, is driven with a Query object and will change, while the rest will always be constant. So a basically want to wrap my query object results with the WITH statement.
Here is a simplified SQL example and hoping someone can guide me to the best way to accomplish this in rails, as I see no way to do it. I have a bunch of inner joins on the TOTAL_PROFILE table, but don't show them here.
WITH TOTAL_PROFILES
AS (
SELECT profiles.*
,hobbies.*
FROM profiles
INNER JOIN
"profiles"
ON "hobbies"."hobbyable_id" = "profiles"."id"
AND "hobbies"."hobbyable_type" = $1
WHERE (profiles.latitude ( BETWEEN 42.055160808444576
AND 42.19989259155542) )
)
, FAVORITE_FOR_USER
AS (
SELECT "favorites".*
FROM "favorites"
WHERE "favorites"."user_id" = $1
AND "favorites"."profile_id" = $2
ORDER BY
"favorites"."id" ASC LIMIT $3
)
SELECT F."user_id"
, CASE
WHEN F."profile_id" IS NULL
THEN 0
ELSE 1
END AS IS_FAVORITE_FOR_USER
, T.*
FROM
TOTAL_PROFILES T
LEFT JOIN
FAVORITE_FOR_USER F
ON T."profile_id" = F."profile_id"
How can this be converted into ActiveRecord, or Arel?
a_sql = ProfilesQuery::Search.call(:location => 'New York, NY').to_sql
params = []
params << User.first.id # 1
user_id_param = params.length
wrapper_query = <<~SQL
SELECT F."user_id"
, (F."profile_id" IS NOT NULL) AS IS_FAVORITE_FOR_USER
, T.*
FROM (#{a_sql}) T
LEFT JOIN favorites F ON (F.profile_id = T.profile_id AND F."user_id" = $#{user_id_param})
SQL
conn = ActiveRecord::Base.connection.raw_connection
conn.prepare('my_query', wrapper_query )
result = conn.exec_prepared('my_query', ['1'])``
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55561592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Templates in web.py I try to render a template with web.py and some seconds after another, I'm not too much into Python so I could need a little help :).
What I try to achive (return can be returned only once for sure, but I guess you'll get it what I mean)
class index:
def GET(self):
return render.formone('')
time.sleep(30)
return render.formtwo('')
So I need to get around that return somehow, but I have no idea how...
Thanks for answers!
A: Why would you want to render two forms at the same time? You simply cannot send two responses this way. Your script will end after first return.
If I understand you correctly, you want to serve two forms at the same time (meaning you want to join them)? If yes, then look at this example.
Basically you first render both forms
formone = render.formone('')
formtwo = render.formtwo('')
And then join them and send the response
return render.index(unicode(formone), unicode(formtwo))
If you don't want to serve them at the same time, this can't be done this way. You may do this via AJAX (ie event from webpage, send request and ask for second form after clicking on some element or whatever) or sending another standard non-async request (submitting first form).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25476877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript Button Not Redirecting I am trying to make a simple webpage with buttons that redirect to other subpages, all the HTML javascript, and CSS files are in the same folder. When I use the javascript code it just won't redirect when I click the button, anyone knows what is wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
<script src="script.js" type="text/javascript"></script>
</script>
<link href="styles.css" rel="stylesheet">
<title>About me</title>
</head>
<body>
<div class="title">
<h1 style="size: 22;">HOMEPAGE</h1>
</div>
<div class="btn-group blue">
<button id="general">General</button>
<button>2</button>
<button>3</button>
<button>4</button>
</div>
<div class="float-container">
<div class="float-child" style="border: white;">
<img src="https://api.time.com/wp-content/uploads/2014/03/improving-life-health-hiking-nature.jpg" alt="Picture of Hiker" style="width: 100%; padding: 5px;"/>
</div>
<div class="float-child">
<p>
Hello, welcome to my website.
</p>
</div>
</div>
</body>
</html>
And here is the Javascript.
document.addEventListener('DOMContentLoaded', function(){
let general = document.querySelector(".general");
general.addEventListener('click', function(){
window.location.replace("general.html");
});
});
Anyone notice anything?
I tried different ways of redirecting on W3 schools and none of it worked.
A: Because you have defined button by id not by class
<button id="general">General</button>
So change
let general = document.querySelector(".general");
to
let general = document.querySelector("#general");
document.addEventListener('DOMContentLoaded', function(){
let general = document.querySelector("#general");
general.addEventListener('click', function(){
window.location = "https://www.facebook.com";
return false;
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
<script src="script.js" type="text/javascript"></script>
</script>
<link href="styles.css" rel="stylesheet">
<title>About me</title>
</head>
<body>
<div class="title">
<h1 style="size: 22;">HOMEPAGE</h1>
</div>
<div class="btn-group blue">
<button id="general">General</button>
<button>2</button>
<button>3</button>
<button>4</button>
</div>
<div class="float-container">
<div class="float-child" style="border: white;">
<img src="https://api.time.com/wp-content/uploads/2014/03/improving-life-health-hiking-nature.jpg" alt="Picture of Hiker" style="width: 100%; padding: 5px;"/>
</div>
<div class="float-child">
<p>
Hello, welcome to my website.
</p>
</div>
</div>
</body>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74554879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Aggregate initialization of noncopyable base class I am constructing derived class from non-copyable base class. I would like to aggregate-initialize Base in the initializer:
// for convenience, could be any other way to disable copy
#include<boost/noncopyable.hpp>
struct Base: public boost::noncopyable{
int a;
};
struct Derived: public Base{
Derived(int a): Base{a} {}
};
but I am getting:
error: could not convert ‘a’ from ‘int’ to ‘boost::noncopyable_::noncopyable’
As I understand, noncopyable cannot be initialized, fair enough. Can I then somehow craft the aggregate initializer so that noncopyable initialization is skipped? (I tried e.g. things like Base{{},a} without real understanding, but that did not work either: ~noncopyable is protected).
Or will I need to explicitly define Base::Base which will skip the noncopyable initialization, using it from Derived::Derived instead of the aggregate initialization?
A: The aggregate initialization of the base class you tried
Derived(int a): Base{{}, a} {}
// ^^
Would have worked if the constructor of boost::noncopyable wasn't protected (see here).
The easiest fix should be to add a constructor to the base class.
#include <boost/core/noncopyable.hpp>
struct Base: private boost::noncopyable
{
int a;
Base(int a_) : a{a_} {}
};
struct Derived: public Base
{
Derived(int a): Base{a} {}
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61863580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JQUERY, i need to replace something i need to replace ' / ' from list of genres that i add by clicking checkboxes, the first one is added without ' / ' so when i uncheck them and replace it with nothing but the first one can't be replaced cause it don't have ' / ' in front of it. So how can i do the replace operation so it will replace and the first one! JSFiddle
$("input[type=checkbox]").click(function(){
var spacer
if(!$("#genre").val()){
spacer = "";
} else {
spacer = " / ";
}
if($(this).is(':checked')){
$("#genre").val($("#genre").val() + spacer + $(this).val());
} else {
$("#genre").val($("#genre").val().replace(' / ' + $(this).val(),""));
}
});
A: Hope this will be useful. The order of addition will not be preserve.
$("input[type=checkbox]").click(function () {
var checkList = [];
$("#genreslist").find("input").each(function () {
if (this.checked) checkList.push(this.value);
});
$("#genre").val(checkList.join("/"));
});
Fiddle : here
To preserve order you can do :
$("input[type=checkbox]").click(function(){
var spacer = "";
var value = $("#genre").val();
if($("#genre").val()){
spacer = " / ";
}
if($(this).is(':checked')){
$("#genre").val(value + spacer + $(this).val());
} else {
var endSpacer = "";
if(value.indexOf($(this).val()) == 0)
{
spacer="";
endSpacer = value.length > $(this).val().length ? " / " : "";
}
$("#genre").val($("#genre").val().replace(spacer + $(this).val() + endSpacer,""));
}
});
Fiddle : here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25833760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Does renaming a project in VS require me to change ALL occurrences of it's old name in the .sln file? I searched already on stackoverflow and on the internet but I couldn't find a similar specific question.
When i have to rename a already checked-in (tfs) project in my visual studio (2010-2013) solution, I always use a procedure similar to this one here in the accepted question:
stackoverflow.com/questions/2043618/proper-way-to-rename-solution-and-directories-in-visual-studio
Here is the important snippet from there (thanks to author):
*
*Close Visual Studio.
*Create a backup of your .sln file (you can always roll back).
*Imagine you want to rename directory "Project1" to "Project2".
*If not using source control, rename the folder from "Project1" to "Project2" using Windows Explorer.
*If using source control, rename the folder from "Project1" to "Project2" using the functions supplied by source control. This
preserves the history of the file. For example, with TortoiseSVN,
right click on the file, select TortoiseSVN .. Rename.
*In the .sln file, edit all instances of "Project1" to be "Project2".
*Restart Visual Studio, and everything will work as before, but with the project in a different directory.
..and there i always do step 6:
Step 6.: In the .sln file, edit all instances of "Project1" to be "Project2".
By observing the .sln file i could see that until step 6 (so in my case of using the tfs i did steps 1,2,3 and 5) there are still occurrences of the old project name in the .sln file:
Project("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}") = "Project2",
"Project1\Project2.csproj", "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"
and:
SccProjectUniqueName92 = Project1\Project2.csproj
SccProjectName92 = Project1
SccLocalPath92 = Project1
Until now i had no problems with that approach. But as i could see a colleague of me is skipping step 6 and there are still occurrences of the old project name in the .sln file.
Now i wonder if step 6 is really needed/required?
I am keeping using step 6 just for more cleanness! But whats your opinion on this?
Could the old project name occurrences in the .sln file (if skipping step 6) even some time lead to functional problems with tfs/vs etc.?
Or is it only for the purpose of a cleaner/clearer code better to do carry out step 6?
A: If you are renaming a project within a solution, that is under source control, really all you need to do is to rename the project in Visual Studio and then submit the changes to the project file and the solution file, back into source control.
Visual Studio and TFS should handle all of the changes for you, VS will rename the project and update the references in the SLN file.
TFS will handle the rename and will maintain the history line.
The only time it should get complicated is if you are moving projects and solutions within source control, when you are carrying out this sort of task then the list above is a fair description of what needs to be done, but after step 4 i would just open the solution remove the project that can no longer be found and add in the newly renamed project, this would then automatically handle the sln file changes. now obviously this would orphan your history on the project if it was under source control, but you would make the project name change through TFS before reopening the solution.
if you want to manually change the sln file then a find and replace operation is the simplest way to update the file.
Coming Back to your question.
You really should ensure the sln file is correct as this tells VS where to download the files from and what projects actually make up the solution, by not updating the sln file correctly you, or other users of TFS may not get the correct files downloaded and you may have issues opening your solution.
An example of fall out from not having these files in line can be found in this question Why missing <SccProjectName> in project file cause "The project file is not bound to source control"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25502480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Parameter filter based on another parameter value selected in tableau I have a parameter region having values APAC,US.
I have another parameter department having values D1,D2,D3,D4.
Now If I select Region value as APAC ,below that I have to show Department parameter value as D1 and D2 for the user.
If I select Region values as US , I have to show Department value as D3 and D4
I tried but my 2nd parameter is not filtering based on first parameter value selected.
Please suggest how to do.
enter image description here
A: If Region and Department fields have mapping in data set, then use Filters instead of a parameter.
For Department Filter check the option "Only Relevant Values" in filter settings.
Hope this works!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57985272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Username/handle system using Python - TCP/IP chat client Here is my server code.
# chat_server.py
import sys, socket, select
HOST = ''
SOCKET_LIST = []
RECV_BUFFER = 4096
PORT = 9009
def chat_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
# add server socket object to the list of readable connections
SOCKET_LIST.append(server_socket)
print "Chat server started on port " + str(PORT)
while 1:
# get the list sockets which are ready to be read through select
# 4th arg, time_out = 0 : poll and never block
ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0)
for sock in ready_to_read:
# a new connection request recieved
if sock == server_socket:
sockfd, addr = server_socket.accept()
SOCKET_LIST.append(sockfd)
print "Client (%s, %s) connected" % addr
broadcast(server_socket, sockfd, "[%s:%s] entered our chatting room\n" % addr)
# a message from a client, not a new connection
else:
# process data recieved from client,
try:
# receiving data from the socket.
data = sock.recv(RECV_BUFFER)
if data:
# there is something in the socket
broadcast(server_socket, sock, "\r" + '[' + str(sock.getpeername()) + '] ' + data)
else:
# remove the socket that's broken
if sock in SOCKET_LIST:
SOCKET_LIST.remove(sock)
# at this stage, no data means probably the connection has been broken
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
# exception
except:
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
continue
server_socket.close()
# broadcast chat messages to all connected clients
def broadcast (server_socket, sock, message):
for socket in SOCKET_LIST:
# send the message only to peer
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
# broken socket connection
socket.close()
# broken socket, remove it
if socket in SOCKET_LIST:
SOCKET_LIST.remove(socket)
if __name__ == "__main__":
sys.exit(chat_server())
Here is my client code.
# chat_client.py
import sys, socket, select
def chat_client():
if(len(sys.argv) < 3) :
print 'Usage : python chat_client.py hostname port'
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try :
s.connect((host, port))
except :
print 'Unable to connect'
sys.exit()
# TEST
person = raw_input ('Please enter your username: ')
print 'Connected to remote host. You can start sending messages.'
sys.stdout.write( person + '[Me]: ' ); sys.stdout.flush()
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
if sock == s:
# incoming message from remote server, s
data = sock.recv(4096)
if not data :
print '\nDisconnected from chat server'
sys.exit()
else :
#print data
sys.stdout.write(data)
sys.stdout.write( person + '[Me]: '); sys.stdout.flush()
else :
# user entered a message
msg = sys.stdin.readline()
s.send(msg)
sys.stdout.write( person + '[Me]: '); sys.stdout.flush()
if __name__ == "__main__":
sys.exit(chat_client())
I'm currently trying to work on adding sort of a "handle" system into the chat client. If you were to run this code, you'll notice that the handle you choose is only displayed on your client, and not anybody else's. I've done hours of research already, and I can't for the life of me figure out how to have a client's chosen handle displayed onto other clients.
I'm still relatively new to Python, and especially new to TCP/IP programming. Any help, advice, and constructive criticism will be welcomed. Thanks in advance!
A: You can do it on the server or the client side
Server side
To implement it server side, you need to maintain some kind of mapping in the server between client sockets and handles, so that when you broadcast a message from a socket, you can retrieve its handle and prepend it to the message before sending.
In order to know the handle of the clients, they can send it to the server as the first message when they connect. The server will interpret this first message as the handle, and store it mapping it to the socket from what it has been received.
The advantage of this approach is that the server can validate the handle before it accepts it from the clients, and if it is already in use, reject the handle or abort the connection. Also, the clients cannot fake their handle later in the conversation, as it is the server that sends them.
Client side
This is the easiest implementation, as you only need to modify the client and prepend the handle before sending each message.
# user entered a message
msg = sys.stdin.readline()
s.send(person + ": " + msg)
sys.stdout.write( person + '[Me]: '); sys.stdout.flush()
The drawbacks of this approach are that a malicious client can fake the handle to pretend to be another person, and that two clients can have the same handle at the same time, making them indistinguishable from each other.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33162096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RequireJS, KendoUI and KnockoutJS any chance in them working together? So I want to use requirejs, kendo ui and knockout JS together.
I read Using Kendo with RequireJS and the Knockout JS article Asynchronous Module Definition (AMD) With RequireJs and then I found the Knockout-Kendo library via Knockout.js and Kendo UI - a Potent Duo and I thought to myself - this is awesome - I'm about to be in a beautiful world of rainbows, MVVM, AMD and HTML5 lusciousness.
But now it seems more like I'm in a dark underground world of pain and suffering. Here's the deal...
I have a simple web site that has a js folder that has the following inside:
*
*jquery-2.0.3.min.js
*knockout-2.3.0.js
*knockout-kendo.min.js
*require.js
*kendo-ui/** all the kendo files under here
and an index.html file that I have put in the root containing this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="js/require.js"></script>
</head>
<body>
<div id="grid" data-bind="kendoGrid: items"> </div>
<script type="text/javascript">
require.config({
baseUrl : 'js',
paths: {
'jquery': 'jquery-2.0.3.min',
'knockout': 'knockout-2.3.0',
'kendo': 'kendo-ui',
'knockout-kendo': 'knockout-kendo.min',
},
shim: {
'jquery': {
exports: 'jQuery'
}
}
});
define('mainViewModel', ['knockout'], function (ko) {
return function mainViewModel(){
this.items = ko.observableArray([
{ id: "1", name: "apple"},
{ id: "2", name: "orange"},
{ id: "3", name: "banana"}
]);
};
});
require(['jquery','knockout','mainViewModel','knockout-kendo'],
function($, ko, mainViewModel) {
ko.applyBindings(new mainViewModel());
});
</script>
</body>
</html>
As far as I can fathom, that should be basically correct but I am getting this exception:
GET http://localhost/ko-kendo/js/kendo-ui.js [HTTP/1.1404 Not Found 1ms]
Error: Script error for: kendo
http://requirejs.org/docs/errors.html#scripterror @http://localhost/ko-kendo/js/require.js:163
Seems that knockout-kendo is trying to load up kendo-ui.js but it, unsurprisingly since it doesn't exist, can't find it.
In an attempt to verify the mappings I knocked up this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="js/require.js"></script>
</head>
<body>
<div id="grid" data-bind="kendoGrid: items"> </div>
<script type="text/javascript">
require.config({
baseUrl : 'js',
paths: {
'jquery': 'jquery-2.0.3.min',
'knockout': 'knockout-2.3.0',
'kendo': 'kendo-ui',
'knockout-kendo': 'knockout-kendo.min',
},
shim: {
'jquery': {
exports: 'jQuery'
}
}
});
define('mainViewModel', ['knockout'], function (ko) {
return function mainViewModel(){
this.items = ko.observableArray([
{ id: "1", name: "apple"},
{ id: "2", name: "orange"},
{ id: "3", name: "banana"}
]);
};
});
require(['jquery','knockout','mainViewModel','kendo/kendo.grid.min'],
function($, ko, mainViewModel) {
var vm = new mainViewModel();
$(document).ready(function () {
$('#grid').kendoGrid({
dataSource: new mainViewModel().items()
});
});
ko.applyBindings(vm);
});
</script>
</body>
</html>
That worked fabulously (well, it worked) - you can see that the difference between the two is that in the second case I am not using knockout-kendo and therefore, the binding does not apply, which is why I do that kendoGrid thing in the document ready function.
So, does anyone know how on this green and beautiful earth I can get knockout-kendo working with require JS? I feel like there might be something fancy with a shim that would get it going but I can't work it out...
A: Knockout-Kendo is set to depend on a kendo module. The easiest thing to do is point kendo at the kendo.web file like: kendo: kendo.web.min (in whatever directory kendo.web.min.js is in).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18485019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why is it that i am still not able to create a new directory in sdcard after capturing an image for my app? public class EditUploads extends Activity implements OnClickListener {
ImageView ivEditUploads, imgSave;
EditText etxtPrice, etxtDescription;
Spinner sCategories;
PhotoDbAdapter ourHelper;
Long pRowId = null;
private String description, category, price, imagepath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_edit_uploads);
findViewById();
if (getIntent().hasExtra("byteArray")) {
Bitmap b = BitmapFactory.decodeByteArray(getIntent()
.getByteArrayExtra("byteArray"), 0, getIntent()
.getByteArrayExtra("byteArray").length);
ivEditUploads.setImageBitmap(b);
}
addItemsOnSCategories();
addListenerOnSpinnerItemSelection();
String _path = Environment.getExternalStorageDirectory() + "/Myfolder/"
+ System.currentTimeMillis() + ".jpg";
}
private void findViewById() {
ivEditUploads = (ImageView) findViewById(R.id.ivEditUploads);
imgSave = (ImageView) findViewById(R.id.imgSave);
sCategories = (Spinner) findViewById(R.id.sCategories);
etxtDescription = (EditText) findViewById(R.id.etxtDescription);
etxtPrice = (EditText) findViewById(R.id.etxtPrice);
imgSave.setOnClickListener(this);
}
public void addItemsOnSCategories() {
sCategories = (Spinner) findViewById(R.id.sCategories);
List<String> list = new ArrayList<String>();
list.add("His");
list.add("Hers");
list.add("Kid's");
list.add("Everything Else");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sCategories.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
sCategories
.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
@Override
public void onClick(View v) {
Bitmap sourceBitmap = ((BitmapDrawable) ivEditUploads.getDrawable())
.getBitmap();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Neatpicks");
myDir.mkdirs();
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fname);
Uri mCapturedImageURI = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null,
null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor.getString(column_index_data);
File mediaStorageDir = new File(Environment
.getExternalStorageDirectory().getPath(), "Neatpicks");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("Neatpicks", "failed to create directory");
return;
}
}
description = etxtDescription.getText().toString();
category = sCategories.getOnItemSelectedListener().toString();
price = etxtPrice.getText().toString();
imagepath = capturedImageFilePath;
PhotoDbAdapter saveUploads = new PhotoDbAdapter(EditUploads.this);
saveUploads.open();
if (pRowId == null) {
long saveUpId = saveUploads.createEntry(description, category,
price, imagepath);
saveUploads.close();
if (saveUpId > 0) {
pRowId = saveUpId;
Intent uploads = new Intent(getApplicationContext(),
Mobile.class);
startActivity(uploads);
}
}
}
}
i had tried to use the mkdir methods however, i was still not able to see the images in a newly created folder...i am hoping someone would help point out my mistakes and guide me along cause i am fairly new to android programming. Thanks in advance!
A: Your app probably needs to request the WRITE_EXTERNAL_STORAGE permissions as described here, but you might also want to check your folder path.
In future you should report any exceptions or logcat entries you see and more detail in general about HOW the operation fails. Also try other things such as creating folders in your private data space using Environment. getDataDirectory()
A: You need to provide the permission to AndroidManifest.xml for STORAGE permissions.
Go to AndroidManifest.xml-> permission tab -> click add -> uses permission
Name:android.permission.WRITE_EXTERNAL_STORAGE and android.permission.READ_EXTERNAL_STORAGE if necessary.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20537691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Remove undefined select option after $compile? It appears that when you create a select element inside of a directive, it creates a sort of dummy option (I assume since at this point it doesn't know what to set it to and doesn't want to make assumptions). The top option below is the option I mean:
<select ng-model="optionVal">
<option value="? undefined:undefined ?"></option>
<option value="opt1">Option One</option>
<option value="opt2">Option Two</option>
</select>
Functionally everything works, but having that empty entry in the select box is ugly, and I'd like to remove it. Does anyone know a way to do that?
A: That option is created because your model does not contain one of opt1 or opt2, so it creates an option to match the current value of your model. The way to avoid that is to set your model to a value first.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52881005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to select only certain items from a collection using Streams in Java I am trying to select only names from a collection using streams: These are the entries:
Person{id=4, name=E, color=red}]
[Person{id=0, name=A, color=blue}
Person{id=1, name=B, color=green}
Person{id=2, name=D, color=pink}
Person{id=0, name=C, color=yellow
I've tried using map, but it doesn't seem to alter the list since the function I'm mapping it to is supposed to be a getter method.
list.stream().map(p -> getter.apply(p))collect(Collectors.toList());
A: If you have getter defined for the fields of Person, you can map the names:
List<String> personNames = list.stream().map(Person::getName).collect(Collectors.toList());
A: Use .filter, like the webiste explains you, instead of .map
A: To filter say on the name, do it like this.
Person{id=4, name=E, color=red}]
[Person{id=0, name=A, color=blue}
Person{id=1, name=B, color=green}
Person{id=2, name=D, color=pink}
Person{id=0, name=C, color=yellow
Assuming a List<Person>
To get all the Person objects with a specific name
List<Person> specific = list
.stream()
.filter(person->person.name.equals("E"))
.collect(Collectors.toList());
To get just the names
List<String> names = list
.stream()
.map(person->person.name)
.collect(Collectors.toList());
A: Here is a generic code, that uses filter:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
class Person {
int id;
String name;
String color;
@Override
public String toString() {
// TODO Auto-generated method stub
return id + ":" + name + ":" + color;
}
public Person(int id, String name, String color) {
super();
this.id = id;
this.name = name;
this.color = color;
}
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 getColor() {return color;}
public void setColor(String color) {this.color = color;}
}
public class Test {
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
list.add(new Person(1,"Ana","red"));
list.add(new Person(2,"tna","orange"));
list.add(new Person(3,"Hna","green"));
list.add(new Person(4,"Ana","blue"));
List<Person> t = list.stream().filter(p->p.getName().equals("Ana")).collect(Collectors.toList());
System.out.println(t);
}
}
For this particular question it is suggestible to use filter instead of map. Because we are only interested in filtering the stream to get the desired output.
On the other hand, map operation is used on the stream if we have the requirement to manipulate the data further in which condition we can apply more functions before the terminal operation (example is provided).
By using map, you transform the object values.
The map operation allows us to apply a function, that takes in a parameter of one type, and returns something else.
For an example:
Stream students = persons.stream()
.filter(p -> p.getAge() > 18)
.map(new Function<Person, Customer>() {
@Override
public Customer apply(Person person) {
return new Customer(person);
}
});
Filter is used for filtering the data, it always returns the boolean value. If it returns true, the item is added to list else it is filtered out.
For in-depth understanding follow the documentation
link
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62922643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: I can't see the save button but see the test button only in amazon lambda function everyone!
I can't see the save button but see the test button only in amazon lambda function.
I can't know what's the reason for it.
I searched on goolge, but can't find answer.
Save button has been shown before yesterday, but today I can't see.
I hope anyone can help me.
Thanks.
A: The user interface changed overnight. Now you have to use Deploy button:
A: you are right! As per the new deployment "save" button is integrated within each module. So you don't need to globally save all changes at once instead you can save only the particular setting. Likewise you can directly deploy scripts from the function code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63953949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Regular expression in HTML - Command OR I have this:
<input type="text" name="funkce<%=i %>" value="" size="20" data-toogle="tooltip" title="Vlož hodnoty a-z o maximální délce 3 znaky." style="width: 50px; padding: 2px" required maxlength="3" pattern="([a-z]{1,3})|(([a-z]{1}[\s,]+)*[a-z]{1})" />
It is not working I need control input for two types string.
I need insert example "a,b,c" or "abc", but or (|) in pattern is not working :(
A: Your pattern is working. It is checked onsubmit, not onkeydown nor onkeypress.
However, the pattern is nondeterministic. It should be writen in such a way that every character is matched by at most one subpattern. In this case, deterministic version is: [a-z](([a-z]{1,2})|([\s,]+[a-z])*)
Also maxlength="3" will not work with input a,b,c.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44413000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get multiple instances of an object registered via Autofac module registration I have a use case where I need to get two copies of objects registered from Autofac module and pass them to register different types.
In the below code sample,
*
*I want to pass an object of DataProtectionService with config dbConfig to register MyDbRepo.
*Similarly, I want to pass an object of DataProtectionService with config cacheConfig to register MyCacheRepo.
But, I am not sure how should I do that? Am I missing something really basic here?
I don't have an option to remove this DataProtectionServiceModule. Is there a way to achieve what I am expecting?
public class DataProtectionServiceModule : Module
{
private readonly string config;
public DataProtectionServiceModule(string config)
{
this.config = config;
}
protected override void Load(ContainerBuilder builder)
{
builder.Register<Token>(compContext =>
{ // a complex logic here
}).OnRelease(instance => instance.Dispose());
builder.Register(c =>
{
// a logic to generate an object of IDataProtectionService
// this logic involves the use of config field of this class.
}).As<IDataProtectionService>();
}
}
public class MyDbRepo : IMyDbRepo
{
IDataProtectionService dataProtectionService;
public MyDbRepo(IDataProtectionService dataProtectionService)
{
this.dataProtectionService = dataProtectionService;
}
}
public class MyCacheRepo : IMyCacheRepo
{
IDataProtectionService dataProtectionService;
public MyCacheRepo(IDataProtectionService dataProtectionService)
{
this.dataProtectionService = dataProtectionService;
}
}
// Program.cs of my backend micro service
var builder = new ContainerBuilder();
builder.RegisterModule(new DataProtectionServiceModule("dbConfig"));
builder.RegisterModule(new DataProtectionServiceModule("cacheConfig")); // I have figured, this is wrong.
builder.RegisterType<MyDbRepo>().As<IMyDbRepo>().SingleInstance();
builder.RegisterType<MyCacheRepo>().As<IMyCacheRepo>().SingleInstance();
A: You can use Keyed Services. And then in your registration add a specific Resolve.
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// Program.cs of my backend micro service
var builder = new ContainerBuilder();
builder.RegisterModule(new DataProtectionServiceModule("dbConfig", DeviceState.Db));
builder.RegisterModule(new DataProtectionServiceModule("cacheConfig", DeviceState.Cache)); // I have figured, this is wrong.
builder.RegisterType<MyDbRepo>().WithParameter(
new ResolvedParameter(
(pi, ctx) => pi.ParameterType == typeof(IDataProtectionService),
(pi, ctx) => ctx.ResolveKeyed<IDataProtectionService>(DeviceState.Db)
)
).As<IMyDbRepo>().SingleInstance();
builder.RegisterType<MyCacheRepo>().WithParameter(
new ResolvedParameter(
(pi, ctx) => pi.ParameterType == typeof(IDataProtectionService),
(pi, ctx) => ctx.ResolveKeyed<IDataProtectionService>(DeviceState.Cache)
)
).As<IMyCacheRepo>().SingleInstance();
var container = builder.Build();
var cache = container.Resolve<IMyCacheRepo>();
var db = container.Resolve<IMyDbRepo>();
}
}
public enum DeviceState { Cache, Db }
public class DataProtectionServiceModule : Module
{
private readonly string config;
private readonly DeviceState _state;
public DataProtectionServiceModule(string config, DeviceState state)
{
this.config = config;
_state = state;
}
protected override void Load(ContainerBuilder builder)
{
builder.Register<Token>(compContext =>
{ // a complex logic here
}).OnRelease(instance => instance.Dispose());
builder.Register(c =>
{
// a logic to generate an object of IDataProtectionService
// this logic involves the use of config field of this class.
return new DataProtectionService(config);
}).Keyed<IDataProtectionService>(_state);
}
}
public class DataProtectionService : IDataProtectionService
{
public string Config { get; }
public DataProtectionService(string config)
{
Config = config;
}
}
public class MyDbRepo : IMyDbRepo
{
IDataProtectionService dataProtectionService;
public MyDbRepo(IDataProtectionService dataProtectionService)
{
this.dataProtectionService = dataProtectionService;
}
}
public interface IDataProtectionService
{
}
public interface IMyDbRepo
{
}
public class MyCacheRepo : IMyCacheRepo
{
IDataProtectionService dataProtectionService;
public MyCacheRepo(IDataProtectionService dataProtectionService)
{
this.dataProtectionService = dataProtectionService;
}
}
public interface IMyCacheRepo
{
}
Alternatively you can use Named Services and the config-name dbConfig and cacheConfig. This way you do not need to change the constructor of DataProtectionServiceModule.
builder.RegisterType<MyDbRepo>().WithParameter(
new ResolvedParameter(
(pi, ctx) => pi.ParameterType == typeof(IDataProtectionService),
(pi, ctx) => ctx.ResolveNamed<IDataProtectionService>("dbConfig")
)
).As<IMyDbRepo>().SingleInstance();
builder.RegisterType<MyCacheRepo>().WithParameter(
new ResolvedParameter(
(pi, ctx) => pi.ParameterType == typeof(IDataProtectionService),
(pi, ctx) => ctx.ResolveNamed<IDataProtectionService>("cacheConfig")
And your module:
protected override void Load(ContainerBuilder builder)
{
//builder.Register<Token>(compContext =>
//{ // a complex logic here
//}).OnRelease(instance => instance.Dispose());
builder.Register(c =>
{
// a logic to generate an object of IDataProtectionService
// this logic involves the use of config field of this class.
return new DataProtectionService(config);
}).Named<IDataProtectionService>(config);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67265970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Datasource is not bound in context My datasource.xml
<?xml version="1.0" encoding="UTF-8"?>
<datasource>
<local-tx-datasource>
<jndi-name>SampleDS</jndi-name>
<connection-url>jdbc:mysql://www.mycomp.com:3306/mydb </connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<min-pool-size>
1>/min-pool-size>
<max-pool-size>
20>/max-pool-size>
admin</user-name>
<password>admin</password>
<metadata>
<type-mapping & g ; mySQL</type-mapping>
</metadata>
</local-tx-datasource>
</datasource>
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="1.0">
<persistence-unit name="DefaultPersistenceUnit"
transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>User</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://www.mycomp.com:3306/mydb" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"></property>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.password" value="admin" />
<property name="hibernate.connection.username" value="admin" />
<property name="hibernate.connection.datasource" value="SampleDS" />
</properties>
</persistence-unit>
</persistence>
UserList.java
public List<User> getUsers(){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("DefaultPersistenceUnit");
EntityManager em = emf.createEntityManager();
Query query = em.createQuery(CityList.EJBQL);
List<User> users= query.getResultList();
return users;
}
After deploying when accessing my xhtml page I am getting the error
javax.persistence.PersistenceException: [PersistenceUnit: DefaultPersistenceUnit] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:57)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:48)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)
at com.myapp.action.UserList.getUsers(UserList.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:467)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:161)
at org.apache.el.parser.AstValue.getValue(AstValue.java:159)
at org.apache.el.parser.AstDeferredExpression.getValue(AstDeferredExpression.java:44)
at org.apache.el.parser.AstCompositeExpression.getValue(AstCompositeExpression.java:50)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:106)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
at javax.faces.component.UIOutput.getValue(UIOutput.java:165)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:201)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:351)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:160)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:879)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1670)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:164)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:849)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1663)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1666)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1666)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:389)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:127)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:117)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:135)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:335)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:403)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:301)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:162)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:140)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.hibernate.HibernateException: Could not find datasource
at org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:79)
at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:143)
at org.hibernate.ejb.InjectionSettingsFactory.createConnectionProvider(InjectionSettingsFactory.java:51)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:90)
at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2863)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2859)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1870)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:906)
... 51 more
Caused by: javax.naming.NameNotFoundException: Name SampleDS is not bound in this Context
at org.apache.naming.NamingContext.lookup(NamingContext.java:803)
at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:158)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:75)
... 58 more
How to resolve this?
A: With the hibernate.connection.datasource property, you're telling hibernate to look for a datasource in JNDI. Obviously you don't have one. Since you're specifying all the other required connection properties there, I'm guessing you don't really mean to do that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6956713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Missing artifact com.google.appengine:appengine-tools-sdk:jar:${appengine.sdk.version} I am getting the below error while creating a maven project in eclipse 3.0
Missing artifact com.google.appengine:appengine-tools-sdk:jar:${appengine.sdk.version}
Can someone help me out?
A: It looks like your template substitution is not working. Have you tried either making sure you have a maven property appengine.sdk.version define, or substituting the placeholder with a fixed version of appengine-tools-sdk?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51325435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: TextView dp does not scale with screen size I am attempting to create a textView that will take up a large portion of the top center part of the screen. Ideally, setting the text size in dp would allow the textView to remain the correct relative size (taking up about 70% of the width of the screen, and maybe 20% of the top). It looks correct in the layout editor, and in the emulator at HVGA resolution. However, when I test it at higher resolutions (on my tablet, or emulating a 720p display) the text takes up a very small portion of the top center part of the screen. (maybe 30% width instead of 70%, and it doesn't seem any larger vertically).
Is there a way to scale text to correctly increase relative size with resolution?
A: Set the layout_width as fill_parent, which will make it spread across the screen for all devices.
Add some padding on left right and top which seems suitable.
The padding might seem different for different screens but still this might be a better solution.
A: set
android:layout_width="match_parent"
edit:
check this out
Auto Scale TextView Text to Fit within Bounds
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10773577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Async task with Symfony 4 application I need to import a list of members, when I want to import 1 or 2 members it goes very fast but when I want to import hundreds of them it goes slowly, and my page is loading while it is importing into the members table.
My question is how to make this importing in the background while browsing my application and receive a flash that informs me import is successful?
MemberManagerImportController.php
if ($uploaded) {
$this->getDoctrine()->getManager()->flush();
->>> (this line async) $eventBus->dispatch(new ConvertMemberImportFile($import->getId()));
$this->addFlash('success', 'member.import_mapping_saved_successfully');
return $this->redirectToRoute('app_group_manager_members_import_result', [
'group_id' => $community->getId(),
'import_id' => $import->getId(),
]);
}
messenger.yml
framework:
messenger:
default_bus: messenger.bus.event
buses:
default:
middleware:
- Arxus\NewrelicMessengerBundle\Middleware\NewRelicMiddleware
messenger.bus.event:
default_middleware: allow_no_handlers
middleware:
- 'AppBundle\MessageBus\SqsBus\Middleware\ForwardToNotificationMiddleware'
messenger.bus.notification:
transports:
sqs: 'sqs-custom://'
async: "%env(MESSENGER_TRANSPORT_DSN)"
routing:
'*': sqs
AppBundle\Member\Import\Bus\Message\ConvertMemberImportFile: async
serializer:
default_serializer: 'messenger.transport.symfony_serializer'
A: there are a couple of ways to achieve it, for example:
*
*you can use server-side events and subscribe your client to be notified once the import is done https://symfony.com/blog/symfony-gets-real-time-push-capabilities
*simpler way is storing a record once the import is done somewhere in DB/redis and ask the backend if the operation is finished on each page load/via ajax
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66545361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: trying to select checkboxes which have a specific class Here is my code where i am trying to select the images which only the specific class attached to it
$("#allimages").change(function () {
$('input:checkbox:not("#checkAll")').prop('checked', $(this).prop('checked',$(this).hasClass('isImage')));
});
but it is selecting all checkboxes ignoring if any class is attached to it or not
A: Without seeing the HTML, it's hard to know what you're trying to accomplish.
I would suggest the following based on what you have provided:
$("#allimages").change(function() {
$("input[type='checkbox'].isImage:not('#checkAll')").prop('checked', $(this).prop("checked"));
});
When #allimages is changed, that same value will be sent to all checkboxes that have class isImage and is not #checkAll.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64849896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: django Download Link(filefield) i am trying to create a Software download website, and each software has some file and download link (mac,windows,linux,..).
Can anyone tell me how to use 'filefield' for download links(not one).
(Sorry, my English is so weak).
A: You just need to put download attribute in the anchor tag . and the anchor tag will allow the user to get the file from the href location. A small example is give below
<a download href="/media/{{friend.picture}}"><img height="100%" width="100%" class="img-fluid d-block mx-auto" src="/media/{{friend.picture}}"></a>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61556548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Meteor Account Credential Assignment I have a Meteor app that works with a Facebook app for user login. On the actual hosted version, the login makes use of the actual Facebook app but in localhost in development, the app uses a Facebook test app.
The problem is that when I switch over from development to deploying, I need to comment out the credentials for production and uncomment the credentials for development. How could I solve this issue?
// Removes the config b/c dupliation error and re-defines it
// Facebook API config
// Since Facebook Test app has been created, wrap this in conditional that only executes if on Amazon server and not localhost
// STRICTLY - Production
// ServiceConfiguration.configurations.remove({
// service: "facebook"
// });
// ServiceConfiguration.configurations.insert({
// service: 'facebook',
// appId: Meteor.settings.FacebookId,
// secret: Meteor.settings.FacebookSecret
// });
// STRICTLY - Dev
ServiceConfiguration.configurations.remove({
service: "facebook"
});
ServiceConfiguration.configurations.insert({
service: 'facebook',
appId: 'id',
secret: 'secret'
});
A: You should add dev and prod variables to your settings.json file, and load them locally with meteor --settings settings.json. The settings.json file would look something like this:
{
"dev": {
"public": {
"facebook": {
"appId": "abc123"
}
},
"private": {
"facebook": {
"secret": "456def789"
}
}
},
"prod": {
"public": {
"facebook": {
"appId": "def234"
}
},
"private": {
"facebook": {
"secret": "789ghi101112"
}
}
}
You could then access them just as you were before: Meteor.settings.dev.public.facebook.appId.
The public/private may be overkill for your project (and I may have messed up the brackets), but this should convey the general concept. For more info, check out this oft-cited post.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33163296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I'm trying to display images that I uploaded to my backend with multer I'm using multer to upload images from my react client. All the images are being stored they just aren't showing up. The images are being stored, but aren't showing up in react. The are set in state just not displaying. I can see them in the images folder on the backend so I know multer is working.
This is my react component
class AddNewDish extends Component {
constructor(props){
super(props)
this.state = {
name: '',
imageUrl: '',
description: ''
}
}
createDishHandler = (event) => {
event.preventDefault()
const fd = new FormData();
fd.append('name', this.state.name)
fd.append('imageUrl', this.state.imageUrl, this.state.imageUrl.name)
fd.append('description', this.state.description)
axios.post('http://localhost:8080/add-new-dish', fd,)
.then(res => {
console.log(res, 'res')
})
this.props.history.push('/')
}
onChange = (e) => {
switch(e.target.name) {
case 'imageUrl':
this.setState({imageUrl: e.target.files[0]});
break;
default:
this.setState({[e.target.name]: e.target.value})
}
console.log(e)
}
render () {
console.log(this.state.imageUrl, 'in imgUrl')
return (
<div>
<form onSubmit={this.createDishHandler}>
<input
label='Name'
onChange={this.onChange}
name='name'
type='text'
placeholder='Enter Dish Name'
value={this.state.name}
/>
< input
label='Dish Image'
onChange={this.onChange}
name='imageUrl'
type='file'
placeholder='Enter Dish Image'
// value={this.state.imageUrl}
/>
<input
label='Description'
onChange={this.onChange}
name='description'
placeholder='Enter Dish Description'
type='text'
value={this.state.description}
/>
<img src={this.state.imageUrl}/>
<button>Submit Dish</button>
</form>
</div>
)
}
};
export default AddNewDish
One the backend
const multer = require('multer');
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'public')
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString() + '-' + path.extname(file.originalname))
}
});
const fileFilter = (req, file, cb) => {
if(
file.mimetype === 'image/png' ||
file.mimetype === 'image/jpg' ||
file.mimetype === 'image/jpeg'
) {
cb(null, true)
} else {
cd(null, false)
}
}
exports.upload = multer({
storage: fileStorage,
fileFilter: fileFilter
})
.single('imageUrl')
This is how I call my route
exports.postADish = async ( req, res,) => {
console.log(req.file, 'in req.file')
try {
const { name, description } = req.body;
const imageUrl = req.file.path
const newDish = await dish.postNewDish({name, description, imageUrl})
res.status(201).json(`new dish added`)
} catch (err) {
res.status(500).json(`Error posting dish`)
console.log(err)
}
};
How I use upload middleware
router.post('/add-new-dish', dishController.upload, dishController.postADish);
making folder public
app.use('/public', express.static('public'))
This is how I'm trying to display the images in my index route on the frontend
class App extends Component {
constructor () {
super()
this.state = {
data: []
}
}
componentDidMount() {
axios
.get(`http://localhost:8080/`)
.then(res => {
console.log(res, 'response')
this.setState({
data: res.data.dishData
})
})
.catch(err => {
console.log(err)
})
}
render() {
console.log(this.state.data)
return (
<div className="App">
<Nav
<Route
exact path ='/'
render={props =>
<Home
{...props}
dishes={this.state.data}
/>
}
/>
My state looks like this
{id: 7, name: "test dish", imageUrl: "public/2019-04-20T22:52:09.900Z-20190411_112505.jpg", description: "test description"}
I'm getting back the imageUrl and using it in the home component like this
const Home = (props) => {
return (
<DishWrapper>
<DishContent>
{props.dishes.map(dish => {
console.log(dish, 'in dish')
return (
<Dish key={dish.id}>
<h3>{dish.name}</h3>
<img src={ `public/${dish.imageUrl}`} alt={dish.name}/>
<h5>{dish.description}</h5>
</Dish>
)
})}
</DishContent>
</DishWrapper>
)
};
export default Home
In the backend my get looks like this
exports.getDishes = async (req, res) => {
try {
const dishData = await dish.getDishes()
if(!dishData) {
res.status(404).json(`No dishes available at this time`)
} else {
res.status(200).json({
dishData,
})
}
} catch (err) {
res.status(500)
console.log(err)
}
};
A: So to view the image before the the upload you need to first use FileReader which is a javascript object that lets web applications asynchronously read the contents of files. This will give you a base64 version of your image that you can add to your image src. So you can do this in your onChange function and it would look something like the following:
onChange = (e) => {
switch(e.target.name) {
case 'imageUrl':
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = () => {
this.setState({
imageUrl: file,
imgBase64: reader.result
})
};
reader.readAsDataURL(file);
break;
default:
this.setState({[e.target.name]: e.target.value})
}
}
in this example i'm adding to the state the imgBase64 key and adding the base64 value to it but you can use whatever name you like just be sure to add it to your state object.
Then to view it you can use this value as the image src like so:
<img src={this.state.imgBase64}/>
After that when you submit your image to multer you need to return the image's filename so you can access it after you upload it so in your route since it seems like your getting the correct filename back when you log it you can return it to your axios call and use it after that. So in your route just send back a json object and use it. So instead of res.status(201).json(new dish added) send something like the following:
res.status(201).json({
msg: 'new dish added',
imageUrl: req.file.filename
})
and then your axios call will receive this json object and you can access in your frontend afterwards like so:
createDishHandler = (event) => {
event.preventDefault()
const fd = new FormData();
fd.append('name', this.state.name)
fd.append('imageUrl', this.state.imageUrl, this.state.imageUrl.name)
fd.append('description', this.state.description)
axios.post('http://localhost:8080/add-new-dish', fd,)
.then(res => {
//you can set your res.data.imageUrl to your state here to use it
console.log('Success Message: ' + res.data.msg + ' - Image File Name: ' + res.data.imageUrl)
})
this.props.history.push('/')
}
But in the above function I see that you push do a different page when uploading. So if you push to a different page then you obviously aren't going to be using this state anymore so you will need probably need to just retrieve it from your database at that point from the new page.
Anyway I hope this helps and if you have any questions let me know.
P.S. I just wanted to let you know you may want to use Date.now() + path.extname(file.originalname) instead of new Date().toISOString() + '-' + path.extname(file.originalname) in you multer upload it looks a little cleaner without all of the colons and dashes but it's not necessary.
Edit:
So if you are going serve up a static folder with express then like I said in previous comments below you are going to have to use absolute urls to access your content. React cannot access anything with relative paths outside of the public folder in your client. So if in your backends root you are going to have a folder named images then in multer you would set the destination to 'images' with express you would serve up the static folder app.use(express.static('images')) and to access this with your image you would need to use an absolute url
<img src={ `http://localhost:8080/${imageUrl}`} alt={dish.name}/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55769505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Spring Batch - Connecting to Database using JNDI without Spring boot I am working on a spring batch which runs only once in a day. Please note that its not a spring boot Project rather its just Spring core along with Spring batch libraries.
I have a question, this jar will be placed in a server where IBM Websphere Was 6 server is also running.
In my Jar, Would I be able to use the JNDI datasource connection available in the WAS server.
I thought even though the Jar resides on the same physical server as IBM WAS, JNDI can only be used by the apps deployed in the WAS Server . Please let me know if my understanding is wrong.
Also if you can guide me in the right direction on ways to efficently connecting to Database would be very helpful. I am just looking for reference as a starter.
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"ABPBatchInfrastructure.xml",
"AgencyBillPayFileUploadApp.xml"
);
DataSource ds = (DataSource) ctx.getBean("dbDataSource");
Connection connection = ds.getConnection();
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("select name from notify.product");
XML Below
<jee:jndi-lookup id="dbDataSource"
jndi-name="jdbc/MyLocalDB"
expected-type="javax.sql.DataSource" />
Stack Trace below
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbDataSource': Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61766078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Script to Move Directory by Combined Size In a main directory, eg /media/date/ There are a bunch of sub folders like so:
/media/date/resource1/a-lot-of.files
/media/date/resource2/a-lot-of.files
/media/date/resource3/a-lot-of.files
I want to have a script or a command that scans the sizes of each resource level folder, then moves them together under /media/date/1-fold/resouceX, resourceY Until it goes up to ~1TB. Then it will move the next batch to a new folder like 2-fold
I have in mind df and mv but don't know how to go on from there. Any input is welcomed!
A: src_path="/media/date/resource"
dest_path="/media/date/dir"
dir_suffix="0"
curr_total="0"
ONE_TERRA=$(( 1024 * 1024 * 1024 * 1024 )) # in KB
for folder in "${src_path}"*; do
if ! [[ -d "${folder}" ]]; then continue; fi
if ! [[ -d "${dest_path}${dir_suffix}" ]]; then
mkdir "${dest_path}${dir_suffix}"
folder_size=$(du -s "${folder}" | grep -E -o "[[:digit:]]+")
curr_total=$(( curr_total + folder_size ))
mv "${folder}" "${dest_path}${dir_suffix}"
if (( curr_total > ONE_TERRA )); then
dir_suffix=$(( dir_suffix + 1 ))
fi
Steps are as follows:
*
*for each node of the pattern /media/date/resource*
*if it isn't a directory, continue
*if the dest dir doesn't exist, create it
*get the size of the dir to move in KB
*add it to the curr total of dest dir
*move the dir to dest dir
*if the curr dest dir size is over one terra, increment the dest dir suffix.
I have not tested the code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68943372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: plotting between two curved lines I have data where the X(time), Y1 (Median values), Y2(25th percentile) and Y3(75th percentile). Now i want to plot all these in the same plot, and shade the area between the median curve and upper quartile curve and again shade the area between median curve and lower quartile curve.
Is there some easy way to do this?
I tried the option
xx = [X,X];
yy = [Y1,Y2];
fill(xx,yy,'b');
.. But I am not happy with the above code as it does not give me the plot that I am looking for.
Please could someone help me.!!
Many thanks
SSR
A: Is this what you want?
x = 0:.01:1;
y1 = 5+sin(2*pi*x);
y2 = y1-1;
y3 = y1+1; %// example values
fill([x x(end:-1:1)],[y3 y1(end:-1:1)],[.6 .6 .6]) %// light grey
hold on
fill([x x(end:-1:1)],[y2 y1(end:-1:1)],[.4 .4 .4]) %// dark grey
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29387454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: JavaScript console library I have heard about a JavaScript library that simulates the console from development tools, but I can't find anything on the web.
My need is when I deploy my HTML5 + JavaScript application (with Icenium) in a device (tablet or smartphone and Android or iOS). Sometimes some bugs only occurs on those devices and not in my desktop's simulator, so a console running on it will be very helpful.
A: Are you looking for something like jqconsole?
A: Not JavaScript tools for emulating the console, but here are some other ways around it:
Chrome for Android has remote debugging through Chrome for Desktop
And I think Safari has a similar feature for iOS devices.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18701089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to filter data only in the visible page of the table which is having filter in the header in Tabulator I have a table in which i display 5 rows per page.If searched for a value it is fetching results from complete data table.it has to search only from the displayed page in tabulator.
A: It is not possible to filter only the current page. If you have a look at the Row Management Pipeline Documentation you will see that Tabulator first filters data and then paginates the data that passes the filter.
In order to do this you would need to filter data outside of the table and then paginate it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59730286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Use spectron with Java and selenium for Electron app My browser-based application has recently switched over to an electron app and now the tests obviously don't seem to work, they can't pick up the windows and the elements correctly.
I've read that Spectron is used to test electron apps but is it possible to use it with Java and Selenium?
I haven't been able to find any examples that aren't in Js. Are there any examples of how electron can be used with java?
Currently, I'm running my electron app like this
public static WebDriver startDriverTwo() {
String projectLocation = System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver", projectLocation + "/chromedriver.exe");
ChromeOptions opt = new ChromeOptions();
opt.addArguments("start-maximized");
//Enter the path of your Electron app
opt.setBinary("C:/path/to/app.exe");
opt.addArguments("start-maximized");
//opt.addArguments("--headless");
driver = new ChromeDriver(opt);
return driver;
}
And then I get(Url), but this opens 2 windows, and selenium can't seem to recognize them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67002722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Batch File FTP attempt for password/authentication multiple times using ERRORLEVEL loop I can't try to reconnect with a different password after authentication failed. ERRORLEVEL seems to not be working in my code. I have no clue what's going wrong. The code is in batch file on Windows 10.
@echo off
echo use USERNAME> ftpcmd.dat
echo PASSWORD>> ftpcmd.dat
ftp -n -s:ftpcmd.dat files.000webhost.com
if %ERRORLEVEL% neq 0 (
goto TEST
)
:TEST
echo user USERNAME> ftpcmd.dat
echo DIFFERENTPASSWORD>> ftpcmd.dat
echo prompt>>ftpcmd.dat
echo cd Test>>ftpcmd.dat
echo mput FILE PATH>> ftpcmd.dat
ftp -n -s:ftpcmd.dat FTPTHING
A: The Windows ftp.exe always returns 0, no matter what.
All you can possibly do, is to parse its output and look for errors. But that's pretty unreliable.
If you want to take this approach anyway, see
*
*how to capture error conditions in windows ftp scripts? or
*Batch command to check if FTP connection is successful.
Though, you better use some better FTP client. Sooner or later you will run into troubles with the ftp.exe anyway, as it does not support an encryption, the passive mode or recursive transfers, among many other limitations.
If you are familiar with PowerShell, use the FtpWebRequest or WebClient from a Powershell script. There are numerous examples here, for example Upload files with FTP using PowerShell.
If not, use some 3rd party command-line FTP client.
For example with WinSCP FTP client, your batch file may look like:
@echo off
winscp.com /ini=nul /log=script.log /command ^
"open ftp://USERNAME:PASSWORD@ftp.example.com/" ^
"put C:\LOCAL\FILE /REMOTE/PATH/" ^
"exit"
if ERRORLEVEL 1 (
winscp.com /ini=nul /log=script2.log /command ^
"open ftp://USERNAME:DIFFERENTPASSWORD@ftp.example.com/" ^
"put C:\LOCAL\FILE /REMOTE/PATH/" ^
"exit"
)
References:
*
*Automate file transfers to FTP server;
*How do I know that script completed successfully?;
*Guide to converting Windows FTP script to WinSCP SFTP script.
WinSCP can also be used from PowerShell, if you want even more robust implementation.
(I'm the author of WinSCP)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42610174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Refactoring empty if-statements I currently working on a project that I need to remove a class that is being used by different other classes. There are cases that I can remove the one line of code that consists of that class where it will never affect the functionality of the program, but also there are cases that the class that you want to be removed is inside an if-statement. The main problem is that once I removed the line of code consisting of that class where is it inside the if-statement, it will be an empty if-statement that will violates the sonar.
Is there another way to refactor an empty if-statement other that negating the condition of one of the statements? Because when I'm just negating the condition, the readability of the code reduced.
For Example:
if((example_A >= 0) && (condition_A))
{
removeThisClass();
}
else if((example_B >= )) && (condition_B))
{
doSomething();
}
else
{
doAnything();
}
Refactored:
if(!((example_A >= 0) && (condition_A)) && ((example_B >= )) && (condition_B)))
{
doSomething();
}
else
{
doAnything();
}
A: You can put this code in separate method (https://refactoring.com/catalog/extractFunction.html) and write it like this:
public void DoSomeStuff() {
if((example_A >= 0) && (condition_A))
return;
if((example_B >= )) && (condition_B)) {
doSomething();
return;
}
doAnything();
}
A: If I understand you right, the line removeThisClass(); should be removed, and you don't want to be left with an empty block like this:
if((example_A >= 0) && (condition_A))
{
}
else if((example_B >= )) && (condition_B))
{
doSomething();
}
else
{
doAnything();
}
In order to not do the "A" tests twice, you need to negate the condition, e.g. like this:
if ((example_A < 0) || ! (condition_A))
{
if ((example_B >= )) && (condition_B))
{
doSomething();
}
else
{
doAnything();
}
}
Your refactored code is wrong, because if the "A" condition is true, the original code would execute removeThisClass();, which means it should now do nothing, but your code will call doAnything(); when "A" is true.
A: You can put in a comment. Sonar should accept that and it could also help the reader.
void doSomething() {
for (int i = 0; i < 42; i++) // Non-Compliant
{
}
for (int i = 0; i < 42; i++); // Compliant
if (myVar == 4) // Compliant - contains a comment
{
// Do nothing because of X and Y
}
else // Compliant
{
doSomething();
}
try // Non-Compliant
{
}
catch (Exception e) // Compliant
{
// Ignore
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54069452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Find position of a character in a file and store its position bash I need to find all the positions of a specific character ## in a file using Bash script and also store all positions for future use.
This is how the file looks like:
assert property ( ( req1 == 0 ) ##1 ( req1 == 1 ) ##1 !( req2 == 1 ) || (gnt1 == 0 ) );
assert property ( ( req1 == 0 ) ##1 !( req1 == 1 ) || ( gnt1 == 1 ) );
assert property ( ( req1 == 1 && req2 == 0 ) ##1 !( req2 == 1 ) || ( gnt1 == 0 ) );
In the above file I want to get all locations for this character (##) and store them as well. How can this be done using shell script?
A: You could use awk for this:
awk -F'##' '
{
for(i=1;i<NF;i++){
printf "%d ",length($i)+offset+1
offset+=length($i)+length(FS)
}
printf "\n"
offset=0
}' file
The parameter delimiter -F is set as your pattern.
Loop through all portions of the line ($1,$2...) and print the length of each portion that actually indicates the position of the pattern (adding the offset for line that would contain more than one match).
A: Try this
#!/bin/bash
str1="assert property ( ( req1 == 0 ) ##1 ( req1 == 1 ) ##1 !( req2 == 1 ) || (gnt1 == 0 ) );"
str2="assert property ( ( req1 == 0 ) ##1 !( req1 == 1 ) || ( gnt1 == 1 ) );"
str3="assert property ( ( req1 == 1 && req2 == 0 ) ##1 !( req2 == 1 ) || ( gnt1 == 0 ) );"
char="##"
awk -v a="$str1" -v b="$char" 'BEGIN{print index(a,b)}' | xargs expr -1 +
awk -v a="$str2" -v b="$char" 'BEGIN{print index(a,b)}' | xargs expr -1 +
awk -v a="$str3" -v b="$char" 'BEGIN{print index(a,b)}' | xargs expr -1 +
The positions are 32, 32 and 45 for these examples. But there is only the first appearance of the ## char for each one. Not sure if you need to get more appearances.
Solution extracted from Dennis Williamsons comment on this post
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41018841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Hi, I am looking for retaining a state of sorting/pagination while navigating on pages I am using react data grids. Functionality I want to achieve is:
I selected page# and sorted in desc order.
I click on data grid row and go to details page.
I click on back button details page, the page# and sorting order I selected should be retained.
please provide inputs how can we achieve using react grid?
A: You can set the user-selected values in the localStorage
localStorage.setItem('sort', 'desc');
and then when the user returns back to the current page fetch the values from localStorage on the component mount lifecycle method
let sort = localStorage.getItem('sort');
and pass it to the grid Component.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61970190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: VB2013 & MySQL not talking properly and program freezing I have been working on a small project for a while now - it takes a plain text input from an Ardiuno Board (simple text, only a few characters). It's a simple NFC Card tagging program. The program is supposed to take the input from the SerialPort and check the input text against a MySQL database. If it finds the name in the database, then it is to update one column, that's it.
The problem is two fold - first, while I can query the database and get a list of people within the database, the tagging side of the program will not update the database, not matter what input is passed to it. Second - whenever the program receives any input, the program locks up and the GUI becomes unresponsive.
My code is below, and I am happy for any Questions, Comments, or Criticisms. Yes, the MySQL server is on port '8228'. This code is driving me mad, and I apologize as it may seem messy...
Imports System.IO.Ports
Imports System.Threading
Imports System.Text
Imports System.Data.Odbc
Public Class Form1
Dim WithEvents SerialPort As New IO.Ports.SerialPort
Dim ListStr As String
Dim SQLString As String
Dim fstoday As String = Today.Day.ToString + "_" + Today.Month.ToString + "_" + Today.Year.ToString
Dim NextLine As String
Dim PortNum As String
Dim SqlConn As String
Dim sw As StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs)
Timer1.Start()
SerialPort.ReceivedBytesThreshold = 4
PortNum = "COM6"
SqlConn = "mydomain.local"
Call TestSQLConnectionToolStripMenuItem_Click()
Call ConnectSerial()
'create todays log file
Dim filesys As New FileStream("c:\TagLog\Log-" + fstoday + ".txt", FileMode.Append, FileAccess.Write, FileShare.Write)
filesys.Close()
End Sub
Private Sub ConnectSerial()
'set the USB (COM) Port and Bandwidth (BaudRate)
Try
SerialPort.BaudRate = 115200
SerialPort.PortName = PortNum
SerialPort.Open()
LabPort.Text = "Reader OK"
LabPort.ForeColor = Color.Green
Catch
SerialPort.Close()
LabPort.Text = "Reader Not Found"
LabPort.ForeColor = Color.Red
End Try
End Sub
'This handles setting and reading from the serial port
Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
Dim str As String = SerialPort.ReadExisting()
Invoke(myD1, str)
End Sub
'This makes the serial input into String format
Delegate Sub myMethodDelegate(ByVal [text] As String)
Dim myD1 As New myMethodDelegate(AddressOf myShowStringMethod)
Sub myShowStringMethod(ByVal myString As String)
ListStr = ""
SQLString = ""
'display text to our textbox
TextBox2.AppendText(myString)
'Add the last input to the listbox
ListBox1.Items.Add(TextBox2.Text)
ListStr = ListBox1.Items(ListBox1.Items.Count - 1)
SQLString = "Select * From TagTable where QuickName='" + myString + "';"
Try
Dim cn As OdbcConnection = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Dim cmd As New OdbcCommand(SQLString, cn)
SQLString = "UPDATE tagtable SET State = NOT State, Time=Now() WHERE QuickName='" + myString + "';"
sw.WriteLine(vbCr + Now() + " " + myString)
Call UpdateSQL()
cn.Close()
Catch ex As Exception
sw.WriteLine(vbCr + Now() + ex.ToString)
End Try
sw.Close()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'Once per Tick, check what the COM port is saying.
If SerialPort.IsOpen Then
TextBox2.Text = ""
Else
TextBox2.Text = ""
Call ConnectSerial()
End If
End Sub
Private Function IIf(fileExists As Boolean, p2 As String) As Object
Throw New NotImplementedException
End Function
Private Sub UpdateSQL()
Dim cn As OdbcConnection = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
'check connection to the SQL Server and update the records
Dim cmd As OdbcCommand = New OdbcCommand(SQLString, cn)
cn.Open()
LabSQL.ForeColor = Color.Green
LabSQL.Text = "SQL OK"
If SQLString <> "" Then
Try
cmd.ExecuteNonQuery()
cn.Close()
LabSQL.ForeColor = Color.Green
Catch ex As Exception
LabSQL.ForeColor = Color.Red
LabSQL.Text = "SQL Not OK"
sw.WriteLine(vbCr + Now() + " " + ex.ToString)
cn.Close()
End Try
Else
cn.Open()
LabSQL.ForeColor = Color.Green
End If
'If there is a problem, change Sql Label, and clsoe the error'd connection.
cn.Close()
SQLString = ""
End Sub
Private Sub TestSQLConnectionToolStripMenuItem_Click() Handles TestSQLConnectionToolStripMenuItem.Click
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
'check connection to the SQL Server
Try
cn.Open()
LabSQL.ForeColor = Color.Green
LabSQL.Text = "SQL OK"
cn.Close()
'If there is a problem, change Sql Label, display the error in a message box and Close the error'd connection.
Catch ex As OdbcException
LabSQL.ForeColor = Color.Red
LabSQL.Text = "SQL Not OK"
cn.Close()
End Try
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Dim msgans As String
msgans = MsgBox("Are you sure you want to exit?", MsgBoxStyle.YesNo, "Exit?")
If msgans = vbYes Then
SerialPort.Close()
Me.Close()
End If
End Sub
Private Sub ToolStripMenuItem3_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem3.Click
PortNum = "COM1"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem4_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem4.Click
PortNum = "COM2"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem5_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem5.Click
PortNum = "COM3"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem6_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem6.Click
PortNum = "COM4"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem7_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem7.Click
PortNum = "COM5"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem8_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem8.Click
PortNum = "COM6"
Call ConnectSerial()
End Sub
Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
MsgBox("Made by Phill C at Epoq IT. Tag Control V2.3")
End Sub
Private Sub LocalMachineToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LocalMachineToolStripMenuItem.Click
SqlConn = "localhost"
Call TestSQLConnectionToolStripMenuItem_Click()
End Sub
Private Sub OtherLocationToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OtherLocationToolStripMenuItem.Click
SqlConn = InputBox("Enter the SQL Address or Location.", "SQL Location Input", "localhost").ToString
Call TestSQLConnectionToolStripMenuItem_Click()
End Sub
Private Sub ShowUserListToolStripMenuItem_Click() Handles ShowUserListToolStripMenuItem.Click
Dim cn As OdbcConnection
Dim Outstring As String = ""
SQLString = "Select Person,Quickname from TagTable"
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Dim cmd As New OdbcCommand(SQLString, cn)
Dim Query = cmd.ExecuteReader()
Outstring = "FULL NAME, QUICK NAME" + vbCr
While Query.Read
Outstring = Outstring + Query.Item(0) + " , " + Query.Item(1) + vbCr
End While
MsgBox(Outstring)
Query.Close()
cn.Close()
End Sub
Private Sub AddUserToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddUserToolStripMenuItem.Click
Dim QueryFull = InputBox("Enter the New Users Full Name.", "New User Input", "New User").ToString
Dim QueryQName = InputBox("Enter the New Users Quick Name / Nickname.", "New User Input", "New User").ToString
SQLString = "Insert Into TagTable (QuickName,Person,State,Time) Values ('" + QueryQName + "','" + QueryFull + "','In', NOW());"
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Try
Dim cmd As New OdbcCommand(SQLString, cn)
MsgBox("New User has been setup on the Server.")
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox("New User setup has failed, please contact IT Support")
End Try
End Sub
Private Sub DeleteUserToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DeleteUserToolStripMenuItem.Click
Dim QueryFull = InputBox("Enter the Users Full Name.", "Delete User Input", "User To be deleted").ToString
Dim QueryQName = InputBox("Enter the Users Quick Name / Nickname.", "Delete User Input", "User To be deleted").ToString
SQLString = "Delete From TagTable Where QuickName='" + QueryQName + "' AND Person='" + QueryFull + "';"
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Try
Dim cmd As New OdbcCommand(SQLString, cn)
MsgBox("User has been removed from the Server.")
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox("User revomal has failed, please check the full name and quick names, and try again.")
End Try
End Sub
End Class
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26485111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Stacktrace arm-linux-gcc I want to dump stacktrace of my program as the example demonstrated at backtrace[3], but I got result below, instead.
I am using linux 2.6, and arm-linux-gcc 4.3.2.
Running:
arm-linux-gcc prog.c -o prog -rdynamic
the result is:
backtrace() returned 1 addresses
/lib/ld-linux.so.3 [0x40025000]
Could you please help me to solve this problem?
Thanks
I don't have any problem with gcc, But I cant get traces with arm-linux-gcc.
A: According to the GCC ARM Options documentation, you need to pass the -mapcs-frame option to GCC to generate stack frames on the ARM platform.
-mapcs-frame
Generate a stack frame that is compliant with the ARM Procedure Call Standard for all functions, even if this is not strictly necessary for correct execution of the code. Specifying -fomit-frame-pointer with this option causes the stack frames not to be generated for leaf functions. The default is -mno-apcs-frame.
This was pointed out to me in a comment to my Linux specific answer to How to generate a stacktrace when my gcc C++ app crashes, which you may also find useful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10864882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to change height of country_picker? I am using country_picker for drop-down-menu.
And I need to reduce height of this menu. How can I do this?
And how to get border to showCountryPicker?
This is what I want
And this what I get
I tried to add bottomSheetHeight, but it hides my bottom buttons.
And without bottomSheetHeigh the drop-down-menu is in full screen mode
This is my code:
Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 12, right: 12),
child: TextFormField(
controller: _country,
readOnly: true,
onTap: () {
showCountryPicker(
context: context,
showWorldWide: false,
showPhoneCode: false,
showSearch: false,
countryListTheme: CountryListThemeData(
backgroundColor: AppColors.backgroundColor,
borderRadius: BorderRadius.circular(8),
bottomSheetHeight: 380,
flagSize: 0,
textStyle: TextStyle(
color: AppColors.grayA0A0A0,
fontSize: 18,
height: 2.0
)
),
onSelect: (Country country) {
log(country.toString());
}
);
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
borderSide: const BorderSide(width: 0)),
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(width: 1, color: AppColors.darkGray),
borderRadius: BorderRadius.circular(10)),
hintText: "Choose a country",
hintStyle: const TextStyle(
color: AppColors.grayA0A0A0, fontWeight: FontWeight.w500),
filled: true,
fillColor: AppColors.lightDark,
contentPadding:
const EdgeInsets.only(left: 8, bottom: 20, top: 20),
prefixIcon: InkWell(
child: SvgPicture.asset(
"assets/icons/Country.svg",
color: AppColors.grayA0A0A0,
height: 14,
width: 18,
fit: BoxFit.scaleDown,
),
),
suffixIcon: InkWell(
child: SvgPicture.asset(
"assets/icons/arrow_down.svg",
color: AppColors.grayA0A0A0,
height: 14,
width: 18,
fit: BoxFit.scaleDown,
),
)
),
),
),
),
A: Row(
children: <Widget>[
Expanded(
flex: 1,
//SizedBox(height: 20.0),
child: CountryPicker(
dense: true,
showFlag: false, //displays flag, true by default
showDialingCode:
true, //displays dialing code, false by default
showName: true, //displays country name, true by default
showCurrency: false, //eg. 'British pound'
showCurrencyISO: false,
onChanged: (Country country) {
setState(() => _selected = country);
print(country.dialingCode);
countryCode = country.dialingCode;
},
selectedCountry: _selected,
),
),
Expanded(
flex: 3,
//SizedBox(height: 20.0),
child: TextFormField(
decoration: InputDecoration(
labelText: 'Mobile no.',
border: OutlineInputBorder(),
),
validator: (val) => val.length != 10
? 'Enter a mobile number of 10 digits'
: null,
onChanged: (val) {
setState(() => phone = val);
phoneno = phone;
},
),
),
],
),
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74445514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Database state is showing as 'Restoring' for a longtime when I do with NORECOVERY option I have a two backup files (MS SQL SERVER)
1) Demo.bak
2)DemoDiff.bak
I want to restore the Base database (Demo.bak) then Differential backup (DemoDiff.bak).
As I need to restore the differential database then I have to restore my base database with NORECOVERY option. But, when I restore with NORECOVERY option the database state is showing as 'Restoring' for a long time (Actually it as only 3519 KB size).
Can anyone help me out from this?
A: RESTORING is the expected state of a database after a RESTORE with NORECOVERY. You can then apply transaction log backups or a differential backup.
Recovery takes the database from RESTORING to ONLINE.
A: You can restore log files till the database is no recovery mode. If the database is recovered it will be in operation and it can continue database operation. If the database has another operations we cannot restore further log as the chain of the log file after the database is recovered is meaningless. This is the reason why the database has to be norecovery state when it is restored.
There are three different ways to recover the database.
1) Recover the database manually with following command.
RESTORE DATABASE database_name WITH RECOVERY
2) Recover the database with the last log file.
RESTORE LOG database_name FROM backup_device WITH RECOVERY
3) Recover the database when bak is restored
RESTORE DATABASE database_name FROM backup_device WITH RECOVERY
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46161154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: push multiple Line Text as one message in a kafka topic I want to push a text consisting of multiple lines as one message into a kafka topic.
After I enter:
kafka-console-producer --broker-list localhost:9092 --topic myTopic
and copy my text:
My Text consists of:
two lines instead of one
I get two messages in the kafka topic, but I want to have just one. Any ideas how to achieve that? Thanks
A: It's not possible with kafka-console-producer as it uses a Java Scanner object that's newline delimited.
You would need to do it via your own producer code
A: You can use kafkacat for this, with its -D operator to specify a custom message delimiter (in this example /):
kafkacat -b kafka:29092 \
-t test_topic_01 \
-D/ \
-P <<EOF
this is a string message
with a line break/this is
another message with two
line breaks!
EOF
Note that the delimiter must be a single byte - multi-byte chars will end up getting included in the resulting message See issue #140
Resulting messages, inspected also using kafkacat:
$ kafkacat -b kafka:29092 -C \
-f '\nKey (%K bytes): %k\t\nValue (%S bytes): %s\n\Partition: %p\tOffset: %o\n--\n' \
-t test_topic_01
Key (-1 bytes):
Value (43 bytes): this is a string message
with a line break
Partition: 0 Offset: 0
--
Key (-1 bytes):
Value (48 bytes): this is
another message with two
line breaks!
Partition: 0 Offset: 1
--
% Reached end of topic test_topic_01 [0] at offset 2
Inspecting using kafka-console-consumer:
$ kafka-console-consumer \
--bootstrap-server kafka:29092 \
--topic test_topic_01 \
--from-beginning
this is a string message
with a line break
this is
another message with two
line breaks!
(thus illustrating why kafkacat is nicer to work with than kafka-console-consumer because of its optional verbosity :) )
A: With Console-consumer you are obviously running tests for your expected data coming from client. If it is a single message, better keep it as a single string by adding a unique delimiter as identifier. e.g.
{this is line one ^^ this is line two}
Then handle the message accordingly in your consumer job. Even if client is planning to send multiple sentences in message, better make it in a single string, it will improve serialization of your message and will be more efficient after serialization.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52151816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: access/set object's values by indexing it by property name I have an object called caser and it has the following properties:
export interface ICaser {
consulter: string;
associater: string;
typologies: string[];
id:number;
}
const caser: ICaser = {
consulter: "john",
associater: "Huns",
typologies: ['starter', 'beginner','intermediary','advanced']
};
And I am accessing the property by indexing, as follows:
_caser[fieldName as keyof ICaser] = value.key as string;
However, this works only for properties which are string type and not for property 'typologies' which is an array of strings.
My question is, how can I make it more generic that it can take any property, whether it is of type string, integer or array?
const handleOnFieldChange = (fieldName: string, value: IDropdownOption, index?: number | undefined) => {
let _caser = Object.assign({}, caser);
var vls;
if (fieldName === "typologies") {
vls = value.selected ?
[..._caser.typologies!, value.key as string] : _caser.typologies.filter(key => key !== value?.key);
_caser['typologies'] = vls;
} else {
_caser[fieldName as keyof ICaser] = value.key as string;
}
setCaser(_caser);
}
using the example above, I will get the following which of course makes sense, but how do I solve it?
ype 'string' is not assignable to type 'string & string[]'.
Type 'string' is not assignable to type 'string[]'.
Edit:
using it as follows: _caser[fieldName], gives the following error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ICaser'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73031564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: My data shows on one page and not the other on Ember I'm using Ember Data to build a web app, and somehow data shows on one template and not the other. My Ember console shows that the model is correctly hooked up to the route, but I don't know why the data won't show.
The data I'm trying to show is {{stackTitle}} in model 'stack'.
I'm using the local storage adapter provided via Ember's tutorial... maybe that's the problem?
Here's my template (the one that's not displaying data):
<script type="text/x-handlebars" data-template-name="stack">
<div class="container-fluid">
<div class="row">
<a href="#"><button class="btn btn-default" type="button">Back</button></a>
<button class="btn btn-default" type="submit">Save</button>
</div>
<h1>
<label {{action "editStack" on="doubleClick"}}>{{stackTitle}}</label>
{{input
value=stackTitle
action="createStack"}}
{{debugger}}
<div>{{stackTitle}}</div>
</h1>
{{partial "todos"}}
</div>
</script>
And here's my router:
Todos.StackRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('stack', params.stack_id);
},
});
My controller:
Todos.StackController = Ember.Controller.extend({
setupController: function(controller, model) {
controller.set('model', model);
},
actions: {
createStack: function() {
var title = this.get('stackTitle');
if (!title.trim()) { return; }
var stack = this.store.createRecord('stack', {
stackTitle: title,
});
stack.save().then(function() {
var promises = Ember.A();
stack.get('todos').forEach(function(todo) {
promises.push(todo.save());
});
Ember.RSVP.Promise.all(promises).then(function(resolvedPromises){
alert('all saved!');
})
});
console.log(this.store.all('stack'));
},
}
});
My model:
Todos.Stack = DS.Model.extend({
stackTitle: DS.attr('string'),
todos: DS.hasMany('todo', {async: true} ),
isTaken: DS.attr('boolean'),
});
I'd love if you could point me in the right direction. Thank you!
A: setupController isn't needed (it's doing the exact same job as the model hook in your route, after the model hook as already done it's work. Delete it.
As for your issue, I don't think Ember.Controller proxies model properties. You'd need to use Ember.ObjectController to do that, but seeing as Ember.ObjectController is on Tom Dale's hit list (it's going away eventually), really you should access stackTitle in your templates as model.stackTitle.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29550603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to return a Map of distinct values and their count for a user in Spring Data JPA? I am working on a Spring application and use Spring Data JPA for database manipulation. I have come across a problem with creating a query.
I have a table where users store products. I want to retrieve a Map for a given user, where I will have information about all distinct categories that the given user has his products in, and their count. In native sql that would be the following query :
SELECT category, count(*) FROM products where user_id = 1 GROUP BY category;
Can you help me achieving it in a Spring Data Jpa Repository? How should the @Query look like? And how to return the data as a Map?
Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53864136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Get value from Modal View in Swift iOS i'm trying to start writing Swift and i'm trying to get a value from a modal view controller with no luck.
I have two controllers, the ViewController and modalViewController.
In ViewController i have a UITableView and with a press of a button i open the modalViewController.
Then from a UITextField i pass the value.
I have implement a protocol with delegate and func but somewhere i'm missing something or had it wrong.
ViewController.swift
import UIKit
class ViewController: UIViewController,UITableViewDelegate,modalViewControllerDelegate{
@IBOutlet var table: UITableView!
var tableData = ["First Row","Second Row","Third Row"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
table.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(table:UITableView?,numberOfRowsInSection section: Int) -> Int
{
return tableData.count
}
func tableView(table:UITableView?,cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default,reuseIdentifier:"cell")
cell.textLabel?.text = tableData[indexPath.row]
return cell
}
func sendText(text: NSString) {
tableData.append(text)
} }
modalViewController.swift
import UIKit
protocol modalViewControllerDelegate {
func sendText(var text: NSString)
}
class modalViewController: UIViewController{
let delegate: modalViewControllerDelegate?
@IBOutlet var textField: UITextField?
@IBAction func cancelButton(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func saveButton(sender: AnyObject) {
delegate?.sendText(self.textField!.text)
dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
I have no errors in the code, the delegate is not working, it's always nil.
Thanks.
A: You have to assign the delegate in your first view controller.
Also, you have to change let delegate: modalViewControllerDelegate? to a var, or else you can't change it.
Right now your delegate is empty.
It's unclear how you're accessing ModalViewController. If you're using segues:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "modalViewControllerSegue" {
var destination = segue.destinationViewController as CategoryViewController
destination.delegate = self
}
}
Or if you're doing it programmatically:
var modalViewController = ModalViewController(parameters)
modalViewController.delegate = self
presentViewController(modalViewController, animated: true, completion: nil)
Storyboard identifier:
let destination = UIStoryboard.mainStoryboard().instantiateViewControllerWithIdentifier("ModalViewController") as ModalViewController
delegate = self
showViewController(destination, sender: nil)
EDIT:
If you want to access ModalViewController by selecting a cell you need the tableView: didSelectRowAtIndexPath method:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("modalViewControllerSegue", sender: self)
}
Using this, you'll need the method prepareForSegue to set the delegate.
A: You have to set your modalViewController's delegate property before presenting it. If you're using segues, you can do this in prepareForSegue(_:).
Also, class names should begin with uppercase letters (modalViewController should be ModalViewController). Only instances should begin with lowercase letters.
A: Another option, instead of using delegation, is to use an unwind segue. Here's a tutorial: http://www.cocoanetics.com/2014/04/unwinding/
In your case, in your presenting view controller you could have the method:
func returnFromModalView(segue: UIStoryboardSegue) {
// This is called when returning from the modal view controller.
if let modalVC = segue.sourceViewController as? ModalViewController
where segue.identifier == "mySegueID" {
let text = modalVC.textField.text
// Now do stuff with the text.
}
}
And then just link up everything in the Interface Builder as shown in the tutorial.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29462380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Data not showing on Firebase I've been following this tutorial on how to use Google Firebase. I've been following the code and because I kept seeing:
Error: No resource found that matches the given name (at 'paddingBottom' with value '@dimen/ activity_vertical_margin')
I added a few lines to app/srs/main/res/values/dimens so it now looks like this:
<resources>
<dimen name="fab_margin">16dp</dimen>
<dimen name="activity_vertical_margin">5dp</dimen>
<dimen name="activity_horizontal_margin">5dp</dimen>
</resources>
I'm trying to add items to the database but I can't seem to end the file by clicking the button. Consequently, no data is showing up on Firebase. Cheers!
A: Please recheck once:
1) Go to Firebase console, select Database.
2) Selecte Rules.
paste below one:
{
"rules": {
".read": true,
".write": true
}
}
Your Activity should be:
public class YourActivity extends AppCompatActivity implements View.OnClickListener {
public static FirebaseDatabase mFirebaseDatabase;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFirebaseDatabase = FirebaseDatabase.getInstance();
final EditText edittext = (EditText) findViewById(R.id.edittext);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (edittext.getText().toString().length() > 0) {
mFirebaseDatabase.getReference("myref").push().setValue(edittext.getText().toString());
}
}
});
}
}
and your_activity.xml will be
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Item"/>
</LinearLayout>
A: Please try to give margin at xml like this:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
/>
Note this will solve the error which you mention above .
Hope this will help you out..and let me
know your feedback
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45811244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Handle import of modules inside of a project I have the following project architecture (simplified):
root/
main.py
mypackage/
__init__.py
module1.py
module2.py
ci_scripts/
script1.py
script2.py
doc/
doc
where the root is nothing more than a folder.
How do I import module1 and module2 in script1.py for example?
I tried to:
*
*Add the relative path inside script1.py: from ..mypackage import module1
*The absolute path
*Use of sys package to append the path of mypackage
To give more context, I was expecting that the following code inside of script1.py would work:
from ..mypackage import module1
module1.func1()
but I get:
ImportError: attempted relative import with no known parent package
And when I try to use the absolute path:
import mypackage.module1
module1.func1()
I get the following error:
ModuleNotFoundError: No module named 'mypackage'
A: Your absolute import probably does not work because your root folder is not set to be mypackage. You can see here on how to do that: python: Change the scripts working directory to the script's own directory
Alternatively, you can use relative imports. You are correctly importing with from ..mypackage import module1 - however, you cannot execute a script directly with a relative import. You need to import the script into some other module which you are then executing. See explanation here: Relative imports in Python 3
A: I've had similar problems in the past and thus I've created a new import library: ultraimport
It gives you more control over your imports and lets you do file system based relative and absolute imports that do always work.
In your script1.py you could then write:
import ultraimport
module1 = ultraimport("__dir__/../mypackage/module1.py")
This will always work, no matter how you run your program and independent of all external factors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75396874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Access same file in Native Client and JavaScript Is there a way to open a file in JavaScript and share that same file with a NativeClient module? I need direct file access in Native Client and JavaScript.
Is this possible?
A: Yes. The HTML5 filesystems (both PERSISTENT and TEMPORARY) are shared between JavaScript and NaCl. You can, for example, write files in JavaScript and then read them them native code.
See: http://www.w3.org/TR/file-system-api/
And: https://developers.google.com/native-client/dev/devguide/coding/file-io
On the NaCl side you can also access the HTML5 filesystems with POSIX I/O operations by using the nacl_io library.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22541297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to click second time on recycle view and firsr time data is show in android i use a flag but this not work any one can help me @Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final MyportfolioRecycleview_Record record = dataList.get(position);
for(int i=0;i< dataList.size();i++) {
holder.issuerNameInBoldLetters.setText(record.getIssuerNameInBoldLetters());
holder.issuerNameInNormalLetters.setText(record.getIssuerNameInNormalLetters());
holder.bondCoupon.setText(record.getBondCoupon() + "%");
holder.bondMaturityDate.setText(record.getBondMaturityDate());
holder.currency.setText(record.getCurrency());
holder.totalBondPrice.setText(record.getTotalBondPrice());
holder.bondPrice.setText(record.getBondPrice());
holder.priceChange.setText(record.getPriceChange());
holder.pricename.setText(record.getPicename());
holder.daychange.setText(record.getDaychange());
}
holder.layout2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(clicktime=true) {
Toast.makeText(getContext(), "datachanged", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
updateData(dataList1);
mAdapter.notifyDataSetChanged();
clicktime=false;
}
if(clicktime=false){
Toast.makeText(getContext(), "datachanged", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
updateData1(dataList);
mAdapter.notifyDataSetChanged();
clicktime=true;
}
}
});
A: holder.layout2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/* if(clicktime=true)*/ if(clicktime==true) {
Toast.makeText(getContext(), "datachanged", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
updateData(dataList1);
mAdapter.notifyDataSetChanged();
clicktime=false;
}
/* if(clicktime=false)*/ if(clicktime==false){
Toast.makeText(getContext(), "datachanged", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
updateData1(dataList);
mAdapter.notifyDataSetChanged();
clicktime=true;
}
}
});
A: To check equivalency in Java, you need to use double equals. Or, you can just put if(clicktime) for true
if(!clicktime) for false
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44320088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How do I intercept the unbuffered output of a Proc::Async in Raku? With a snippet like
# Contents of ./run
my $p = Proc::Async.new: @*ARGS;
react {
whenever Promise.in: 5 { $p.kill }
whenever $p.stdout { say "OUT: { .chomp }" }
whenever $p.ready { say "PID: $_" }
whenever $p.start { say "Done" }
}
executed like
./run raku -e 'react whenever Supply.interval: 1 { .say }'
I expected to see something like
PID: 1234
OUT: 0
OUT: 1
OUT: 2
OUT: 3
OUT: 4
Done
but instead I see
PID: 1234
OUT: 0
Done
I understand that this has to do with buffering: if I change that command into something like
# The $|++ disables buffering
./run perl -E '$|++; while(1) { state $i; say $i++; sleep 1 }'
I get the desired output.
I know that TTY IO::Handle objects are unbuffered, and that in this case the $*OUT of the spawned process is not one. And I've read that IO::Pipe objects are buffered "so that a write without a read doesn't immediately block" (although I cannot say I entirely understand what this means).
But no matter what I've tried, I cannot get the unbuffered output stream of a Proc::Async. How do I do this?
I've tried binding an open IO::Handle using $proc.bind-stdout but I still get the same issue.
Note that doing something like $proc.bind-stdout: $*OUT does work, in the sense that the Proc::Async object no longer buffers, but it's also not a solution to my problem, because I cannot tap into the output before it goes out. It does suggest to me that if I can bind the Proc::Async to an unbuffered handle, it should do the right thing. But I haven't been able to get that to work either.
For clarification: as suggested with the Perl example, I know I can fix this by disabling the buffering on the command I'll be passing as input, but I'm looking for a way to do this from the side that creates the Proc::Async object.
A: You can set the .out-buffer of a handle (such as $*OUT or $*ERR) to 0:
$ ./run raku -e '$*OUT.out-buffer = 0; react whenever Supply.interval: 1 { .say }'
PID: 11340
OUT: 0
OUT: 1
OUT: 2
OUT: 3
OUT: 4
Done
A: Proc::Async itself isn't performing buffering on the received data. However, spawned processes may do their own depending on what they are outputting to, and that's what is being observed here.
Many programs make decisions about their output buffering (among other things, such as whether to emit color codes) based on whether the output handle is attached to a TTY (a terminal). The assumption is that a TTY means a human is going to be watching the output, and thus latency is preferable to throughput, so buffering is disabled (or restricted to line buffering). If, on the other hand, the output is going to a pipe or a file, then the assumption is that latency is not so important, and buffering is used to achieve a significant throughput win (a lot less system calls to write data).
When we spawn something with Proc::Async, the standard output of the spawned process is bound to a pipe - which is not a TTY. Thus the invoked program may use this to decide to apply output buffering.
If you're willing to have another dependency, then you can invoke the program via. something that fakes up a TTY, such as unbuffer (part of the expect package, it seems). Here's an example of a program that is suffering from buffering:
my $proc = Proc::Async.new: 'raku', '-e',
'react whenever Supply.interval(1) { .say }';
react whenever $proc.stdout {
.print
}
We only see a 0 and then have to wait a long time for more output. Running it via unbuffer:
my $proc = Proc::Async.new: 'unbuffer', 'raku', '-e',
'react whenever Supply.interval(1) { .say }';
react whenever $proc.stdout {
.print
}
Means that we see a number output every second.
Could Raku provide a built-in solution to this some day? Yes - by doing the "magic" that unbuffer itself does (I presume allocating a pty - kind of a fake TTY). This isn't trivial - although it is being explored by the libuv developers; at least so far as Rakudo on MoarVM goes, the moment there's a libuv release available offering such a feature, we'll work on exposing it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63486337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Changes not detected in pull requests on Jenkins pipeline plugin I have Jenkins configured to build on pull requests (PR). Our repository is a multi project repository and I have created a script to detect the changes that were made to source code and only run tests that are relevant to the projects that had changes in them (according to the changed file's path):
def getChangedProjects() {
Set projects = []
def changeLogSets = currentBuild.changeSets
for (int i = 0; i < changeLogSets.size(); i++) {
def entries = changeLogSets[i].items
for (int j = 0; j < entries.length; j++) {
def entry = entries[j]
def files = new ArrayList(entry.affectedFiles)
for (int k = 0; k < files.size(); k++) {
def file = files[k]
// get the project folder name and
// add it to changed projects set
projects.add(file.path.tokenize('/')[1])
}
}
}
return projects.findAll {it != null}
}
The Groovy function works as expected and detects the folder that has changed.
Problem is that most of the times Jenkins will not show any changes in Jenkins:
But the PR did contain changes to files and I can see these changes in Github of course.
Anyone know why Jenkins is not showing the changes ?
A: You may create a change log by including a Git Changelog step in the Jenkins pipeline script.
This plugin provides a context object that contains all the information needed to create a changelog. It can also provide a string that is a rendered changelog, ready to be published.
Here is a screenshot of a sample Git changelog produced by this plugin:
More information about this plugin may be found in its wiki.
Hope, it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53537379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: HTML custom form element does not send submit event Created a custom HTML element derived from HTMLFormElement and added listener for "submit" event in constructor. The element is registered properly but the submit handler is never called...
class MyForm extends HTMLFormElement {
constructor() {
super();
this.addEventListener('submit', this.mySubmit);
}
mySubmit() {
console.log('mySubmit was called');
}
connectedCallback() {
console.log('Custom form element added to page.');
}
}
customElements.define('my-form', MyForm, {
extends: 'form'
});
<!DOCTYPE html>
<html lang="de-DE">
<head>
<title>My Form</title>
<meta charset="utf-8">
<!--<script src="myform.js" async="true"></script>-->
</head>
<body>
<h1>My Form</h1>
<my-form>
<p><input type="input" value="Whoa!" /></p>
<p><button type="submit">Submit</button></p>
</my-form>
</body>
</html>
A: As written in the documentation for the custom elements interface, you have to "bind" the custom element functionality to the HTML by using the is="" attribute.
There seems to be differences between custom elements:
1) The ones that use their own shadow DOM ( "stand alone element", "autonomous element" ), and hence are forced to extend HTMLElement ( so not HTMLFormElement ), can be written in the <my-form> style inside the HTML.
2) For custom elements that do not extend HTMLElement, but try to extend other things, like a HTMLFormElement, it seems you need to use <form is="your-defined-name"></form>, ( "customized builtin element" )
https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#Customized_built-in_elements
class MyForm extends HTMLFormElement {
constructor() {
super();
this.addEventListener('submit', this.mySubmit);
}
mySubmit() {
console.log('mySubmit was called');
}
connectedCallback() {
console.log('Custom form element added to page.');
}
}
customElements.define('my-form', MyForm, {
extends: 'form'
});
<!DOCTYPE html>
<html lang="de-DE">
<head>
<title>My Form</title>
<meta charset="utf-8">
<!--<script src="myform.js" async="true"></script>-->
</head>
<body>
<h1>My Form</h1>
<form is="my-form">
<p><input type="input" value="Whoa!" /></p>
<p><button type="submit">Submit</button></p>
</form>
</body>
</html>
A: You could do it without is="" by inheriting HTMLElement by adding your custom mySubmit event, consider the following:
'use strict';
class MyForm extends HTMLElement {
constructor() {
super();
this.addEventListener('mySubmit', this.mySubmit);
debugger;
}
get action() {
return this.getAttribute('action') || window.location.href;
}
mySubmit() {
console.log('mySubmit was called');
window.location = this.action;
}
connectedCallback() {
console.log('Custom form element added to page.');
this.querySelector('[type=mySubmit]').onclick = () => {
this.dispatchEvent(new CustomEvent('mySubmit')); //,{type: 'submit'});
}
}
}
customElements.define('my-form', MyForm); //, {extends: 'form'});
<!DOCTYPE html>
<html lang="de-DE">
<head>
<title>My Form</title>
<meta charset="utf-8">
<!--<script src="myform.js" async="true"></script>-->
</head>
<body>
<h1>My Form</h1>
<my-form action="https://www.google.com">
<p><input type="input" value="Whoa!" /></p>
<p><button type="mySubmit">Submit</button></p>
</my-form>
<hr>
<h1>My Form 2</h1>
<my-form>
<p><input type="input" value="Whoa2!" /></p>
<p><button type="mySubmit">Submit</button></p>
</my-form>
</body>
</html>
A: Thanks a lot for your help! There was only a tiny piece of code missing to make it happen... 'action="#"' in the element. Best regards, Oliver
Now the code looks like this and works as expected:
<!DOCTYPE html>
<html lang="de-DE">
<head>
<title>My Form</title>
<meta charset="utf-8">
<script async="true">
class MyForm extends HTMLFormElement {
constructor() {
super();
console.log('Custom form element created.');
this.addEventListener('submit', this.mySubmit);
}
mySubmit(event) {
event.preventDefault();
console.log('mySubmit was called');
}
connectedCallback() {
console.log('Custom form element added to page.');
}
}
customElements.define('my-form', MyForm, { extends: 'form' });
</script>
</head>
<body>
<h1>My Form</h1>
<form is="my-form" action="#">
<p><input type="input" value="Whoa!"></input></p>
<p><button type="submit">Submit</button></p>
</form>
</body>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57112440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: svg to woff font I have an SVG font file that is exactly how I want it. When I run it through a converter though (http://onlinefontconverter.com/), the output WOFF file displays different in Chome vs IE9. In IE9, the vertical alignment of the font is off (if I set font-size:100px;line-height:100px; it looks fine in Chrome, but in IE9 the top of the glyphs are chopped off).
Is this a problem with IE9 incorrectly displaying WOFF files, or is there more to it than that?
I did a test where I converted my Courier New TTF file into WOFF, and it displays fine in both browsers. When I take the Courier New SVG, however, and convert that to WOFF, the same display issue arises.
Thanks!
EDIT: The display issue also occurs with EOT files and in IE10. It seems to me like there is some issue converting SVG -> WOFF, but I don't know much about the topic.
A: For IE < 9 you should use EOT files. WOFF is for modern browsers. The FontSquirrel webfont generator is really helpful for this and will give you the @font-face kit too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15350654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android or Java class naming with $ symbol I'm reviewing a certain project and I see that there are many classes with the same name, but with a dollar ($) symbol at the end + increasing number. For example
Class.java
Class$1.java
Class$2.java
Class$n.java
OtherClass.java
OtherClass$1.java
OtherClass$n.java
What does it mean?
A: The dollar sign is used by the compiler for inner classes. I thought it would be strange to manually make classes/files with those names though: As far as I know it's a compiler thing.
A: AFAIK if it's has number it's an anonymous inner class, if it has a name after $ sign it means just inner class.
Edit:
More about how compiler handles you can see here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5203829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Add Object onStartPage itextPdf except the last Page I am adding a rectangle on top of my page for all pages but I do not want the rectangle on the last page. Here is my code:
@Override
public void onStartPage(PdfWriter writer, Document output) {
Font bold = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD);
bold.setStyle(Font.UNDERLINE);
bold.setColor(new BaseColor(171, 75, 15));
PdfContentByte cb = writer.getDirectContent();
// Bottom left coordinates x & y, followed by width, height and radius of corners.
cb.roundRectangle(100f, 1180f, 400f, 100f, 5f);//I dont want this on the ;ast page
cb.stroke();
try {
output.add(new Paragraph("STATEMENT OF ACCOUNT", bold));
output.add(new Paragraph(new Phrase(new Chunk(" "))));
output.add(new Paragraph(new Phrase(new Chunk(" "))));
output.add(new Paragraph(new Phrase(new Chunk(" "))));
output.add(new Paragraph(new Phrase(new Chunk(" "))));
Image logo = Image.getInstance(imagepath);
logo.setAbsolutePosition(780, 1230);
logo.scaleAbsolute(200, 180);
writer.getDirectContent().addImage(logo);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
Is there a way to either skip or remove this rectangle from the last Page of the document?
A: First of all iText developers often have stressed that in onStartPage one MUST NOT add content to the PDF. The reason is that under certain circumstances unused pages are created and onStartPage is called for them but they then are dropped. If you add content to them in onStartPage, though, they are not dropped but remain in your document.
Thus, always use onEndPage to add any content to a page.
In your use case there is yet another reason for using onEndPage: Usually it only becomes clear that a given page is the last page when the last bit of content has been added to the document. This usually occurs after onStartPage has been called for the page but before onEndPage has.
Thus, after you've added the last bit of regular page content to the document, you can simply set a flag in the page event listener that the current page is the final document page. Now the following onEndPage call knows it processes the final page and can add content differently.
So the page event listener would look like this
class MyPageEventListener extends PdfPageEventHelper {
public boolean lastPage = false;
@Override
public void onEndPage(PdfWriter writer, Document output) {
if (!lastPage) {
[add extra content for page before the last one]
} else {
[add extra content for last page]
}
}
...
}
and be used like this
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, TARGET);
MyPageEventListener pageEventListener = new MyPageEventListener();
writer.setPageEvent(pageEventListener);
document.open();
[add all regular content to the document]
pageEventListener.lastPage = true;
document.close();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52774562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Performance of the LightSwitch HTML Client's Tables_SingleOrDefault and Tables.filter operations We're working with the Visual Studio 2013 version of LightSwitch, and have a number of areas in our HTML Client screens where we've used the following approach to retrieve an entity with a specific id: -
myapp.activeDataWorkspace.ApplicationData.Tables.filter("Id eq " + msls._toODataString(idToFind, ":Int32")).execute()
As we're interested in improving the performance of these screens, I wondered if anyone knows if the following alternative approach would make any difference to the speed? : -
myapp.activeDataWorkspace.ApplicationData.Tables_SingleOrDefault(idToFind).execute()
Whilst the second approach seems more appropriate in this type of situation, as we've a significant number of the former method, I wanted to quantify the value of this change before initiating it (and the re-testing this would entail).
A: Both approaches will produce SQL and execute it on the server. The SQL should be similar/identical and performance will be near identical. If you want to see the SQL being produced i suggest you open up the "SQL Server Profiler" and run a Trace! The trace will also show you execution time taken. Side note: Your performance gains will come from correctly configured Table Indexes.
A: I know its old question but i would like to add some info...
Even both are translated to SQL query and executed on SQL Server, the difference in performance will be related to the way that lightSwitch (oData v3) Generate the statement..
Taking in consideration between the following;
1- select * from Table where colA like ('foo')
2- select * from Table where colA = 'foo' TOP(1)
general if colA is primary Key at the table then SQL will stop searching after the first match on the second if just want to retrieve only one ,, and the equal is better performance...
you can trace the generated link query from each one on file msls-2.5.2.js line 6803 to 6900.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30916790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add bar to each group to represent group mean? I am interested in adding a bar to each group (species) to represent each group average. For example, in the below example, I have four separate groups, I would like to add another bar to each group to represent each group average.
thank you
library(ggplot2)
# create a dataset
specie <- c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3) )
condition <- rep(c("normal" , "stress" , "Nitrogen") , 4)
value <- abs(rnorm(12 , 0 , 15))
data <- data.frame(specie,condition,value)
head(data)
# Grouped
ggplot(data, aes(fill=condition, y=value, x=specie)) +
geom_bar(position="dodge", stat="identity")
A: I would do it this way:
library(tidyverse)
dat %>%
group_by(species) %>%
summarise(conditions = 'average', values = mean(values)) %>%
bind_rows(dat) %>%
ggplot(aes(x = species, y = values, fill = conditions)) +
geom_col(position = "dodge") +
ggthemes::theme_tufte() +
scale_fill_brewer(palette = 'Set2')
Data
set.seed(57377888)
dat <- data.frame(
species = c(
rep("sorgho" , 3),
rep("poacee" , 3),
rep("banana" , 3),
rep("triticum" , 3)
),
conditions = rep(c('normal', 'stress', 'nitrogen'), 4),
values = abs(rnorm(12, 0, 15)),
stringsAsFactors = F
)
A: What you’re looking for is called a summary statistic (stat_summary in ggplot2 parlance).
And rather than another bar, I suggest adding a new geometry that’s less ambiguous. A dot is conventional, or a short horizontal bar.
Here’s a minimal code to add it:
ggplot(data, aes(fill = condition, x = specie, y = value)) +
geom_col(position = 'dodge') +
stat_summary(aes(group = specie), fun.y = mean, geom = 'point')
(Note that I’ve used geom_col() instead of geom_bar(stat = 'identity').)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57377888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Best way to store a list of objects in ASP.Net MVC In my current project, I am building an object list from multiple database tables. I am currently storing them in the user session (Global.asax/Session_Start) as showed below.
protected void Session_Start()
{
Session.Add("listeOF", new ListOf());
}
This is working and I can use the data, but I was wondering if there's a better way to store it (by better I mean faster access). I call this data in my controllers.
A: You need some other data store to keep it across postback requests, so if it's global to the application, you can use application cache, but if it's specific to the user, then session is fine. If there isn't that much data involved and it's not that intensive as a read, you may want to consider whether there is a benefit to caching a chunk of data vs just re-querying it when needed.
To get more advanced and present another alternative that is more involved, a CQRS implementation is a possibility (also see this); the idea there is one data container is for transaction data, and another for reads (whether that is a separate database or table, or even a document database as some possibilities).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44441601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Closing AlertDialog.Builder in Android In the following code, I tried to dismiss the AlertDialog box but to no avail. However, if I remove compareKeys() function, the dismiss will work. So how can I make it dismiss after calling the compareKeys() function?
public void promptAdministratorPassword() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Alert!");
alert.setMessage("Please enter your password: ");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
password = input.getText().toString();
if (password.equals("password")) {
try {
compareKeys();
} catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
}
}
dialog.dismiss();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
A: Call dialog.dismiss() before password = input.getText().toString() and add dialog.dismiss() inside setNegativeButton's OnClickListener too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41082391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I map an array in ruby? I have an array of integers
a = [3, 4, 5, 6]
and I need to POW this numbers, so they can be like this
a
# => [9, 16, 25, 36]
I'm trying to do this with this piece of code:
a.map!(&:**2)
but Isn't working :(
Can anyone help me?
A: You can use a lambda with & if you so desire:
square = lambda { |x| x**2 }
a.map!(&square)
This sort of thing is pointless busywork with a block so simple but it can be nice if you have a chain of such things and the blocks are more complicated:
ary.select(&some_complicated_criteria)
.map(&some_mangling_that_takes_more_than_one_line)
...
Collecting bits of logic in lambdas so that you can name the steps has its uses.
A: You should do this
a.map! { |i| i**2 }
Read the docs.
A: As a matter of rule, you cannot add parameters to methods using the &:sym syntax.
However, if you follow my suggestion here you could do the following:
class Symbol
def with(*args, &block)
->(caller, *rest) { caller.send(self, *rest, *args, &block) }
end
end
a.map!(&:**.with(2))
# => [9, 16, 25, 36]
A: You can only use the &: shortcut syntax if you are calling a method on the object with no arguments. In this case, you need to pass 2 as an argument to the ** method.
Instead, expand the block to the full syntax
a.map! { |n| n**2 }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23718037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Named pipe throws exception after few connections I have 2 applications: 1 dispatcher and second receiver.
I'm using Name pipe server and client to send to message from dispatcher to receiver
public partial class DispatcherForm : Form
{
public DispatcherForm()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
var pipe = new NamedPipeServerStream("DispatcherPipe", PipeDirection.InOut);
pipe.WaitForConnection();
Task.Run(async () =>
{
var buffer = Encoding.UTF8.GetBytes("Hello from dispacther");
await pipe.WriteAsync(buffer, 0, buffer.Length);
pipe.Dispose();
Application.Exit();
});
base.OnLoad(e);
}
}
public partial class ReceiverForm : Form
{
private NamedPipeClientStream m_pipe;
public ReceiverForm()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
startProcess();
base.OnLoad(e);
}
private void startProcess()
{
string processName = "DispatcherEventTester.exe";
var process = new Process();
process.StartInfo.FileName = processName;
process.Start();
m_pipe = new NamedPipeClientStream("DispatcherPipe");
startConnecting(new CancellationTokenSource().Token);
}
private Task startConnecting(CancellationToken token)
{
var buffer = new byte[8096];
return m_pipe.ConnectAsync(token)
.ContinueWith(async t =>
{
while(m_pipe.IsConnected)
{
if (t.IsCanceled)
{
m_pipe.Close();
break;
}
var ret = await m_pipe.ReadAsync(buffer, 0, buffer.Length);
this.Invoke(new Action(() =>
{
richTextBox1.AppendText(Encoding.UTF8.GetString(buffer)+Environment.NewLine);
}));
m_pipe.Close();
break;
}
},token);
}
private void button1_Click(object sender, EventArgs e)
{
startProcess();
}
}
the application works but weird things happen sometimes.
The application throws System.IO.IOException: All pipe instances are busy.
if pressing on button1 few times
what is this error and how do I clear the pipe instances?
there were also few times I received in ReadAsync method 0 values
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74982688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Calling AllocConsole & FreeConsole multiple times and keep In- & Output functionality of Console object in C# .NET OS: Windows 10 Enterprise 1703 64-bit
I cannot allocate and free a console more than once without loosing the Console.ReadKey() functionality in a windows form application.
This question is similiar to Exception when using console window in a form application but the answer is missing out on the Console.ReadKey() function.
The following code works for the first execution only. One receives a new console window and the user has to press any key. On the second execution the text is displayed as well but Console.ReadKey() throws a System.InvalidOperationException.
System.InvalidOperationException: 'Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read.'
Left out the DllImport declarations within the static Win32Wrapper class for brevity.
Win32Wrapper.AllocConsole();
// set standard out handle to console window
var ConOut = Win32Wrapper.CreateFile(
"CONOUT$",
GenericAccessRight.GENERIC_READ | GenericAccessRight.GENERIC_WRITE,
ShareMode.FILE_SHARE_WRITE,
IntPtr.Zero,
CreationDisposition.OPEN_EXISTING,
0,
IntPtr.Zero
);
Win32Wrapper.SetStdHandle(Win32Wrapper.STD_OUTPUT_HANDLE, ConOut);
// set stadard in handle to console window
var ConIn = Win32Wrapper.CreateFile(
"CONIN$",
GenericAccessRight.GENERIC_READ | GenericAccessRight.GENERIC_WRITE,
ShareMode.FILE_SHARE_READ,
IntPtr.Zero,
CreationDisposition.OPEN_EXISTING,
0,
IntPtr.Zero
);
Win32Wrapper.SetStdHandle(Win32Wrapper.STD_INPUT_HANDLE, ConIn);
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true });
Console.SetIn(new StreamReader(Console.OpenStandardInput()));
Console.WriteLine("Hello World!"); // works every time
Console.Read(); // works every time
Console.ReadKey(true); // second call: InvalidOperationException
Win32Wrapper.CloseHandle(ConIn)
Win32Wrapper.CloseHandle(ConOut)
return Win32Wrapper.FreeConsole();
A: I found a way to simulate the above behaviour by not destroying the console I created before but instead simply hiding and displaying it again.
if (FirstTime)
{
FirstTime = false;
Win32Wrapper.SetStdHandle(Win32Wrapper.STD_OUTPUT_HANDLE, HWND.Zero);
Win32Wrapper.SetStdHandle(Win32Wrapper.STD_INPUT_HANDLE, HWND.Zero);
Win32Wrapper.AllocConsole(); // show implicitly
}
else
{
Console.Clear(); // clear => simulate new console
Win32Wrapper.ShowWindow(Win32Wrapper.GetConsoleWindow(), 5); // show (again)
}
Console.WriteLine("Hello World!");
Console.Read();
Console.ReadKey(true);
Win32Wrapper.ShowWindow(Win32Wrapper.GetConsoleWindow(), 0); // hide
Only the first function call allocates a new console further calls only show the already existing console again. All I need is a static variable to take track of it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58450846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Windows Live Login API SSL issue - Python I'm writing a program to invite several Windows Live Contacts into a web application, all in Django 1.4. I'm experiencing the following problem.
I'm able to log the user in Windows Live using his account credentials through the Windows Live REST API by using this piece of code
def hotmail(request):
auth_params = {
'client_id': settings.HOTMAIL_KEY,
'scope': 'wl.basic',
'response_type': 'code',
'redirect_uri': 'http://my_testing_comain/hotmail/process'
}
auth_url = settings.HOTMAIL_AUTH_URL % urllib.urlencode(auth_params)
return HttpResponseRedirect(auth_url)
Then, I receive an Authorization Code that I exchange for an Access Token (according to the OAuth Protocol) this is the piece of code I use to process the Windows Live's response:
def hotmail_process(request):
if request.method == 'GET':
parameters = {
'code': request.GET['code'],
'grant_type': 'authorization_code',
'redirect_uri': 'http://my_testing_url/hotmail/process',
'client_id': settings.HOTMAIL_KEY,
'client_secret': settings.HOTMAIL_SECRET,
}
response = urllib2.urlopen(settings.HOTMAIL_AUTH_URL % urllib.urlencode(parameters)).read()
response = simplejson.loads(response)
consumer = oauth.Consumer(settings.HOTMAIL_KEY, settings.HOTMAIL_SECRET)
client = oauth.Client(consumer)
contacts = client.request(settings.HOTMAIL_USER_FRIENDS_URI % response['access_token'])
return HttpResponse(simplejson.loads(contacts))
return HttpResponse('Invalid request')
But I get the following error:
SSLHandshakeError at /hotmail/process/
[Errno 1] _ssl.c:499: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
Request Method: GET
Request URL: http://my_testing_url/hotmail/process/?code=5330307c-664c-4d5b-27b3-a19a97bc8546
Django Version: 1.4
Exception Type: SSLHandshakeError
Exception Value:
[Errno 1] _ssl.c:499: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
and the following traceback:
Environment:
Request Method: GET
Request URL: http://my_testing_url/hotmail/process/?code=5330307c-664c-4d5b-27b3-a19a97bc8546
Django Version: 1.4
Python Version: 2.7.1
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'contacts')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/home/user/virtenvs/israel/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/user/virtenvs/israel/networks/contacts/views.py" in hotmail_process
26. contacts = client.request(settings.HOTMAIL_USER_FRIENDS_URI % response['access_token'])
File "/home/user/virtenvs/israel/lib/python2.7/site-packages/oauth2/__init__.py" in request
682. connection_type=connection_type)
File "/home/user/virtenvs/israel/lib/python2.7/site-packages/httplib2/__init__.py" in request
1544. (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/home/user/virtenvs/israel/lib/python2.7/site-packages/httplib2/__init__.py" in _request
1294. (response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/home/user/virtenvs/israel/lib/python2.7/site-packages/httplib2/__init__.py" in _conn_request
1230. conn.connect()
File "/home/user/virtenvs/israel/lib/python2.7/site-packages/httplib2/__init__.py" in connect
1005. raise SSLHandshakeError(e)
Exception Type: SSLHandshakeError at /hotmail/process/
Exception Value: [Errno 1] _ssl.c:499: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
The thing is that, if I delete the line where I do the client.request() for this:
return HttpResponseRedirect(settings.HOTMAIL_USER_FRIENDS_URI % response['access_token'])
I get the contacts in json format in my browser
So, apparently, my python oauth2 lib is missing some certificates (or that's what I think), so I tried this Python - SSL Issue with Oauth2 with no results. I also tried some libraries before I found out that they were deprecated. I've also tried to do it with the plain REST API call but I got a "FORBIDEN" response.
My oauth2 library works fine because I was able to implement the same functionality with GMail.
Any help or hint will be truly appreciated.
Thank you in advance.
A: Why not just do this?
jcts = urlib2.urlopen(settings.HOTMAIL_USER_FRIENDS_URI % response['access_token'])
contacts = simplejson.loads(jcts)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10883992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I retrieve the ID number of this text view How do I retrieve the text of a specific textView? BEcause when I click an ID number it displays '1' in the textview of the next class in every text view I click. I used JSON array so it's kind of tricky for me. And yes I'm completely a beginner.
DisplayListView
package rjj.tutorial_jsonandlistview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class DisplayListView extends AppCompatActivity {
String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
SearchView sv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_listview_layout);
listView = (ListView)findViewById(R.id.listview);
contactAdapter = new ContactAdapter(this,R.layout.row_layout);
listView.setAdapter(contactAdapter);
json_string = getIntent().getExtras().getString("json_data");
//Searchview
sv = (SearchView)findViewById(R.id.search);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
contactAdapter.getFilter().filter(newText);
return true;
}
});
//End of Searchview
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String id ,firstname , surname, age , username, password;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
id = JO.getString("id");
firstname = JO.getString("firstname");
surname = JO.getString("surname");
age = JO.getString("age");
username = JO.getString("username");
password = JO.getString("password");
Contacts contact = new Contacts(id, firstname, surname, age,username,password);
contactAdapter.add(contact);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void hello(View view) {
Intent intent = new Intent(this, Update.class);
TextView textView = (TextView)findViewById(R.id.tx_id);
String id = textView.getText().toString();
intent.putExtra("id", id);
startActivity(intent);
}
}
My ContactAdapter Class:
package rjj.tutorial_jsonandlistview;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Julian on 7/20/2017.
*/
public class ContactAdapter extends ArrayAdapter {
List list = new ArrayList();
public ContactAdapter(@NonNull Context context, @LayoutRes int resource) {
super(context, resource);
}
public void add(Contacts object) {
super.add(object);
list.add(object);
}
@Override
public int getCount() {
return list.size();
}
@Nullable
@Override
public Object getItem(int position) {
return list.get(position);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View row;
row = convertView;
ContactHolder contactHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
contactHolder = new ContactHolder();
contactHolder.tx_id = (TextView)row.findViewById(R.id.tx_id);
contactHolder.tx_firstname = (TextView)row.findViewById(R.id.tx_firstname);
contactHolder.tx_surname = (TextView)row.findViewById(R.id.tx_surname);
contactHolder.tx_age = (TextView)row.findViewById(R.id.tx_age);
contactHolder.tx_username = (TextView)row.findViewById(R.id.tx_username);
contactHolder.tx_password = (TextView)row.findViewById(R.id.tx_password);
row.setTag(contactHolder);
} else{
contactHolder = (ContactHolder)row.getTag();
}
Contacts contacts = (Contacts)this.getItem(position);
contactHolder.tx_id.setText(contacts.getId());
contactHolder.tx_firstname.setText(contacts.getFirstname());
contactHolder.tx_surname.setText(contacts.getSurname());
contactHolder.tx_age.setText(contacts.getAge());
contactHolder.tx_username.setText(contacts.getUsername());
contactHolder.tx_password.setText(contacts.getPassword());
return row;
}
static class ContactHolder{
TextView tx_id, tx_firstname, tx_surname, tx_age, tx_username, tx_password;
}
}
My Update Class:
package rjj.tutorial_jsonandlistview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Update extends AppCompatActivity {
String id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
id = getIntent().getExtras().getString("id");
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText(id);
}
}
My display_listview_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="rjj.tutorial_jsonandlistview.DisplayListView">
<SearchView
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="@+id/search"
android:queryHint="Search..."/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/search"
android:id="@+id/listview">
</ListView>
</android.widget.RelativeLayout>
The row_layout.xml (which I use to display the JSON array)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="75dp">
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="@+id/tx_id"
android:layout_alignParentLeft="true"
android:text="ID"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
android:onClick="hello"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="@+id/tx_firstname"
android:layout_toRightOf="@+id/tx_id"
android:text="Firstname"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="@+id/tx_surname"
android:layout_toRightOf="@+id/tx_firstname"
android:text="Lastname"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="@+id/tx_age"
android:layout_toRightOf="@+id/tx_surname"
android:text="Age"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="@+id/tx_username"
android:layout_toRightOf="@+id/tx_age"
android:text="Username"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="@+id/tx_password"
android:layout_toRightOf="@+id/tx_username"
android:text="Password"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
</RelativeLayout>
A: In method hello(View view) you don't need this string:
TextView textView = (TextView)findViewById(R.id.tx_id);
becouse the view in hello(View view) this is our TextView. Just cast it to TextView and get text from it:
String id = ((TextView)view).getText().toString();
Another and most universal approach: to change
TextView textView = (TextView)findViewById(R.id.tx_id);
to
TextView textView = (TextView)((ViewGroup)(view.getParent())).findViewById(R.id.tx_id);
In this way you can use any R.id for current list item.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45232327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.