text:
Q: How to let a user draw a line using a canvas in WPF I am trying to make a simple image editor where users can load an image and draw arrows, text, and rectangles on it.
Right now I have a window with some buttons and a viewbox with a canvas and an image inside it.
Basically a user would click the arrow button, click somewhere on the canvas, move the mouse which would show a line, and then click somewhere else to actually draw the line.
How do I tell the canvas to start listening for a mouse click only after the draw button is clicked? Here is what I have so far.
<Window x:Class="ImageEditor.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="600" Width="800">
    <Window.CommandBindings>
        <CommandBinding Command="local:CapturePointsCommand" Executed="CommandBinding_Executed" CanExecute="CommandBinding_CanExecute"/>
    </Window.CommandBindings>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Button Grid.Row="0" Name="_drawArrow" Height="69" Width="69" Click="_drawArrow_Click" HorizontalAlignment="Left" Margin="5,5,0,5">
            <Image Source="Media/arrow.png"/>
        </Button>
        <Button Grid.Row="0" Name="_drawBox" Height="69" Width="69" Click="_drawBox_Click" HorizontalAlignment="Left" Margin="79,5,0,5">
            <Image Source="Media/rectangle.png"/>
        </Button>
        <Button Grid.Row="0" Name="_drawText" Height="69" Width="69" Click="_drawText_Click" HorizontalAlignment="Left" Margin="153,5,0,5">
            <Image Source="Media/text.png"/>
        </Button>
        <Viewbox Grid.Row="1">
            <Canvas Name="_canvas" Height="{Binding Height, ElementName=_picture}" Width="{Binding Width, ElementName=_picture}" MouseLeftButtonUp="_canvas_MouseLeftButtonUp">
                <Image  Name="_picture" Source="{Binding Image}" Height="488" Width="800"/>
            </Canvas>
        </Viewbox>
        <Button Grid.Row="2" HorizontalAlignment="Right" Name="_Load_Button" Content="Load" Margin="0,5,5,5" Width="75" Height="23" Click="_Load_Button_Click" />
        <Button Grid.Row="2" HorizontalAlignment="Right" Name="_Save_Button" Content="Save" Margin="0,5,85,5" Width="75" Height="23" Click="_Save_Button_Click" />
        <Button Grid.Row="2" HorizontalAlignment="Right" Name="_Cancel_Button" Content="Cancel" Margin="0,5,165,5" Width="75" Height="23" Click="_Cancel_Button_Click" />
        <Button Grid.Row="2" HorizontalAlignment="Right" Name="_Reset_Button" Content="Reset" Margin="0,5,245,5" Width="75" Height="23" Click="_Reset_Button_Click" />
    </Grid>
</Window>

With this as code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.IO;

namespace ImageEditor
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public static readonly RoutedCommand CapturePointsCommand = new RoutedCommand();

        private ImageSource _image;

        public MainWindow()
        {
            InitializeComponent();
        }

        public ImageSource Image
        {
            get
            {
                return this._image;
            }
            set
            {
                this._image = value;
            }
        }

        private List<Point> _points = new List<Point>();

        public List<Point> Points
        {
            get
            {
                return this._points;
            }
            set
            {
                this._points = value;
            }
        }

        private void _Save_Button_Click(object sender, RoutedEventArgs e)
        {
            if (Image == null)
                System.Windows.Forms.MessageBox.Show("There is nothing to save");
            else
            {
                Image = this._picture.Source;
                this.Close();
            }
        }

        private void _Reset_Button_Click(object sender, RoutedEventArgs e)
        {
            this._picture.Source = Image;
        }

        private void _Cancel_Button_Click(object sender, RoutedEventArgs e)
        {
            Image = null;
            this._picture.Source = null;
            this.Close();
        }

        private void _Load_Button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            string path;
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                path = ofd.FileName;
                Uri pathUri = new Uri(path);
                PngBitmapDecoder decoder = new PngBitmapDecoder(pathUri, BitmapCreateOptions.None, BitmapCacheOption.None);
                BitmapSource pathSrc = decoder.Frames[0];
                Image = pathSrc;
                this._picture.Source = Image;
            }
            else
            {
                path = null;
            }
        }

        private void _drawArrow_Click(object sender, RoutedEventArgs e)
        {
            Line line = new Line();
            line.Stroke = Brushes.Black;
            line.X1 = Points[0].X;
            line.Y1 = Points[0].Y;
            line.X2 = Points[1].X;
            line.Y2 = Points[1].Y;

            this._canvas.Children.Add(line);
        }

        private void _drawBox_Click(object sender, RoutedEventArgs e)
        {

        }

        private void _drawText_Click(object sender, RoutedEventArgs e)
        {

        }

        private void _canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Point p = Mouse.GetPosition(_canvas);
            Points.Add(p);
        }

        private void _drawArrow_MouseDown(object sender, MouseButtonEventArgs e)
        {

        }

        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }
    }
}

A: The code below provided the functionality for me which you can adapt to work for you.
The enumeration is a list of all the different shapes you want the user to be able to draw. The buttons you have implemented should set the activeShapeType value. Add your methods from drawing rectangles, circle, etc to the switch statement in the Canvas_MouseLeftButtonDown event.
The right click event will allow the user to cancel a line they are drawing before the second click.
    public bool IsFirstPoint = true;
    public Point StartPoint;
    public enum ShapeType
    {
        line,
        circle,
        rectangle
    }
    public ShapeType activeShapeType = ShapeType.line;

    private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (IsFirstPoint)
        {
            StartPoint = (Mouse.GetPosition(Surface));
            IsFirstPoint = false;
        }
        else
        {
            switch (activeShapeType)
            {
                case ShapeType.line:
                    Line line = new Line() { X1 = StartPoint.X, Y1 = StartPoint.Y, X2 = Mouse.GetPosition(Surface).X, Y2 = Mouse.GetPosition(Surface).Y, Stroke = Brushes.Black };
                    Surface.Children.Add(line);
                    break;
                case ShapeType.rectangle:
                   /*Your code to draw rectangle here*/
                   break;
            }
            IsFirstPoint = true;
        }
    }

    private void Surface_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        IsFirstPoint = true;
    }

This code should add the temporary line while moving the mouse.
private void Surface_MouseMove(object sender, MouseEventArgs e)
    {
        if (!IsFirstPoint)
        {

            if (Surface.Children.Count > 0)
            {
                var child = (from c in Surface.Children.OfType<FrameworkElement>()
                             where "tempLine".Equals(c.Tag)
                             select c).First();
                if (child != null)
                {
                    Surface.Children.Remove(child);
                }
            }

            switch (activeShapeType)
            {
                case ShapeType.line:
                    Line line = new Line() { Tag="tempLine", X1 = StartPoints.X, Y1 = StartPoints.Y, X2 = Mouse.GetPosition(Surface).X, Y2 = Mouse.GetPosition(Surface).Y, Stroke = Brushes.Black };
                    Surface.Children.Add(line);

                    return;
            }
        }
    }

A: I did something like this using InkCanvas, drawing, and adding symbols to the canvas.
However I control most of my things with bools, so you know which state you are in when you are clicking on a button.
Then when you click on the canvas, the state is used to say okay i'm in a square/arrow state, this is what im supposed to draw. However. What i think you are looking for is the
Down, move up functionality.
When you click the canvas mousedown, you get the position of where you want to start your figure, and when you move the mouse while pressed, you could do a dragging animation, or skip that and go straight to where you release on the canvas. Get the other position, and then from those positions draw the line..
x1,y1 (mousedown position on canvas) x2,y2 (mouseup on canvas) I don't really have time to provide an example now since i'm on my way home, but it should not be tooooooo difficult, just break it up in small steps from where you are before you click to where you wanna go when you have clicked.
Hope this is of any help.


text:
Q: A dependency autowired correctly in constructor gets null later on automatically for same Service object with KafkaListener @EnableKafka
@Configuration
public class KafkaConfiguration {
@Bean
public ConsumerFactory<String, String> consumerFactory() {
   //configurations
    return new DefaultKafkaConsumerFactory<>(config);
}

@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory();
    factory.setConsumerFactory(consumerFactory());
    return factory;
}
}

@Service
public class KafkaConsumer {
private Dep dependency;

@Autowired
public KafkaConsumer(Dep dep){
this.dependency = dep;
}

@KafkaListener(topics = "Kafka_Example", containerFactory = "kafkaListenerContainerFactory")
public void consume(String message) {
    System.out.println("Consumed message: " + message);//dependency null here
}

The dependency is properly autowired when constructor is called. But later on when consume method is called by spring kafka listener then dependency is null. Both times the object of Kafka consumer is the same. Dep is a @Service class with a basic print method.How is this possible?

But when I add another containerfactory provider method it works and the dependency is not null.
@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> customKafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory();
    factory.setConsumerFactory(consumerFactory());
    return factory;
}

using this as containerFactory works.
What changed?

redpajama_set_name: RedPajamaStackExchange


text: Q: Google Analytics Streamview with firebase integration I am looking to integrate google analytics into our back end and connecting the data to make it easier for our team to see everything. I wanted to know if I was able to embed the StreamView map into the website or if there is any other service like this i can add into our backend to see a live user map. Thanks!


text:
Q: O método MediaPlayer.create() é chamado no background? Estava lendo a documentação do Android Media Playback e me ocorreu uma dúvida. Na documentação falava que não é aconselhável chamar o método mediaPlayer.prepare() na thread responsável pela UI, e gostaria de saber se o método MediaPlayer.create(this, R.raw.amostra_de_audio) é chamado no background ou é necessário alguma configuração adicional. Desde já agradeço.

A: O método MediaPlayer.create() não é assíncrono. Não poderia ser porque ele retorna uma instância de MediaPlayer.
Ele internamente chama o método prepare() retornando assim o MediaPlayer pronto a ser usado.
Para se conseguir o mesmo de forma assíncrona terá de se criar uma instância, através de new e chamar o método prepareAsync().
MediaPlayer myMediaPlayer = new MediaPlayer();
....
....
myMediaPlayer.setDataSource(url);
myMediaPlayer.prepareAsync();

myMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

    @Override
    public void onPrepared(MediaPlayer player) {
        player.start();
    }

});

O método onPrepared() do OnPreparedListener passado ao método setOnPreparedListener() será chamado quando o MediaPlayer estiver pronto para ser usado.


text:
Q: Exporting empty fields as NULL I am using QGIS 3.4 and I work with a shapefile and its Attribute Table with a few rows where some fields are just blank (no zero value or NULL).
When I export the shapefile file to ArcGIS Pro all the blank fields become zero but they should be NULL. How can I handle this problem?

A: I had the same problem but I just found how to solve it.
Here is the solution

*

*Open attributes table

*Using 'select by expression' function, select rows containing null values of a column

*Enable 'edit' mode

*You will now find editing engine in the tool bar

*Select the column that contains null values that you want to preserve

*write null in the editing engine

*Go to the right end of the editing engine and click the button called 'update the selected'

*Now the null values become 'actual null(empty) value' rather than string value with characters(alphabets) 'NULL'

So, the null values you have are not actually empty value but character values of 'NULL'. -->  AGAIN they are not empty so they changed to 0 when you refactor and export it


text:
Q: Source Resistance I have a module that generate an AC signal for a measurement it makes. Frequency and Amplitude output provides information and we use that. Now I am designing a better amplifier for the module and I am trying to figure out what is the source resistance of this module. (The resistance seen from the amplifier).
Unfortunately, datasheet offers no clues. How can I measure source resistance of this unknown entity in a reliable way?

A: You could use a voltage divider made by the source resistance and an additional potentiometer placed by you , measure the output voltage and adjust the potentiometer until the output voltage from voltage divider is half from the original output voltage.


text:
Q: I am getting the following problem at the time of ravendb installation At the time of ravendb installation when I am trying to run run.ps1 in windows powershell I am getting the following error. If any one knows the solution please help me.
PS D:\RavenDB> .\run.ps1
File D:\RavenDB\run.ps1 cannot be loaded because the execution of scripts is disabled on this system.
Please see "get-help about_signing" for more details.
At line:1 char:10
+ .\run.ps1 <<<<
    + CategoryInfo          : NotSpecified: (:) [], PSSecurityException
    + FullyQualifiedErrorId : RuntimeException

A: This has to do with the ExecutionPolicy in PowerShell on your computer. The simplest fix is to run Set-ExecutionPolicy Unrestricted from an elevated PowerShell prompt and then execute run.ps1


text:
Q: SQL data type for multiple decimal places What data type in SQL Server will insert the correct number of decimal places for the number entered into a table. When I try to enter a number like so 6.828.678 into a deciaml or numeric field it says input value was not in the correct format. What data type do i use so that it allows this?

A: If you are trying to store the data in format 6.828.678 (as in your post) then consider using VARCHAR data type.
You can't store 6.828.678 format data into either deciaml or numeric type field cause they are not valid number format and that's why you are getting the error.
Not sure, but per your comment if you want to SUM and compare the value then store it as INT datatype but before inserting the data make sure to remove the ..
You can use REPLACE() function like CAST(REPLACE('6.828.678','.','') as INT). Hope this helps.


text:
Q: How to generate build for android mobile? I have installed PhoneGap in my mac and I am able to select PhoneGap project template using Xcode. Now I my doubt is, how can I deploy the application on Android device?
Do I need to set up Eclipse and need to install PhoneGap Sdk again?
Can't I develop it on one platform and get the build for other mobile devices?

A: Yes you need to configure cordova on seperate platforms if you download the libraries.
Although you can use https://build.phonegap.com/
To just write code once and you will get the respective installable files for the mobile platforms.

A: I agree with above answer. But if you keep developing apps using Phongap you better you Install ecplipse and sdk. Then add following plugin
http://www.mobiledevelopersolutions.com/
It will generate you entire set up  for application. You need to replace www folder.
Make your you also replace correct cordova js file. Because it needs to be the one created for Android.


text:
Q: Vagrant SSH failed with ubuntu/xenial64 I have done vagrant init ubuntu/xenial64; vagrant up --provider virtualbox, then when I was trying to vagrant ssh I got message with folowing.

no kex alg

A: most likely your ssh client is getting too old, can you run ssh -V to find out the version and upgrade if needed.


text:
Q: C# MVC Access Action Param from controller Initialization If I have a controller with HTTP POST action with once or several parameters like this:
//[HttpPost]
public ActionResult Ajaxbuscarope(string texto="")
{

}

How could I access to "texto" parameter directly from the controller Initialization...
protected override void Initialize(System.Web.Routing.RequestContext
requestContext)
{

    var texto=???
}

I can access the Get parameters using this...
var url_with_params=System.Web.HttpContext.Current.Request.Url.AbsoluteUri;

But this is not working with post request with declared parameters
System.Collections.Specialized.NameValueCollection post = System.Web.HttpContext.Current.Request.Form;

A: HttpRequest request = HttpContext.Current.Request;
request.InputStream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(request.InputStream);

var requestFromPost = Encoding.Default.GetString(HttpContext.Current.Request.BinaryRead(HttpContext.Current.Request.TotalBytes));
//this is very important to have the parameters available in the action
request.InputStream.Seek(0, SeekOrigin.Begin);


text:
Q: Why would you hire a mercenary? In a mercenary encounter, why would it be strategic to hire the mercenary?

*

*If you fight the mercenary, you've spent 1 fuel, explored 1 beacon, and gained default rewards through battle. This is what I consider a good beacon.

*If you hire them to delay the rebels and use those 2 extra jumps, you've spent 3 fuel, 10-25 scrap, and explored 3 beacons, one of them (the mercenary one) being effectively empty.

*If you hire them to scout the sector, you've spent 1 fuel, 10-20 scrap, and gained the sector map.

I currently always fight the mercenary (they are worse than rebels and I must be honorable). Delaying the rebels does not seem better on average and the only situation I would consider it is if I am able to complete a quest or avoid Rebel elites. Scouting the sector seems situational, such as if you are very damaged and looking for a store.
Why would you let those filthy mercenaries live?

A: In the few times I've hired a mercenary for extra jumps it was when

*

*I'm scrap heavy and fuel heavy and I've been hunting for a shop (shields maxed and I need to get better guns) so I want to explore every beacon. I find extra jumps are more useful than the map as you only need to be 1 system away to discover a shop.

Or

*

*Trying to increase quest related odds, like getting to and back from a quest beacon in a weird system map or finding a ship like the incomplete rebel cruiser, finding the right slug, mantis, rock, etc. ship.

Or

*

*I have the system mapped already and getting the extra jump enables me to hit an extra distress beacon or two and I have the abilities that maximizes profits from these or I'm desperate for an extra crew member.

And finally if you have one or more scrap arms the chance to turn 1 default rewards with bonuses into 2 default rewards with bonuses is quite enticing.
Most of the time though I agree with you, blast those mercenary scum into scrap!

A: I have always fought them but I have started to rethink this.  Besides the fairly obvious situational things usually get mentioned (completing quests, desperate for a shop, no rebel free path to the exit, etc) I actually think it is sometimes economical to delay.
As mentioned in the question, there are two sides
side 1: default battle rewards
side 2: -scrap, -2 fuel, two encounters
Now if we assume every encounter is a default battle, and we feel we can win default battles without injury, AND fuel isn't really an issue, then I think this is actually a good deal.  Beyond sector 1, the cost to hire the mercenary is almost always lower then the reward for a default battle, especially if you are killing crew.  In other words, 1 default reward is worse than 2 default rewards minus the fee.  When you factor in the possibility to get much better than default rewards this is even more attractive.
I want reiterate though, that this only applies if fuel is not an issue and you are feeling strong for the area.


text:
Q: Changing Home Directory for cygwin I know that this question has been asked before on this site, but I am very new with Cygwin and am really confused by a lot of the other answers.
What is the best method to change my home directory in Cygwin?

A: Perhaps the most easier way is to make a folder junction with mklink.exe windows command. Assuming that you would like to use windows home directory:

*

*Press Win + R and type cmd.

*rename your cygwin home e.g.: c:\cygwin\home\username --> username_backup

*type mklink /j c:\cygwin\home\username c:\Users\username

*if you would like to use the contents of your old home directory you should copy them to the new one


text:
Q: GDB debugger doesn't work in Code::blocks Information:
OS: Ubuntu 14.04
IDE: Code::blocks 13.12
Debugger: gdb 7.10
I'm new to code::blocks and was trying out the debugger, but it didn't work. So I'm here to ask you what I could do to find a solution to this problem.
When I click on 'step into' and the XTerm console opens with the message:

warning: GDB: Failed to set controlling teminal: Operation not permitted

And the output is not to be seen anywhere.

A:
I found out there was no real problem, I only had to end the line that I was trying to see with a 'endl'

What I was trying to execute in the debugging session, but couldn't see:
 cout << "Hello World!";

What solved the problem, enabling me to see the output in the debugger:
 cout << "Hello World!" << endl;

A: Indeed, you need to flush your buffered streams (ie. fflush for FILE*, and .flush for std::stream-s).
But you don't need any IDE to run gdb. You could run it in a plain terminal, try gdb or gdb -tui or gdb --args or in Emacs


text:
Q: Using grepl to extract a value from text across multiple columns I have a dataframe (df) containing 2 columns of data for state and city. Sometimes, however, the data inside the 2 columns are transposed or incorrectly entered. The dataframe will look something like this:
location          state
Bangkok
                  Bangkok Metropolitan
Central Thai      Bangkok

I want to create a new column, "City" by extracting 'Bangkok' from these two into a separate column. I can do this for one column by something like:
df$city <- ifelse(grepl("Bangkok",df$location),"Bangkok","")

However, I want to search at least 2 or more columns at once, something like:
df$city <- ifelse(grepl("Bangkok",df$location||df$state),"Bangkok","")

which, obviously, doesn't work. 'filter' in plyr I think does something similar but in reverse.
Any help appreciated. Thanks!

A: You could also just paste the columns together
df$city <- ifelse(grepl("Bangkok", paste(df$location,df$state)),"Bangkok","")

A: You can use grepl more than once. Besides, you should use | rather than ||.
df1 <- data.frame(location=c("Bangkok", "",  "Central Thai", "someth"),
                  state=c("", "Bangkok Metropolitan", "Bangkok", "youguess"),
                  stringsAsFactors = FALSE)

df1$city <- ifelse(grepl("Bangkok", df1$location) | grepl("Bangkok", df1$state),
                   "Bangkok","")
df1
#       location                state    city
# 1      Bangkok                      Bangkok
# 2              Bangkok Metropolitan Bangkok
# 3 Central Thai              Bangkok Bangkok
# 4       someth             youguess

See also ?"|"
For |, & and xor a logical or raw vector.
For ||, && and isTRUE, a length-one logical vector.


text:
Q: execute code on start of app engine endpoints Is there a way to start a piece of code on-start of GAE using Endpoints java?
I know by using servlets we can do that, but using endpoints is it possible? If yes, then how should I proceed. Can't find anything around this. I am new to GAE.
Basically, I want to run an init method as soon as the server starts.
I am using Android Studio for developing this server so it's NOT the latest V2 endpoints.

A: You can do this using warmup requests and a ServletContextListener.


text:
Q: How can I make my .muttrc portable to older machines despite "unknown variable" On an older machine, which I am not an administrator of, I can't use my
global .muttrc, without getting
Error in /home/jidanni1/.muttrc, line 18: sidebar_visible: unknown variable
source: errors in /home/jidanni1/.muttrc

Is there some way for me to still be able to use the same .muttrc on both
new and old machines, without getting this error?


text:
Q: Почему Android Studio не принимает картинки? Подскажите, почему android studio не загружает картинки в папку drawable никакого формата?
Появляется ошибка:
Refactoring cannot be performed
File C:\Users....\cat.png is read-only

A: В нижней части студии стоит блокировка на изменения файлов в проекте.

Нужно нажать на иконку замочка.
UPD
ответ из комментария:
Файл должен находится в директории текущего пользователя.

A: Проблема в том, что файл доступен только для чтения, а, при перетаскивании в студию, Вы его перемещаете. Скопируйте его комбинацией Ctrl + C, Ctrl + V и будет Вам счастье.

A: У меня была такая же проблема, решил с помощью изменения структуры с Android на Project


text:
Q: Validate a username on Linux using PAM I know there has been many questions regarding authentication schemes using PAM on Linux and I also have a working copy for a username/password auth.
I want to know if we can validate "just" the username alone...given that I don't even create a password when I create that particular user in Linux. If Yes, let me know how to go about it. A few code snippets would be really great. Thanks!
P.S. Right now I authenticate by passing values through strings (each for username and password)

A:  This is what I figured, an easy method, and it might be different than anybody else's logic.
- Take that "username" only and try to create a user using Linux's own system call.
- If the user creation succeeds --> the user never existed (it solves my problem of creating a user without a password).
- If the user creation fails --> the user already exists and it doesn't create.
The system will return this and you must grab the return value to move on to the next step of your program).
Let me know if this can be made more refined.

A: You can use pam_securetty that check if user id is 0, if the user doesnt exist -this check fails and therefore its validate the username. Add to /etc/pam.d/login
auth require pam_securetty.so


text:
Q: make error about CRT2.o I use MinGW+msys.
I'm trying to install OpenCASCADE as following instruction.
https://sites.google.com/site/philippeguerville/home/build-opencascade-for-windows-with-mingw
I've already installed libpng freeglut FreeImage freetype.
gl2ps and oce have been left.
Now I'm facing problem when I make gl2ps, errors occur as below.
[ 50%] Linking C executable gl2psTest.exe
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../crt2.o:(.text+0x1bc): undefined r
eference to `__cpu_features_init'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../crt2.o:(.text+0x1cb): undefined r
eference to `_CRT_fmode'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../crt2.o:(.text+0x1ee): undefined r
eference to `_CRT_fmode'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../crt2.o:(.text+0x202): undefined r
eference to `_CRT_fmode'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../crt2.o:(.text+0x26c): undefined r
eference to `_CRT_glob'
collect2.exe: error: ld returned 1 exit status
make[2]: *** [gl2psTest.exe] Error 1
make[1]: *** [CMakeFiles/gl2psTest.dir/all] Error 2
make: *** [all] Error 2

Where ware those _cpu_features_init _CRT_fmode _CRT_glob defined?
Is there any header files to define _cpu_features_init _CRT_fmode _CRT_glob?
I make g1lps with following command.
cmake -G "MSYS Makefiles" -DCMAKE_INSTALL_PREFIX=/usr/local -DZLIB_INCLUDE_DI
R=/C/Qt/Qt5.5.0/Tools/mingw492_32/i686-w64-mingw32/include -DZLIB_LIBRARY=/C/Qt
/Qt5.5.0/Tools/mingw492_32/i686-w64-mingw32/lib/libz.a -DGLUT_INCLUDE_DIR=/usr/
local/include -DGLUT_glut_LIBRARY=/usr/local/lib/libglut.dll.a -DPNG_PNG_INCLUD
E_DIR=/usr/include -DPNG_LIBRARY=/usr/local/lib/libpng.a

Makefile was generated as below which focused on gl2psTest.
#=============================================================================
# Target rules for targets named gl2psTest

# Build rule for target.
gl2psTest: cmake_check_build_system
    $(MAKE) -f CMakeFiles/Makefile2 gl2psTest
.PHONY : gl2psTest

# fast build rule for target.
gl2psTest/fast:
    $(MAKE) -f CMakeFiles/gl2psTest.dir/build.make CMakeFiles/gl2psTest.dir/build
.PHONY : gl2psTest/fast

# target to build an object file
gl2psTest.obj:
    $(MAKE) -f CMakeFiles/gl2psTest.dir/build.make CMakeFiles/gl2psTest.dir/gl2psTest.obj
.PHONY : gl2psTest.obj

# target to preprocess a source file
gl2psTest.i:
    $(MAKE) -f CMakeFiles/gl2psTest.dir/build.make CMakeFiles/gl2psTest.dir/gl2psTest.i
.PHONY : gl2psTest.i

# target to generate assembly for a file
gl2psTest.s:
    $(MAKE) -f CMakeFiles/gl2psTest.dir/build.make CMakeFiles/gl2psTest.dir/gl2psTest.s
.PHONY : gl2psTest.s

And also CMakeFiles/gl2psTest.dir/build.make is below.
# CMAKE generated file: DO NOT EDIT!
# Generated by "MSYS Makefiles" Generator, CMake Version 3.3

# Delete rule output on recipe failure.
.DELETE_ON_ERROR:

#=============================================================================
# Special targets provided by cmake.

# Disable implicit rules so canonical targets will work.
.SUFFIXES:

# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =

.SUFFIXES: .hpux_make_needs_suffix_list

# Suppress display of executed commands.
$(VERBOSE).SILENT:

# A target that is always out of date.
cmake_force:

.PHONY : cmake_force

#=============================================================================
# Set environment variables for the build.

# The shell in which to execute make rules.
SHELL = /bin/sh

# The CMake executable.
CMAKE_COMMAND = /c/MinGW/msys/1.0/local/bin/cmake.exe

# The command to remove a file.
RM = /c/MinGW/msys/1.0/local/bin/cmake.exe -E remove -f

# Escaping for special characters.
EQUALS = =

# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /C/src/products/oss/gl2ps-1.3.8-source

# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /C/src/products/oss/gl2ps-1.3.8-source

# Include any dependencies generated for this target.
include CMakeFiles/gl2psTest.dir/depend.make

# Include the progress variables for this target.
include CMakeFiles/gl2psTest.dir/progress.make

# Include the compile flags for this target's objects.
include CMakeFiles/gl2psTest.dir/flags.make

CMakeFiles/gl2psTest.dir/gl2psTest.obj: CMakeFiles/gl2psTest.dir/flags.make
CMakeFiles/gl2psTest.dir/gl2psTest.obj: CMakeFiles/gl2psTest.dir/includes_C.rsp
CMakeFiles/gl2psTest.dir/gl2psTest.obj: gl2psTest.c
    @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=/C/src/products/oss/gl2ps-1.3.8-source/CMakeFiles --progress-num=$(CMAKE_PROGRESS_1) "Building C object CMakeFiles/gl2psTest.dir/gl2psTest.obj"
    /c/MinGW/bin/gcc.exe  $(C_DEFINES) $(C_FLAGS) -o CMakeFiles/gl2psTest.dir/gl2psTest.obj   -c /C/src/products/oss/gl2ps-1.3.8-source/gl2psTest.c

CMakeFiles/gl2psTest.dir/gl2psTest.i: cmake_force
    @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Preprocessing C source to CMakeFiles/gl2psTest.dir/gl2psTest.i"
    /c/MinGW/bin/gcc.exe  $(C_DEFINES) $(C_FLAGS) -E /C/src/products/oss/gl2ps-1.3.8-source/gl2psTest.c > CMakeFiles/gl2psTest.dir/gl2psTest.i

CMakeFiles/gl2psTest.dir/gl2psTest.s: cmake_force
    @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Compiling C source to assembly CMakeFiles/gl2psTest.dir/gl2psTest.s"
    /c/MinGW/bin/gcc.exe  $(C_DEFINES) $(C_FLAGS) -S /C/src/products/oss/gl2ps-1.3.8-source/gl2psTest.c -o CMakeFiles/gl2psTest.dir/gl2psTest.s

CMakeFiles/gl2psTest.dir/gl2psTest.obj.requires:

.PHONY : CMakeFiles/gl2psTest.dir/gl2psTest.obj.requires

CMakeFiles/gl2psTest.dir/gl2psTest.obj.provides: CMakeFiles/gl2psTest.dir/gl2psTest.obj.requires
    $(MAKE) -f CMakeFiles/gl2psTest.dir/build.make CMakeFiles/gl2psTest.dir/gl2psTest.obj.provides.build
.PHONY : CMakeFiles/gl2psTest.dir/gl2psTest.obj.provides

CMakeFiles/gl2psTest.dir/gl2psTest.obj.provides.build: CMakeFiles/gl2psTest.dir/gl2psTest.obj

# Object files for target gl2psTest
gl2psTest_OBJECTS = \
"CMakeFiles/gl2psTest.dir/gl2psTest.obj"

# External object files for target gl2psTest
gl2psTest_EXTERNAL_OBJECTS =

gl2psTest.exe: CMakeFiles/gl2psTest.dir/gl2psTest.obj
gl2psTest.exe: CMakeFiles/gl2psTest.dir/build.make
gl2psTest.exe: libgl2ps.a
gl2psTest.exe: C:/MinGW/msys/1.0/local/lib/libglut.dll.a
gl2psTest.exe: c:/Qt/Qt5.5.0/Tools/mingw492_32/i686-w64-mingw32/lib/libz.a
gl2psTest.exe: C:/MinGW/msys/1.0/local/lib/libpng.a
gl2psTest.exe: c:/Qt/Qt5.5.0/Tools/mingw492_32/i686-w64-mingw32/lib/libz.a
gl2psTest.exe: C:/MinGW/msys/1.0/local/lib/libpng.a
gl2psTest.exe: CMakeFiles/gl2psTest.dir/linklibs.rsp
gl2psTest.exe: CMakeFiles/gl2psTest.dir/objects1.rsp
    @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --bold --progress-dir=/C/src/products/oss/gl2ps-1.3.8-source/CMakeFiles --progress-num=$(CMAKE_PROGRESS_2) "Linking C executable gl2psTest.exe"
    /c/MinGW/msys/1.0/local/bin/cmake.exe -E remove -f CMakeFiles/gl2psTest.dir/objects.a
    /c/MinGW/bin/ar.exe cr CMakeFiles/gl2psTest.dir/objects.a @CMakeFiles/gl2psTest.dir/objects1.rsp
    /c/MinGW/bin/gcc.exe  -O2 -g -DNDEBUG  -mwindows -Wl,--whole-archive CMakeFiles/gl2psTest.dir/objects.a -Wl,--no-whole-archive  -o gl2psTest.exe -Wl,--out-implib,libgl2psTest.dll.a -Wl,--major-image-version,0,--minor-image-version,0 @CMakeFiles/gl2psTest.dir/linklibs.rsp

# Rule to build all files generated by this target.
CMakeFiles/gl2psTest.dir/build: gl2psTest.exe

.PHONY : CMakeFiles/gl2psTest.dir/build

CMakeFiles/gl2psTest.dir/requires: CMakeFiles/gl2psTest.dir/gl2psTest.obj.requires

.PHONY : CMakeFiles/gl2psTest.dir/requires

CMakeFiles/gl2psTest.dir/clean:
    $(CMAKE_COMMAND) -P CMakeFiles/gl2psTest.dir/cmake_clean.cmake
.PHONY : CMakeFiles/gl2psTest.dir/clean

CMakeFiles/gl2psTest.dir/depend:
    $(CMAKE_COMMAND) -E cmake_depends "MSYS Makefiles" /C/src/products/oss/gl2ps-1.3.8-source /C/src/products/oss/gl2ps-1.3.8-source /C/src/products/oss/gl2ps-1.3.8-source /C/src/products/oss/gl2ps-1.3.8-source /C/src/products/oss/gl2ps-1.3.8-source/CMakeFiles/gl2psTest.dir/DependInfo.cmake --color=$(COLOR)
.PHONY : CMakeFiles/gl2psTest.dir/depend


text:
Q: Why does this simple counting loop in assembly start behaving eratically when I add a random floating point instruction? I am working on a bare metal OS for the Raspberry Pi model B, which features an ARM1176-JZF-S processor. While working on implementing the sine function for a math library, I encountered something very strange, which I've whittled down to a small-ish minimum reproducible example.
The following code counts up from zero to four, and prints out each number with spaces in between:
    mov     r4, #0              // Initialize counter to 0

c_loop$:
    ldr     r0, =IntString      // Convert counter to a string
    mov     r1, r4
    bl      int_to_str

    ldr     r0, =IntString      // Print the string
    ldr     r1, =0x00000FF0     // (Green text on black background)
    bl      print

    ldr     r0, =Space          // Print a space
    ldr     r1, =0x00000FF0     // (Green text on black background)
    bl      print

    mov     r5, #0x1000000      // Pause for a beat
c_pause$:
    subs    r5, #1
    bne     c_pause$

    add     r4, #1              // Increment counter
    cmp     r4, #5              // Repeat until counter = 5
    blt     c_loop$

halt:                           // Wait forever
    b       halt

The functions int_to_str and print were both written by me, and work fine. To be clear, they are not printing to any kind of output stream; they just write pixels in the shape of numbers directly to a frame buffer, which I got from the GPU through the mailbox system. The label IntString is a space for me to store the conversion of the counter to a string so I can print it out, and the label Space points to a string that's just a single space. This code works as intended and I see the numbers displayed on the screen.
Here's what's odd. Have a look at this floating-point operation:
    vadd.f32    s2, s0, s1      // What the heck is happening here?

When I add this into the loop right before the line where I increment the counter, I get different behavior entirely. Rather than printing "0, 1, 2, 3, 4", I now I see "0, 1, 0, 1, 0, 1, ..." repeating forever. Why is this happening? Why does the floating point instruction have any effect on this code at all?
Important additional info: A while ago, I was working on some code to draw a Mandelbrot fractal to the screen, using floating point arithmetic to do the calculations. Back then I believed that my Raspberry Pi had a Cortex A7 processor (which is what the newer models have) and I turned to the Cortex A7 Floating-Point Unit Technical Reference Manual which says that:

To use the Cortex-A7 FPU in Secure state and Non-secure state, first define the NSACR and then define the CPACR and FPEXC registers to enable the Cortex-A7 FPU.

It gave the following code snippet to accomplish this task:
    MRC     p15, 0, r0, c1, c1, 2
    ORR     r0, r0, #3<<10  // enable fpu
    MCR     p15, 0, r0, c1, c1, 2

    LDR     r0, =(0xF << 20)
    MCR     p15, 0, r0, c1, c0, 2

    MOV     r3, #0x40000000
    VMSR    FPEXC, r3

For some reason, this worked, and my Mandelbrot fractal appeared. Anyway, this snippet is present the program I'm working on today, directly above the code shown. When I remove it, I get different unexpected behavior. The program prints "0, 0, 0, ..." -- an infinite series of just 0's instead of 0's and 1's.
More details: My best guess about what's going on here is that the s0 and s1 floating point registers initially contain garbage, and that adding them together can raise an exception. This would explain a detail I haven't mentioned yet, which is that the code occasionally works even with the floating point instruction included -- maybe one time in five.
In order to test this theory, I tried setting all registers involved to zero right before the counting loop begins:
    mov     r0, #0
    vmov    s0, r0
    vmov    s1, r0
    vmov    s2, r0

And lo and behold, the loop worked again. However, as a further test, I decided to set both s0 and s1 to the maximum value a float can hold, reasoning that this should yield an overflow error and cause the unexpected behavior to return:
    ldr     r0, =0b01111111011111111111111111111111
    vmov    s0, r0
    vmov    s1, r0
    vmov    s2, r0

But this too leads to the correct counting behavior!
I'm at a loss for what's going on here. What's causing this?
Update: I've just noticed an issue. The code I'm using to assemble .s files into .o files is this:
    arm-none-eabi-as -o $@ $< -mfpu=vfpv4 -mcpu=cortex-a72 -mfloat-abi=hard

But this has two issues. One, the vfpv4 is incorrect as the model B features VFPv2, and two, cortex-a72 is incorrect as the model B features an ARM1176-JZF-S.
Fixing the first of these two issues doesn't change any of the behavior mentioned above (I re-tried each example and got the same results). The second issue seems more serious, however, since the man page for arm-none-eabi-as doesn't list the model B's processor type as one of the options. I will investigate further and post an update once I know more.

A: I have fixed this now. This web page explains what needs to be done to set up floating point numbers, and I was missing this part of the process:
    @; load the status register
    fmrx    r0, fpscr
    @; enable flush-to-zero (bit 24)
    orr     r0, #0x01000000
    @; disable traps (bits 8-12 and bit 15)
    bic     r0, #0x9f00
    @; save the status register
    fmxr    fpscr, r0

The page explains:

The default floating point mode on the ARM11 is to implement the most common floating point operations in hardware, and delgate to software for special cases. This is done by raising an unsupported operation exception, called a trap, in which you the programmer are supposed to figure out what went wrong (e.g., an underflow), calculate the correct result, and resume the program.
If, like me, you don't feel like implementing a bunch of floating point operations, there is an alternative: RunFast mode, or Flush-to-zero mode (which nearly means the same thing). This is a pure hardware floating point implementation which is not-quite IEEE 754-compliant. [...]

I haven't implemented any such handlers, so it looks like this configuration is what I need. I don't have a full mental picture of why this was causing the exact problem I was having, but I'm no longer surprised that there was a problem.


text:
Q: How do you structure your entities you intend to reuse? Lets say you have the following entities in your database:
Image http://lh6.ggpht.com/_UpGtM3B8h1U/Sa7SqfWmgDI/AAAAAAAAAHE/epqtm7EnoFg/test.gif
You want to be able to add a note to all three of the other entity tables (User, Client and Project).  How would you set this up?

*

*Add a tableName and a FKId to the Note table?

*Create a separate table for each associated Note group (ie., ClientNote, UserNote)

*Create a separate field in Note for each Foreign key (UserId, ClientId, etc)

I seem to be going back and forth between option 2 and 3, although I'd be up for 1 if there were an elegant implementation.  Option 2 is attractive because there are no nulls.  Option 3 is attractive because a note feels like a note no matter what it is associated with.
Any thoughts?

A: I would typically go with option 2. I don't stress about the number of tables in a database within reason.
The big question is, are these notes going to be handled as a single item? For example, are you going to ever say, "Show me all notes, regardless of whether it's for a client or user or project." I can't think of any situations where that would be useful. You're going to typically say, "Show me THIS CLIENT'S notes" or "Show me THIS PROJECT'S notes."
Since they are not logically one item I suggest not trying to model them physically as one item.

A: The way i've usually seen this handled is in option 1.  The up-side is that this is a fairly easy way for the humans involved to see what is happening.  As you said, the downside is that the SQL becomes a bit less elegant.
That's just kinda how it goes, though.  In reality, even though it may feel a bit clunky, the resulting queries are clear and readable.  You will only have to add sql to new code, as you go, in the areas where you've added new tables.
When you're actually manipulating notes directly, you only have to handle one table.

A: There is a fourth method (which I would recommend): add a unique id to the Note table, and a field noteId to User, Client and Project

A: What do do may depend on whether the notes fields you need are truly the same between entities. If they are the same then, I would probably have a Notes table (then if the needs change all notes get a revision date field, for example, added in one step) with a Notetype (user, client, project), noteID, and id from the appropriate table as well as all the notes related fields you need. The biggest problem with this is the FK relationships will have to be managed through a trigger instead of an FK. You don't want to put in an invalid userid, but since the whole column doesn't contain userids you can't just set up an FK relationship. On the other hand if you add another entity later, you can do without affecting your table structure (although you would still have to modify the trigger) which is the problem with having the ids in separate fields. This also means you will not be able to use cascade update or delete which can make deleting records (or changing a natural key (shudder)) more difficult.
If the needs for what fields you have for the notes are different between entities, I would create separate Notes Tables for each entitity.
If you are going to hit the Notes table in every query between all the enitites, you may want separate Tables for each entity as well to reduce locking and blocking issues. Notes however, may not need to be hit as often so it might not be too bad a situation.

A: Option 3.  Have an identity as primary key, and have a foreign key column for any tables that share the Note table.  I handle Email, Phone, Address etc. this way.
The only drawback I know if is if you have 10 tables linked to Note - you'd have 10 foreign key columns.
The problem I have with Option 1 is that it feels like you are creating an artificial foreign key (with TableName/Pkid, which isn't actually part of the User/Project primary keys, which are only Pkid).  That may just be my personal bias, I just never felt like that was good design, but I couldn't exactly say why.

A: I think, you should definitively avoid solution 1 in this case.
You loose the integrety reference, it becomes impossible to query your database without dynamic SQL and you always need 2 queries to select some notes!
You should never use this way in simples cases like here.
As I see it, I go with option 4 (adding a field note_id on project, client and user). If you need multiple notes for one row, it's not a problem. You simply add an extra table (lets say note_set) that makes the n-1 relation.
client(client_id, note_set_id)
user(user_id, note_set_id)
project(project_id, note_set_id)
note_set(note_set_id)
note(note_id, note_set_id, title, body)
the major problem of this solution, is that given a note you cannot find the initial "entity" without making an UNION on the three tables. It doesn't seems a big problem to me but, if it is, then go with option 3.
Finally, option 2 is good as well but it's not what I call "reuse".
Please excuse my english.


text:
Q: Short story - AI wakes up, takes over when mathematician discovers how to factor products of large primes Dystopian short story - an agent on Earth, reads that a mathematician has a method to factor products of two huge primes, so he tries to contact him and suppress knowledge, but it's too late. The AI wakes up, takes over the world, and agent goes back to his parallel universe, which is ruled by sympathetic AI.

A: That sounds like "Antibodies" by Charles Stross. It's in his collection Toast (you can download it from Charles' webpage, here and read the story here)

 Protagonist finds out a mathematician has just proved P=NP. He and his partners, spies for some unknown authority, try to suppress the information - at first the reader has no idea why - but fail. They decide to escape instead, and just barely make it as AI quickly takes over human society; there's a scene where they sneak past security officers wearing unusual earpieces who are clearly being remote controlled. As they escape into a parallel universe, the protagonists reflect on their good luck in coming from one of the few timelines not taken over by AI - but it becomes obvious to the reader that they are also under control, and have been brainwashed into believing that their AI overlord is the good one.


text:
Q: Only want clang for source-to-source transforms; how do I build clang without the LLVM backend? I am using clang to write source-to-source transforms, so I do not need the code generation backend.  Further, the size of the Clang/LLVM executable is a problem:

*

*I am constantly recompiling my transforms and the linking stage takes a long time.

*If I ever have to run it in the debugger, it takes minutes to load into gdb.
How do I configure the Clang/LLVM build process to build Clang without the LLVM backend?


text:
Q: my first conan package not getting found by CMAKE? I have seemingly successfully built my first local conan package and uploaded it to my local artifactory.. I can also add it by full name in the dependencies of other projects like so..
[requires]
thrift/0.13.0
mypkg/0.0.1@user/channel

[generators]
cmake

I can link it without error likeso in my OtherProject CMakeLists.txt
cmake_minimum_required(VERSION 2.8.12)
project(OtherProject)
add_compile_options(-std=c++11)

# Using the "cmake" generator
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup(TARGETS)

add_executable(OtherProject src/Main.cpp)
target_link_libraries(OtherProject CONAN_PKG::my-pkg)

but when I attempt to reference this in my consuming project's C++ it fails to find the mypkg.a file or any headers I expect to be available to it?  Did I build my recipe incorrectly?  Or am I just needing to change how I reference my new conan package in my code ?
OtherProject/consumingHeader.H
#pragma once
#include "MyPkgsHeader.h"

Error on build
> cmake --build .
Scanning dependencies of target OtherProject
[ 50%] Building CXX object CMakeFiles/OtherProject.dir/src/Main.cpp.o
In file included from /OtherProject/src/Main.cpp:12:
/OtherProject/src/TestCppClient.h:8:10: fatal error: 'MyPkgsHeader.h' file not found
#include "MyPkgsHeader.h"
         ^~~~~~~~~~~~~~~~~~~~
1 error generated.
make[2]: *** [CMakeFiles/OtherProject.dir/src/Main.cpp.o] Error 1
make[1]: *** [CMakeFiles/OtherProject.dir/all] Error 2
make: *** [all] Error 2

MyPkg Recipe conanfile.py
from conans import ConanFile, CMake, tools

class MyPkgConan(ConanFile):
    name = "mypkg"
    version = "0.0.1"
    license = "<Put the package license here>"
    author = "<Put your name here> <And your email here>"
    url = "<Package recipe repository url here, for issues about the package>"
    description = "<Description of mypkg here>"
    topics = ("<Put some tag here>", "<here>", "<and here>")
    settings = "os", "compiler", "build_type", "arch"
    options = {"shared": [True, False]}
    default_options = {"shared": False}
    generators = "cmake"

    def source(self):
        self.run("git clone --depth 1 --branch 0.0.1 git@github.com:PROJECT/my-pkg.git")

        tools.replace_in_file("my-pkg/CMakeLists.txt", "         LANGUAGES CXX )",
                              '''         LANGUAGES CXX )
add_compile_options(-std=c++11)''')

    def build(self):
        cmake = CMake(self)
        cmake.configure(source_folder="my-pkg")
        cmake.build()

        # Explicit way:
        # self.run('cmake %s/hello %s'
        #          % (self.source_folder, cmake.command_line))
        # self.run("cmake --build . %s" % cmake.build_config)

    def package(self):
        self.copy("*.h", dst="include", src="my-pkg")
        self.copy("*hello.lib", dst="lib", keep_path=False)
        self.copy("*.dll", dst="bin", keep_path=False)
        self.copy("*.so", dst="lib", keep_path=False)
        self.copy("*.dylib", dst="lib", keep_path=False)
        self.copy("*.a", dst="lib", keep_path=False)

    def package_info(self):
        self.cpp_info.libs = ["mypkg"]

#EDIT: Seeing a problem with includes folder
As instructed I took a look at my conanbuildinfo.cmake and specifically looked for the path under CONAN_INCLUDE_DIRS_MY-PKG
the source files are in a folder structure I didn't expect
/../<conanhash>/include/source/cppclient/client/MyPkgsHeader.h

when I was expected perhaps
/../<conanhash>/client/MyPkgsHeader.h

or

/../<conanhash>/MyPkgsHeader.h

Sounds like I need to change my recipe a bit...

A: The right process to debug this kind of problems is the following:

*

*Check the generated conanbuildinfo.cmake file, it will contain variables like CONAN_INCLUDE_DIRS pointing to folders in the Conan cache, that should contain the expected headers.

*If you cannot identify the variables in the conanbuildinfo.cmake that belongs to your missing dependency, it might be that you are missing a requires = "pkg/version..." in your recipe, or to execute conan install again to fetch that dependency and generate a new conanbuildinfo.cmake

*Navigate to those folders, check if the expected headers are there. If they are not, it seems that the package was incorrectly created. You need to go back to the recipe that created that package, fix it and execute conan create again

*Most common problems while packaging the final artifacts is some wrong pattern or path in the self.copy() calls inside the package() method. For headers the call would be something like self.copy("*.h", dst="include", src="<path/to/headers>"), where the src argument could be wrong.

*It is possible to go to the Conan cache folder and navigate inside after a conan create and check manually if the expected files are there.

In order to avoid problems of incorrectly created packages, it is very recommended to use the test_package functionality. In short it is a "consumer" project, together with the package recipe that will be automatically fired when conan create, and it will install+build+execute whatever app you tell it, to make some basic checks about the package and fail as early as possible if not correct. Check the "test_package" docs


text:
Q: How can I create Samsung's "Fix Now" button with gradient animation in Android Studio How can I create this awesome button with gradient animation? I attached a GIF.

A: Make a drawable for background and set in on back
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
    android:radius="14dp"
    />
<gradient
    android:angle="45"
    android:centerX="34%"
    android:startColor="#56ab2f"
    android:endColor="#a8e063"
    android:type="linear"
    />
<padding
    android:left="0dp"
    android:top="0dp"
    android:right="0dp"
    android:bottom="0dp"
    />
<size
    android:width="270dp"
    android:height="60dp"
    />
<stroke
    android:width="3dp"
    android:color="#1d5b01"
    />
</shape>


text:
Q: How To Write Condition Statement based on Data from Database I am new learner for vb. I created 2 form (Form1 & Form2)
Form1 is a profile subject for user which will be saved in database. There is three combobox = Name,Subject 1, Subject 2.
form1 Screen Shot:

View in database : I don't have any problem to save the data into database. I used the code below.
Database Screen Shot:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim constr As String = "server=localhost;user=root;database=test;port=3306;password=root123;SslMode=none"
    Dim conn As MySqlConnection = New MySqlConnection(constr)
    Dim result As Integer
    'If True Then
    Try
        conn.Open()
        With {}
            Dim cmd As MySqlCommand

            cmd = New MySqlCommand("INSERT INTO profilesubject(name,subject1,subject2) VALUES(@name,@subject1,@subject2)", conn)
            cmd.Parameters.AddWithValue("@name", ComboBox1.Text)

            cmd.Parameters.AddWithValue("@subject1", ComboBox2.Text)
            cmd.Parameters.AddWithValue("@subject2", ComboBox3.Text)
            result = cmd.ExecuteNonQuery()
            'conn.Close()
        End With
        'End If

        If result > 0 Then

            MsgBox("Record has been saved")

        Else
            MsgBox("Error!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
        End If

    Catch ex As Exception
        Console.WriteLine(ex.ToString())
        MsgBox(ex.Message)

    Finally
        conn.Close()
    End Try

End Sub

For example :
User 1( Name : John, Subject 1:Mathematics, Subject 2: English)
User 2( Name : Mark, Subject 1:Mathematics, Subject 2: English)
User 3(Name : Brenda, Subject 1:History, Subject 2: Science)
After the data have been saved, when we click button in form1, form2 will appear.
form2 Screen Shot:

form2 has 2 combobox which is subject and name. Based on the data saved from previous database, If the user choose 'Mathematics' for subject in form2, the name who choose 'Mathematics' will appear in the combobox for name(which select from database). So the combobox value should appear (John and Mark), If the user choose 'History' for subject, the combobox for name should appear 'Brenda'.
The problem is, i don't know how to write a proper condition statement from database. This is my code. but it is not working. I hope you guys can help me to solve it.
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    Dim connStr As String = "server=localhost;user=root;database=test;port=3306;password=root123;SslMode=none"
    Dim con As New MySqlConnection(connStr)
    Dim cmd As New MySqlCommand()

    Dim reader As MySqlDataReader
    con.Open()
    cmd.Connection = con
    cmd.CommandText = "select subject1,subject2 FROM profilesubject WHERE subject1=@subject1,subject2=@subject2)"
    reader = cmd.ExecuteReader
    cmd.Parameters("@subject1").Value = ComboBox1.Text
    cmd.Parameters("@subject2").Value = ComboBox1.Text

    If (reader.Item("@subject1").Equals(ComboBox1.Text) & (reader.Item("@subject2").Equals(ComboBox1.Text))) Then

        Dim adapter As New MySqlDataAdapter("SELECT `id`, `name`, `subject1`, `subject2` FROM test.profilesubject", con)
        Dim table As New DataTable()

        adapter.Fill(table)

        ComboBox1.DataSource = table

        ComboBox1.ValueMember = "id"
        ComboBox1.DisplayMember = "name"
    End If
    con.Close()
End Sub

A: If I understand correctly, Form1.Subject1, Form1.Subject2, and Form2.Subject combo boxes all have the same list of subjects. So, you want, on Form2 in combo Name a list of all students who have chosen the subject in Form2.Subject either as Subject1 or Subject2.
To accomplish this you need to search 2 columns for the subject. You need the id and name returned.
Select name, id From test.profilesubject Where subject1 = @subject Or subject2 = @subject;
A Using...End Using block will close and dispose your database objects that may be using unmanaged code. This will happen even if there is an error.
Good job using Parameters! This is very important to protect your database.
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
        'Use this event instead of SelectedIndexChanged so it won't jump
        'around when you load the combobox
        Dim connStr As String = "server=localhost;user=root;database=test;port=3306;password=root123;SslMode=none"
        Dim table As New DataTable()
        Try
            Using con As New MySqlConnection(connStr)
                'Pass the sql statement and the connection to
                'the Constructor of the Command
                Using cmd As New MySqlCommand("Select name, id From test.profilesubject Where subject1 = @subject Or subject2 = @subject;", con)
                    'you are looking for the same value in subject1 and subject2
                    'so you only need one parameter
                    'Check the data type of the subject field in your database
                    'and alter this line if necessary
                    cmd.Parameters.Add("@subject", MySqlDbType.Text).Value = ComboBox1.Text
                    con.Open()
                    'the Load method of a DataTable takes a DataReader as
                    'a parameter and ExecuteReader returns a DataReader
                    table.Load(cmd.ExecuteReader)
                End Using
            End Using
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        If table.Rows.Count > 0 Then
            ComboBox1.DataSource = table
            ComboBox1.ValueMember = "id"
            ComboBox1.DisplayMember = "name"
        Else
            MessageBox.Show("Sorry, no matches")
        End If
End Sub


text:
Q: Android Animation - Rotate Image Moves Irregularly when start the animation it moves slow in the beginning and it gets faster as it move. anyone suggest me. here is my code
  Animation rotateAnim;
  rotateAnim = new RotateAnimation(0, 360,
                                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
  rotateAnim.setDuration(60*1000);
  rotateAnim.setInterpolator(new AccelerateInterpolator());
  _mClockNeedle.startAnimation(rotateAnim);

A: You are using a AccelerateInterpolator. The behavior you describe is how this class is made, as specified in the API. You may want to use the LinearInterpolator instead, if you want it to move at a constant rate. There are also other subclasses of Interpolator to chose from.
If you wish for the animation to be shorter or longer this is done with the setDuration method, in milliseconds, as you've set it to 1 minute in your example.


text:
Q: Como no cerrar aplicación de servidor con Sockets tengo una aplicación en java en la que intento levantar un servidor mediante sockets para que después una aplicación cliente le realice peticiones.
El caso es que la aplicación, tal y como la tengo ahora mismo se me cierra, por lo que el cliente nunca podrá conectarse. Adjunto código:
public class ServerApplication {

static final int Port = 8000;

int[] asientos[] = {
    {0, 1, 0, 0},
    {1, 1, 1, 0},
    {0, 1, 0, 1},
    {0, 1, 0, 0},
    {1, 1, 1, 0},
    {1, 1, 1, 1},
    {0, 0, 0, 0},
    {0, 0, 0, 0},
    {0, 0, 0, 1},
    {0, 0, 0, 0}
};

void dibujarAsientos(int[] asientos[]) {
    for (int i = 0; i <= asientos.length; i++) {
        System.out.println();
        for (int j = 0; j < asientos[i].length; j++) {
            System.out.print(asientos[i][j] + " ");
        }
    }
}

public ServerApplication() {
    try {
        ServerSocket skServer = new ServerSocket(Port);
        System.out.println("Escucho al puerto " + Port);
        dibujarAsientos(asientos);
        for (int nClient = 0; nClient < 3; nClient++) {
            Socket sClient = skServer.accept();
            System.out.println("Sirvo al cliente " + nClient);
            OutputStream aux = sClient.getOutputStream();
            DataOutputStream flujo_salida = new DataOutputStream(aux);
            flujo_salida.writeUTF("Hola cliente " + nClient);
            sClient.close();
        }
        System.out.println("Ya se han atendido los 3 clientes");
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

public static void main(String[] args) {
    new ServerApplication();
}

}
En resumen, quiero que esta aplicación quede siempre ejecutándose en un segundo plano, ya que va a ser el servidor al que el cliente va a realizar peticiones.
Un saludo.

A: El socket servidor se cierra por esta linea.
sClient.close();

Si quieres tener un servidor gestionando las peticiones debes de cambiar tu código.
Aqui te dejo un ejemplo de como crear un socket y recibir peticiones.
//Servidor
public class MyServerSocket {
    private ServerSocket server;
    public MyServerSocket(String ipAddress) throws Exception {
        if (ipAddress != null && !ipAddress.isEmpty())
          this.server = new ServerSocket(0, 1, InetAddress.getByName(ipAddress));
        else
          this.server = new ServerSocket(0, 1, InetAddress.getLocalHost());
    }

    private void listen() throws Exception {
        String data = null;
        Socket client = this.server.accept();
        String clientAddress = client.getInetAddress().getHostAddress();
        System.out.println("\r\nNew connection from " + clientAddress);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(client.getInputStream()));
        while ( (data = in.readLine()) != null ) {
            System.out.println("\r\nMessage from " + clientAddress + ": " + data);
        }
    }

    public InetAddress getSocketAddress() {
        return this.server.getInetAddress();
    }

    public int getPort() {
        return this.server.getLocalPort();
    }
    public static void main(String[] args) throws Exception {
        MyServerSocket app = new MyServerSocket(args[0]);
        System.out.println("\r\nRunning Server: " +
                "Host=" + app.getSocketAddress().getHostAddress() +
                " Port=" + app.getPort());

        app.listen();
    }
}

//cliente

public class MySocketClient {
    private Socket socket;
    private Scanner scanner;

    private MySocketClient(InetAddress serverAddress, int serverPort) throws Exception {
        this.socket = new Socket(serverAddress, serverPort);
        this.scanner = new Scanner(System.in);
    }

    private void start() throws IOException {
        String input;
        while (true) {
            input = scanner.nextLine();
            PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true);
            out.println(input);
            out.flush();
        }
    }

    public static void main(String[] args) throws Exception {
        MySocketClient client = new MySocketClient(
                InetAddress.getByName(args[0]),
                Integer.parseInt(args[1]));

        System.out.println("\r\nConnected to Server: " + client.socket.getInetAddress());
        client.start();
    }
}

Antes de ejecutar debes de crear un proyecto java y empaquetarlo en un jar.
Forma de ejecución en consola.
    1.- Iniciar el server

         java -cp + jar + clase del servidor +  ip
         Ejemplo:
         java -cp TCPSocket.jar main.java.MyServerSocket 192.168.100.15

    2.- Iniciar el cliente.

         java -cp + jar + clase del servidor + ip + puerto
         Ejemplo:
         java -cp TCPSocket.jar main.java.MySocketClient 192.168.100.15 63015

         El puerto lo ves cuando ejecutas el servidor (paso 1)
    3.- Enviar mensaje al server.
        al inicial el cliente te dará un mensaje como el siguiente.
        Connected to Server: /192.168.100.15
        le das enter y escribes el mensaje a enviar.
    4.- En la ventana de consola donde ejecutas el server le das enter y verás el mensaje que se ha enviado.

Nota: Este código lo puedes usar, solo cambia el mensaje a enviar y listo.


text:
Q: Remove from tensor randomly I am trying to remove a row from a tensor randomly. The easiest way I saw so far is as follows (as referenced here):
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
a_vecs = tf.unstack(a, axis=1)
val = tf.constant(1)
del a_vecs[val]
a_new = tf.stack(a_vecs, 1)

I want to pass to "del" a random integer that is based on a tensor operation. But when I use:
ran = tf.random_uniform((1,), minval=0, maxval=val, dtype=tf.int32)

I get back an array, and the del doesn't accept array. Also if there's an easier way to remove from the array let me know.

A: You can use tf.boolean_mask of any size and shape you need. Create numpy array of bool values of desired shape with np.random.choice
#your_shape = int or array
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
ran = tf.random_uniform((1,), minval=0, maxval=2, dtype=tf.int32)
a_vecs = tf.unstack(a, axis=1)
rm = np.random.choice([True, False], your_shape)
a_new = tf.boolean_mask(a_vecs, rm)

Or you can  turn array to scalar with np.asscalar, but it will require running within a session.
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
ran = tf.random_uniform((1,), minval=0, maxval=2, dtype=tf.int32)
a_vecs = tf.unstack(a, axis=1)
with tf.Session() as sess:
    r = ran.eval()
    val = np.asscalar(r)
    del a_vecs[val]
    a_new = tf.stack(a_vecs, 1)


text:
Q: Add prefix to twig trans filter I have a messages.de.yml that looks like
...
profile:
    ...
    availability:
        ...
        4_week: Vier mal pro Woche
        ...
...

(The ... are not important for this example)
I have a user class that has a field called availability. I want to display this field in the user's profile and to translate it. Let's assume the value of user.availability is "4_week"
This code is working:
{{ ("profile.availability." ~ user.availability)|trans }}

But is this really the recommended way? I tried using profile.availability / messages.profile.availability as domain:
{{ user.availability|trans({}, "profile.availability") }}

But the output is just 4_week and not "Vier mal pro Woche" as expected.
Simon

A: Yes, this is the recommended way.


text:
Q: ngControlStatus (valid, invalid, pristine, dirty, etc.) not working on  I am trying to do some form validation and for some reason when I try to add a class to my select with the condition of myTest.pristine nothing happens. This works fine on a regular input however. Please see my example below.

  Primary Language *
  <select  class="form-control" #primaryLanguage name="primaryLanguage" [(ngModel)]="model.primaryLanguage">
    <option value="default">Select a Language...</option>
    <option *ngFor="let lang of languages">{{ lang }}</option>
  </select>

Required

A: After looking into this further I found that my #primaryLanguage was not set equal to ngModel. This has solved my issue.

A: Your default value needs to be empty i.e;
<option value="">Select a Language...</option>

and also initially set
model.primaryLanguage = "";

so your final code will be

    Primary Language *
     <select  class="form-control" #primaryLanguage name="primaryLanguage" [(ngModel)]="model.primaryLanguage" required>
       <option value="">Select a Language...</option>
       <option *ngFor="let lang of languages" value="{{yourlanguaugeid}}">{{ lang }}</option>
     </select>

Required


text:
Q: Kendo Scheduler embedded in kendo mobile tabstrip I have a kendo scheduler defined in partial view. This partial view is rendered in a kendo mobile tabstrip.
The problem is that the scheduler seems to be displayed behind some empty container. As I see only a small part of the scheduler header when I try it on a mobile phone (iPhone 5).
When I hook the Databound event in javascript and I set a "debugger" break point, I can see that the "mobile" version is rendered (I used google chrome developper tools to simulate the display on a mobile phone), but right after the execution of the event, some div or other container partially cover my scheduler.
If I don't specify the ".Mobile()" attribute in the definition of the scheduler, it is displayed accordingly on my phone. But it's not the mobile version that it's rendered and I want it to be the mobile version.
I tried to display an empty scheduler and it's not working either.
Any ideas of what I'm doing wrong?
If there's any missing information to help you, feel free to ask for it.
Thank you.
The partial view :
@model List<ISchedulerEvent>
@using System.Web.UI.WebControls
@using System.Linq;
@using Kendo.Mvc.UI

@(Html.Kendo().Scheduler<ISchedulerEvent>()
  .Name("scheduler")
  .WorkDayStart(8,0,0)
  .WorkDayEnd(18,0,0)
  .AllDaySlot(false)
  .ShowWorkHours(true)
  .Editable(false)
  .Mobile()
  .Views(v =>
         {
             v.DayView();
             v.WeekView();
             v.MonthView(monthView => monthView.Selected(true));
             v.AgendaView();
         })
  .DataSource(source => source
      .Read("GetEntries", "Calendar")))

The tabstrip definition :
@using Kendo.Mvc.UI
@using T3.Web.Application.Infrastructure.Helpers

@Html.Action("Index", "Calendar")

TabStrip

        Entrée de temps
        Calendrier
        Sommaire
        Utilisateur

The Controller for the partial view
[HttpGet]
public ActionResult Index()
{
   return this.PartialView("_Calendar");
}

The controller that returns the data for the scheduler
public ActionResult GetEntries([DataSourceRequest]DataSourceRequest request)
{
   var entries = _presenter.GetEntries(base.GetUserAccount().Id);
   return Json(entries.ToDataSourceResult(request));
}

A: With a colleague, we finally found the answer. The problem seems to be within kendo-mobile itself. If I used the scheduler outside the mobile tabstrip, there was no layout problem. The problem occured only with the tabstrib.
It seems to come from the fact that both the scheduler and the tabsrip add a container ".km-content". When debugging using firebug we found that the first ".km-content" of the tabstrip view, was not resized accordingly.
We found a way to manage it manually using javascript. To achieve this we calculate the size between the header and footer of the tabstrip then we assigned it the to first ".km-content" of the tabstrip view. When it's done,  we force the scheduler to update it's own size to fit the new available height.
function resizeView() {

    var windowHeight = $(window).height();
    var tabstripFooterHeight = $(".km-footer").height();
    var tabstripHeaderHeight = $(".km-header").height();

    var padding = (tabstripFooterHeight + tabstripHeaderHeight + 5);

    var contentHeight = windowHeight - padding;
    $(".km-view:visible").children(".km-content").first().height((contentHeight));

    tryResizeScheduler(contentHeight);
}

function tryResizeScheduler(contentHeight) {

    /* Is the calendar tab */
    if (_app.view().id === "/") {
        var schedulerHeight = contentHeight - 1;

        var scheduler = $("#entryScheduler").data("kendoScheduler");
        scheduler.wrapper.height(schedulerHeight);
        scheduler.resize();
    }
}


text:
Q: Xcode, images, core data, incompatible pointers, persisting image data I am very green to programming.
I am using a couple tutorials to build an app but have run into a problem.
I built both tutorial projects and they work.
I integrated them but running into some problems incorporating into the core data project.
Pt 1: The core data works and stores/displayes patient and prescription info.
Pt 2. camera / photo picker gives access to camera and photo library and displays it in the same view with patient or prescription info.
This all works BUT
When I go to add the image to the list of stuff to be saved I get: Incompatible pointer types assigning to NSString from UIImage
Sample Code:
- (IBAction)save:(UIBarButtonItem *)sender {

    ////telling core data what information to save and what fields it came from.
Corresponds with properties up in the text entry area.

    addPrescription.patient = prescriptionsPatient;

    addPrescription.prescriptionName = _prescriptionName.text;

    addPrescription.prescriptionInstructions = _prescriptionInstructions.text;

    addPrescription.scene = _scene.text;

    addPrescription.look = _lookimage.image;

i read a bunch of post on converting NSString to NSDAta for core data to play nice but they didnt seem to apply to what I was doing.
NOTE: my COre Data model has  2 entities and both have an attribute that I'd like to be an image (or its URL)
I have one as Binary Data and another as NSString so I can try to make it work either way using one OR the other.
Any help would be great.
Many thanks

A: Go with the file path string being stored in Core Data and the image file being stored to disk.
Use UIImageJPEGRepresentation to get the data from the image and writeToFile:atomically: to save that data to disk. Then use the file path with your managed object instance.


text:
Q: Is each instance of Tk() class running independent of each other? I have been learning how to make GUIs with Tkinter and a question has occurred to me. As I'm testing the program, I often end up building the code while an instance of it already exists in the background. Are these two independent of each other in terms of performing their functions? I've always read that when I create the instance of the Tk() and then run its mainloop(), that is what takes care of everything. Can I have two or more loops running if each pertains to a different Tk() instance?

A: Each instance of Tk is separate from any other instance of Tk. It gets its own copy of an underlying tcl interpreter. Two instance of Tk in the same process means you have two active tcl interpreters.
As a general rule you should only ever have exactly one instance of Tk, but I suppose if you fully understand how they work, it should be possible to have two or more.
I think this falls into the category of things you shouldn't do until you understand why you shouldn't do them. And once you understand, you won't want to do it.


text:
Q: How do I make a GUI that behaves like this? This is difficult to explain without illustration, so - behold, an illustration, cobbled together from screenshots of a few hello-world examples and a lot of Paint work:

I have started out using Windows Forms on .NET (via IronPython, but that shouldn't be important), and haven't been able to figure out very much. GUI libraries in general are very intimidating, simply because every class has so many possible attributes. Documentation is good at explaining what everything does, but not so good at helping you figure out what you need.
I will be assembling the GUI dynamically, but I'm not expecting that to be the hard part. The sticking points for me right now are:

*

*How do I get text labels to size themselves automatically to the width of the contained text (so that the text doesn't clip, and I also don't reserve unnecessary space for them when resizing the window)?

*How do I make the vertical scrollbar always appear? Setting the VScroll property (why is this protected when AutoScroll is public, BTW?) doesn't seem to do anything.

*How come the horizontal scrollbar is not added by AutoScroll when contents are laid out vertically (via Dock = DockStyle.Top)? I can use a minimum size for panels to prevent the label and corresponding control from overlapping when the window is shrunk horizontally, but then the scrollbar doesn't appear and the control is inaccessible.

*How can I put limits on window resizing (e.g. set a minimum width) without disabling it completely? (Just set minimum/maximum sizes for the Form?) Related to that, is there any way to set minimum/maximum widths or heights without setting a minimum/maximum size (i.e. can I constrain the size in only one dimension)?

*Is there a built-in control suitable for hex editing or am I going to have to build something myself?
... And should I be using something else (perhaps something more capable?) I've heard WPF mentioned, but I understand that this involves XML and I really want to build a GUI from XML - I already have data in an object graph, and doing some kind of weird XML pseudo-serialization (in Python, no less!) in order to create a GUI seems incredibly roundabout.

A: If you're willing to use Java/Swing that basic form should be pretty easy.  I'd like to say that the Netbeans IDE has a pretty good WYSIWYG GUI editor.  Even though it is pretty good I'd by lying if I said that is all there is to it.  You have to understand Swing to get things the way you want or you'll be bashing your head against the wall. It's free.  Most of what you ask for are properties of the GUI builder, you'll need to at least look before asking specifics.
I've had very little experience with Visual Basic, something about the language aggravated me but there is nothing I've seen easier to slap a simple GUI together with.

A: I ended up using WPF.
Getting access to the functionality from IronPython is more involved than I would have expected:
import clr
clr.AddReferenceByName("PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
clr.AddReferenceByName("PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
clr.AddReferenceByName("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
import System.Windows

(I'm not sure if I can/should change the version number. The PublicKeyToken presumably has to do with some kind of DLL signing for security purposes; I don't know why WPF requires this but WinForms didn't.)
Since the namespaces for widgets get quite hairy and there are a lot of names that I want to import, I set up some dynamic import code:
def Import(namespace, what):
    if isinstance(what, str):
        globals()[what] = getattr(namespace, what)
    else:
        for k, v in what.items():
            if k: namespace = getattr(namespace, k)
            for name in v:
                Import(namespace, name)

After figuring out the right combination of layout tools (which wasn't as easy as this summary makes it sound), everything seems to "just work" and I'm quite pleased. The scroll behaviour is accomplished by setting up a ScrollViewer inside the main window and setting the HorizontalScrollBarVisibility to Auto. Inside the ScrollViewer I put a StackPanel which stacks the "field frames", each of which is a Grid with two columns (I add two default ColumnDefinition s to the Grid.ColumnDefinitions). I set the "label" up in column 0, and the "value" widget (combo box, button, whatever) in column 1, with a HorizontalAlignment of Right.
I haven't set up the nested panels yet, but it seems like it shouldn't be difficult. I've already played around with the system for hooking up events to buttons.


text:
Q: LINQ query throwing Null reference exception I am using LINQ query to populate a datagrid. As part of the new enhancement I have to change the existing LINQ query by including one more condition in WHERE clause.
Looked at so many posts and felt stacking WHERE clause condition would be simple.
Earlier the query was returning simple object type(anonymous) and working fine.
Now I divided the query into 2 parts. In first part I am trying to return the known type and trying to stack where clause in the next part.
But some how this is not working and not fetching any results. It is throwing NULL reference exception on grid.DataBind is throwing exception(Null reference exception.)
Posting my code here.
Using db As New ProjectDataContext
        Dim orderLines As IEnumerable(Of orderline)
        Dim customOrderLines As Object
        Try
            If VATSearch = 1 Then
                ' Show only VAT orders
                'orderlines = (From O In db.orderlines Where O.order.order_date > MinTime And O.order.order_date < MaxTime And O.order.order_status_fk > 1 And (O.ol_vat_free Is Nothing OrElse O.ol_vat_free = 0) Order By O.order.order_date _
                '        Select OrderLineID = O.ol_id, Ref = O.order.order_ref, Email = CStr(IIf(O.order.User Is Nothing, O.order.order_billing_email, O.order.User.user_email)), Code = O.StockItem.productsbycolor.product.product_code & O.StockItem.productsbycolor.color.color_code, Size = O.size.size_code, Qty = O.ol_qty, Price = O.ol_product_price, LineTotal = O.ol_lineprice, Delivery = (O.order.order_delivery_total / O.order.orderlines.Count), NonVAT = O.order.order_vat_free _
                '            )
                orderLines = (From o In db.orderlines Where o.order.order_date > MinTime And o.order.order_date < MaxTime And o.order.order_status_fk > 1 And (o.ol_vat_free Is Nothing OrElse o.ol_vat_free = 0) Order By o.order.order_date _
                Select o)

            ElseIf VATSearch = 2 Then
                ' Show only non-VAT orders
                'orderlines = (From O In db.orderlines Where O.order.order_date > MinTime And O.order.order_date < MaxTime And O.order.order_status_fk > 1 And (Not O.ol_vat_free Is Nothing) AndAlso O.ol_vat_free = 1 Order By O.order.order_date _
                '    Select OrderLineID = O.ol_id, Ref = O.order.order_ref, Email = CStr(IIf(O.order.User Is Nothing, O.order.order_billing_email, O.order.User.user_email)), Code = O.StockItem.productsbycolor.product.product_code & O.StockItem.productsbycolor.color.color_code, Size = O.size.size_code, Qty = O.ol_qty, Price = O.ol_product_price, LineTotal = O.ol_lineprice, Delivery = (O.order.order_delivery_total / O.order.orderlines.Count), NonVAT = O.order.order_vat_free _
                '                )
                orderLines = (From O In db.orderlines Where O.order.order_date > MinTime And O.order.order_date < MaxTime And O.order.order_status_fk > 1 And (Not O.ol_vat_free Is Nothing) AndAlso O.ol_vat_free = 1 Order By O.order.order_date _
                        Select O)
            Else
                ' Show both VAT and non-VAT orders
                'orderlines = (From O In db.orderlines Where O.order.order_date > MinTime And O.order.order_date < MaxTime And O.order.order_status_fk > 1 Order By O.order.order_date _
                '   Select OrderLineID = O.ol_id, Ref = O.order.order_ref, Email = CStr(IIf(O.order.User Is Nothing, O.order.order_billing_email, O.order.User.user_email)), Code = O.StockItem.productsbycolor.product.product_code & O.StockItem.productsbycolor.color.color_code, Size = O.size.size_code, Qty = O.ol_qty, Price = O.ol_product_price, LineTotal = O.ol_lineprice, Delivery = (O.order.order_delivery_total / O.order.orderlines.Count), NonVAT = O.order.order_vat_free _
                '            )
                orderLines = (From o In db.orderlines Where o.order.order_date > MinTime And o.order.order_date < MaxTime And o.order.order_status_fk > 1 Order By o.order.order_date _
                        Select o)
            End If

            customOrderLines = (From o In orderLines
                        Select orderLineID = o.ol_id, ref = o.order.order_ref, email = CStr(IIf(o.order.User Is Nothing, o.order.order_billing_email, o.order.User.user_email)),
                        code = o.StockItem.productsbycolor.product.product_code & o.StockItem.productsbycolor.color.color_code,
                        size = o.size.size_code, qty = o.ol_qty, price = o.ol_product_price, lineTotal = o.ol_lineprice,
                        delivery = (o.order.order_delivery_total / o.order.orderlines.Count), nonVAT = o.order.order_vat_free, orderPaymentType = o.order.order_google_order_number)

            results.DataSource = customOrderLines
            results.DataBind()
            results.Visible = True
            btnExportButton.Visible = True

        Catch ex As Exception

        End Try
    End Using

A: use new after select to create anonymous type  and enclose it in braces.
customOrderLines = (From o In orderLines
                    Select new { orderLineID = o.ol_id, ref = o.order.order_ref, email = CStr(IIf(o.order.User Is Nothing, o.order.order_billing_email, o.order.User.user_email)),
                    code = o.StockItem.productsbycolor.product.product_code & o.StockItem.productsbycolor.color.color_code,
                    size = o.size.size_code, qty = o.ol_qty, price = o.ol_product_price, lineTotal = o.ol_lineprice,
                    delivery = (o.order.order_delivery_total / o.order.orderlines.Count), nonVAT = o.order.order_vat_free, orderPaymentType = o.order.order_google_order_number})

I hope this will help.

A: The error you are getting indicates that the LINQ you are trying to run isn't returning any values so customOrderLines is coming back as an empty collection. Since the LINQ includes quite a few filters I would suggest removing Dim customOrderLines As Object and instead doing something like:
Dim customOrderLines = (From o In orderLines
  Select orderLineID = o.ol_id, ref = o.order.order_ref,
  email = CStr(IIf(o.order.User Is Nothing, o.order.order_billing_email, o.order.User.user_email)),
  code = o.StockItem.productsbycolor.product.product_code & o.StockItem.productsbycolor.color.color_code,
  size = o.size.size_code, qty = o.ol_qty, price = o.ol_product_price, lineTotal = o.ol_lineprice,
  delivery = (o.order.order_delivery_total / o.order.orderlines.Count), nonVAT = o.order.order_vat_free,
  orderPaymentType = o.order.order_google_order_number)

if customOrderLines isnot nothing andalso customOrderLines.Any then
  results.DataSource = customOrderLines
  results.DataBind()
  results.Visible = True
  btnExportButton.Visible = True
else
  results.DataSource = nothing
  results.DataBind()
  results.Visible = False
  btnExportButton.Visible = False
end if

This will ensure that you don't try to bind an empty collection and also it will clear out your datagrid if nothing is returned by the LINQ.
But the main issue is still that your LINQ is returning an empty collection somewhere along the line. I would mainly suggest going back and ensuring that the LINQ is actually bringing back what you expect using LINQpad or another utility like it.
You can get LinqPad Here.

A: I was getting error because I was using IIF for null check.
Sometimes it is returning null and query was throwing NULL reference exception.
Now I am using IF instead of IIF and it is working fine.

*

*Naresh

A: I am on this page because I got a NullReferenceException on this:
var allHeights = MyCities.SelectMany(city =>
    city.Houses.SelectMany(h =>
        h.Storeys.Values.Select(s => new { City = city, House = h, Storey = s })))
   .GroupBy(g => g.Storey.Height)
   .OrderBy(heightGroup => heightGroup.Key)
   .ToList();
int i = 0;
foreach (var heightGroup in allHeights)
{
    if (i > 1)
    {
        var previousHeightGroup = allHeights[i-1].ToList();
        var previousPartIDs = previousHeightGroup.Select(g => g?.City?.Name).ToList();
        //.... <do stuff in case of i > 0>
    }
    // do other stuff
    i++;
}

"previousHeightGroup.Select(g => g?.City?.Name).ToList()" threw a NullReferenceException, even though:

*

*None of the elements of this data structure was null

*The previousHeightGroup was not empty

*The "Name" was a string property on the City object and was nonempty

*The Values collection on the Storeys object is nonempty

*Anyway, at the time of the NullReferenceException, the allHeights List should have been fully evaluated by the ToList() call, and the Values resolved

*obviously, all accidental null member accesses are protected with the Elvis operator, even though the members accessed are actually not null

Moreover, I refactored the code like this:
.Select(g => {
   var group = g;
   var city = g?.City;
   var cityName = city?.Name;
   return cityName;
})

... i.e., I broke up the data structure dereferencing inside the Select and single-stepped through it in the debugger, it all worked fine.
Nevertheless, the Select() call then had a NullReferenceException, allegedly in my own code.
The only way to fix this was to refactor the code downstream a little, shut down Visual Studio (2017) and the entire machine, restart everything, and the error did not reproduce any more.
That means, LINQ does throw up sometimes here and there.
This was .Net 4.6.1 .


text:
Q: Custom Dialog or dialog themed activity I see many developers choosing to theme their activity as a dialog instead of using the android dialog and customize it.
I searched on the internet for this answer but couldn't find it.
Could someone give me the pro's and con's of the activity theme method? Of course, it gives you more freedom but are there any styling reasons to avoid customizing the standard dialog?
I, myself needed to re-use fragments in dialogs so I created a themed activity to comfort my needs but now I'm running into trouble at retrieving results from the themed activity.
Thanks in advance.
Bram

A: 1) Start your activity using startActivityForResult.
2) Before you close your dialog-styled activity add needed data to intent extras and save it using SetResult(int, intent).
3) To process results add code to anActivityResult of parent activity that will retrieve data from saved intent.
no probs.
Yes, if you need to add heavy custom logic to your "dialog", then usage of styled activity is preferable.
In case of simple alerts - use Dialog.

A: A custom dialog is easier to create (you don't have to handle onCreate, onPause, screen rotations, ...), and have less overhead.
So you should use a custom dialog whenever you don't want to display something more complex than a dialog.


text:
Q: Error de sintaxis en SQLite Intenté actualizar elementos de una tabla con el siguiente código SQL
WITH tmp(prop_name, property) AS (VALUES ('Brand', 'Example'))
    UPDATE Property
    SET
        prop_name = tmp.prop_name, property = tmp.property
    FROM tmp
    WHERE Property.name == tmp.name;

me muestra el siguiente error de sintaxis:

near "FROM": syntax error

Dado que soy bastante novato utilizando SQL, no he podido hallar el error. Lo que si tengo entendido es que podría estar sobre from.
pd: Estoy utilizando este metodo para actualizar múltiples elementos de una tabla en una sola operación de forma dinámica, esto es debido a que estoy haciendo un sistema que requiere de esa funcionalidad en python y no estoy seguro de si sqlalchemy tiene una función que lo haga. También lo hago para saber si se puede, si no, aceptare cualquier solución alternativa.

A: La respuesta es, en primer lugar, remover el FROM porque ahí no se está haciendo nada, no es necesario y por eso lanza el error de sintaxis. Y dentro de las asignaciones del SET, no hay que poner tmp porque no se invocó desde el FROM, por decirlo de alguna manera.
La solución sería utilizar "correlated subqueries", como indicó @Cuauhtli en su comentario. El código correcto sería el siguiente:
WITH tmp(id, prop_name, property) AS (VALUES (12345, 'Brand', 'Example'))
UPDATE Property
SET
    prop_name = (SELECT prop_name
            FROM tmp
            WHERE Property.id == tmp.id)

    property = (SELECT property
            FROM tmp
            WHERE Property.id == tmp.id)

WHERE id IN (SELECT id FROM tmp)

A prop_name, property se le asignan los valores que están dentro de tmp con una "correlated subqueries" donde (WHERE) se comprueban las id de tmp y las id de la tabla Property. Si se cumple, se extrae el valor seleccionado(SELECT) desde(FROM) tmp.
El código de la última linea selecciona todas las tablas que tengan el id de tmp.
Así lo entiendo con mi escaso conocimiento de SQL


text:
Q: Confusion with referencing items in a array of pointers I'm having a little bit of trouble understanding how this code outputs 10. I understand that p is the address of the first element in the pointer array, meaning  p+1 is the address of the second element of the list. Meaning *(p+1) is the address of the first element of array n. Consequently * (*(p+1) + 1) evaluated to the 2nd element of array n. However, I'm getting confused as to how the below code prints the value 10, meaning the first element of array r. Help is greatly appreciated.
int m[4]={-2,3,6,8,9}, n[4]={7,6,4,3}, r[4]={10,-3,5};
int *p[3]={m,n,r};
printf("%d", *((p+1)[1]));

A: Starting at p:

*

*p: {m, n, r}

*p+1: {n, r}

*(p+1): {n, r}

*(p+1)[1]: r

*((p+1)[1]): r

*((p+1)[1]): {10, -3, 5}

**((p+1)[1]): 10
Note that (p+1)[1] means *((p+1)+1), not (*(p+1))+1.

A: You have an array of pointers, so p is the pointer to -2 (beginning of the m array) and p+1 is the pointer to 7 (beginning of the n array).
So p is the pointer to the beginning of the array that contains 3 pointers and p+1 is the pointer to the beginning of an array that contains 2 pointers and when you write (p+1)[1] you get the same result as p[2].
*p[2] == *(p+1)[1] == *(p+2)


text:
Q: printing multiple lists in python Hey I wrote a python code (python 2.7.3) with multiple lists, but when I try to print them they always come with a space. I want to print the list in continuous manner but I'm unable to do so. I have one list which have integer values and other with character.
Eg: list1 (integer list has 123) and list2(character list has ABC).
Desired Output: ABC123
What I'm getting:  ABC 123
What I did:
print "".join(list2),int("".join(str(x) for x in list1))

Any suggestion what I'm doing wrong?

A: l = ["A","B","C"]
l2 = [1,2,3]
print "".join(l+map(str,l2))
ABC123

map casts all ints to str, it is the same as doing [str(x) for x in l2].

A: The space comes from the print statement. It automatically inserts a space between items separated with comma. I suppose you don't need to covert the concatenated string into an integer, then you concatenate strings from join and print them as one.
print "".join(list2)+"".join(str(x) for x in list1)
Alternatively you can switch to python3's print function, and use its sep variable.
from __future__ import print_function
letters=['A','B','C']
nums=[1,2,3]
print("".join(letters),int("".join(str(x) for x in nums)), sep="")

A: The , is what's adding the space since you are printing two things, a string 'ABC' and an integer 123. Try using +, which directly adds two strings together so you can print the string 'ABC123'
>>> list1=[1,2,3]
>>> list2=['A','B','C']
>>> print "".join(list2),int("".join(str(x) for x in list1))
ABC 123
>>> print "".join(list2)+"".join(str(x) for x in list1)
ABC123

A: Try concatenating the two lists you want while printing. Use "+" instead of ",".
Here 'int' will give error as you can concatenate only strings. So try,
 print "".join(list2)"".join(str(x) for x in list1)

A: print adds a single space automatically between commas.
You can use the new print function:
from __future__ import print_function
print("".join(list2),int("".join(str(x) for x in list1)), sep="")

See docs.

Note: This function is not normally available as a built-in since the
  name print is recognized as the print statement. To disable the
  statement and use the print() function, use this future statement at
  the top of your module