text:
Q: Building apjsua sample application of pjsip for android I have followed PJSIP tutorial and I have successfully build apjsua sample application.
When I try to add account by +a it ask me for Sip Url, Url of the Registrar, Auth Realm, username, Password
I entered

*

*Sip Url : sip:140@122.252.232.5

*Registrar : sip:122.252.232.5

*Auth Realm : *

*Username : 140

*Password : example

After that it gave me following error
    10-17 19:57:27.165: I/apjsua(920): 19:57:27.165  sip_resolve.c  ...Failed to resolve '122.252.232.532.5'. Err=70018 (gethostbyname() has returned error (PJ_ERESOLVE))
10-17 19:57:27.174: I/apjsua(920): 19:57:27.174    tsx0x223a5c  ...Failed to send Request msg REGISTER/cseq=54907 (tdta0x1eb9a0)! err=70018 (gethostbyname() has returned error (PJ_ERESOLVE))
10-17 19:57:27.185: I/apjsua(920): 19:57:27.185    pjsua_acc.c  .....SIP registration failed, status=502 (gethostbyname() has returned error (PJ_ERESOLVE))
10-17 19:57:27.199: I/apjsua(920): 19:57:27.199    pjsua_acc.c  .....Scheduling re-registration retry for acc 2 in 6 seconds..
10-17 19:57:27.212: I/apjsua(920): 19:57:27.212      sip_reg.c  ..Error sending request, status=70018
10-17 19:57:27.226: I/apjsua(920): 19:57:27.226    pjsua_acc.c  ..Unable to create/send REGISTER: gethostbyname() has returned error (PJ_ERESOLVE) [status=70018]

Does any body know where I am getting wrong???
Or does anybody know any other way to use pjsip library for android???

A: You're in luck. I was sitting with this problem a few days ago and it just looked like a simple initialization error. You should really get to grips with debugging c code else you're gonna have a hard time understanding the pjsip stack. Anyway here's what you do:
Make the "setInput" method under /pjsip-apps/src/pjsua/main_android.c look like this:
void setInput(char *s)
{
  int i = 0;

  for (i = 0; i < sizeof(app_var.line); i++)
  {
      app_var.line[i]=NULL;
  }

  /* app_var.line[0] = 0; */

  if (strlen(s) < sizeof(app_var.line))
      strncpy(app_var.line, s, strlen(s));
  pj_sem_post(app_var.input_sem);
}

Looking at the code changes, you should be able to see that the app_var.line char variable was not being cleared properly. Now go to the /pjsip-apps/build/ folder and execute "make". Then go to the /pjsip-apps/src/apjsua/ folder and execute "make". Thereafter refresh your eclipse project and run. That should do the trick.


text:
Q: Binding A List of Images I was trying to bind a list of images (List) to a StackPanel, I tried to separate those Images by using <Separator> but sadly it's not working. Anyone has a clue why? (i'm kinda rookie on wpf..so sry)
My Code:
Code Behind:
            List<Image> v2 = new List<Image>();
        for (int i = 0; i < 10; i++)
        {
            Image v2image = new Image();
            v2image.BeginInit();

            v2image.Source = new BitmapImage(new Uri("http://static.lolskill.net/img/champions/64/xayah.png"));
            v2image.Width = 40;
            v2image.Height = 40;
            v2.Add(v2image);
        }

        BlueTeam.ItemsSource = v2;

The XAML:
<Window x:Class="FML.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:FML"
    mc:Ignorable="d"
    Title="MainWindow" Height="525.885" Width="809.974">
<Grid>
    <ItemsControl Grid.Column="0" x:Name="BlueTeam">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" >

                </StackPanel>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical" >
                    <Image Source="{Binding v2image.Source}"></Image>
                    <Separator Opacity="0" Height="20" Width="20"/>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

Ty for helping me :D
btw: The Images are very small aswell. they're not 40 Width\Height
edit:
This is how it supposed to work: http://imgur.com/a/bZbLf (It works when I'm using a class who has only Image)
this is how it works: http://imgur.com/a/uptlo

A: You should not have a List<Image>, but a List<ImageSource> instead:
var v2 = new List<ImageSource>();

for (int i = 0; i < 10; i++)
{
    v2.Add(new BitmapImage(
        new Uri("http://static.lolskill.net/img/champions/64/xayah.png")));
}

BlueTeam.ItemsSource = v2;

You would then declare an Image control with a fixed size in the ItemTemplate and bind it directly to the collection element, by Source="{Binding}":
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Image Source="{Binding}" Width="40" Height="40" Margin="10"/>
    </DataTemplate>
</ItemsControl.ItemTemplate>

Not sure what the Separator was supposed to do. In the example above, I've simply set the Image's Margin property.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Many Many-To-Many relationships Laravel I am trying to achieve the following:
I am trying to set up the database for an ecommerce like website and I have a Products table. Each product might have several SpecificationsHeader (which is something like the 'title' for each specificationsgroup), "under" this SpecificationsHeader could be many Specifications (those again act like 'titles', like 'Size'), for each one of those Specifications, a value should be assigned like 'XXL'. The main difficulty i face is getting the relationships correct since i would like to have all of them kinda reusable.
Example Product 1:
Product: iPhone
SpecificationHeader: 'CPU & RAM'
Specification(s): 'CPU speed' - SpecificationValue: '1.4GHz'
Specification(s): 'Ram size' - SpecificationValue: '2GB'
...
SpecificationHeader: 'Camera'
Specification(s): 'Camera Resolution' - SpecificationValue: '12MP'

Example Product 2: (might share some of the above values or might have completely different)
Product: Samsung
SpecificationHeader: 'CPU & RAM'
Specification(s): 'CPU speed' - SpecificationValue: '3GHz'
Specification(s): 'Ram size' - SpecificationValue: '4GB'
Specification(s): '4G' - SpecificationValue: 'Yes'
...
SpecificationHeader: 'Networking'
Specification(s): 'Something' - SpecificationValue: 'somevalue'

I experimented with several Pivot tables but i am obviously doing something wrong since the best i managed is getting the headers and specifications but not getting the values.
My latest approach was this:

But all of you who know what are doing will find it utterly stupid.
So,
the ideal solution would be:
Fetching the product brings with it a specification - specificationValue pair, grouped under the specificationheader.
Any help would be appreciated!

A: If I were you I would change only one thing, it's to set belongsTo relation between SpecificationValue and Specification
Like this:

But it produce some limits like if you have specifications memory and RAM you wont be able to use the same specification value 8 gb for each.
And there are some positive moments.
Example: User has added new specification to product size. You will show only needed values such as s, m, l, xl etc. without values from the other specifications like 3 Gb, Plastic, 4x4


text:
Q: Can FileMaker Server v11 support FileMaker v9 clients? See title.  Apparently FMServer v8 won't run on 10.6.x, so will upgrading the server component be sufficient or will we need to update all the v9 client licenses as well?

A: With the latest updates to both (FMServer 11v2 and FM 9v3), apparently the answer is 'yes'.

A: We're running FMServer 11v2 on our 10.6 server, with our FM 8.5 clients on 10.4.11 without problems.


text:
Q: Why Dirichlet's energy uses a **squared** norm? $E = \int_{\Omega}\left \| \nabla u(x)\right \|^2 dx$
So, Dirichlet's energy measures the integral of the squared norm of the gradient. Why squared norm? What would we get if we use just a norm? It's still going to be non-negative.
If I calculated a $u(x)$ that minimizes $E = \int_{\Omega}\left \| \nabla u(x)\right \| dx$ (not squared) would it be worse than Dirichlet? My goal is exactly what I specify: the gradient at any point should have minimum length.
Is the reason for the squared norm minimisation equivalent to the role of the square in the least squares fit? (here)

A: I think the square comes from physical modelling the bending energy.
But then, the square of a Hilbert space norm has several nice properties: it is uniformly convex and twice continuously differentiable with constant second derivative.
The Dirichlet problem
$$
\min \int_\Omega \frac12|\nabla u|^2 - uf \ dx
$$
is of course not equivalent to
$$
\min \int_\Omega |\nabla u| - uf \ dx.
$$
The latter problem is much harder to solve and analyze.
For instance, it is much more difficult to prove that the second problem has a solution with integrable gradient.
The minimizer of the Dirichlet energy satisfies
$$
-\Delta u = f,
$$
whereas the minimizer of the second problem satiesfies
$$
-\nabla\cdot\left( \frac{\nabla u}{\|u\|} \right) =f.
$$
To have a finite-dimensional analogue, consider the minimization of
$$
\sum_{i=1}^n \frac12|a_i|^2 - a^Tc
$$
and of
$$
\sum_{i=1}^n |b_i| - b^Tc.
$$
The first one has solution $a_i=c_i$, the second has a solution only if $|c_i|\le 1$ for all $i$ (which is then $b_i=c_i$).

A: I think in this form, the Dirichlet's energy is a strictly convex quadratic function and should have an UNIQUE minimum for reasonable boundary conditions .
This also holds for the least squared norm minimisation.


text:
Q: Unable to declare a latex environment I tried using this code
\newenvironment{bashcommands}{\ttfamily\color[RGB]{22,22,22}\begin{Verbatim}}{\end{Verbatim}}

But ended up spitting out an error. The error however was not related to this command, but related to another command that I put earlier. I have verified that command to be correct on this site.
This is the error I get in case anyone wants to look at it.
Runaway argument?
! File ended while scanning use of \FancyVerbGetLine.
<inserted text>
                \par
l.136 \include{chapters/chapter2}

Any help with solving this would be greatly appreciated.
Thank you

A: There is restrictions tu use of Verbatim environmnent, you should use \CustomVerbatimEnvironment available in the "fancyvrb" package to define your own verbatim environments.

A: First, I'd comment out all of your include statements and just test the usage of this environment in a simple context.  If you just keep hitting enter, or force it into quiet mode as it compiles, it will produce lots of errors, but it will give you a readable dvi or pdf (depending on your latex call).  Examining exactly what it spit out along with the log file should give you an idea of what is happening.


text:
Q: django How do I get the user id in the data base with a foreign key I'd like to get the user id in the db automatically when the user fill a form, but I don't know what I have to do. I'm working on that for all day long, I tried to do it by an hidden input but I'm not it's the solution.
This is my code:
 class ImputationForm(forms.Form):

    user = forms.ModelChoiceField(queryset=User.objects.all(),  widget=forms.HiddenInput())

    morning = forms.BooleanField( required=False)
    afternoon = forms.BooleanField(required=False)
    workpackage = forms.ModelChoiceField(
                                        queryset=Workpackage.objects.all()
                                        )

class ImputationFormModel(ModelForm):

    class Meta:
        model = Imputation

def imputation(request):

        if request.method == 'POST': # If the form has been submitted...
            form = ImputationForm(request.POST) # A form bound to the POST data
            f =   ImputationFormModel(request.POST)

            if form.is_valid(): # All validation rules pass
                user = request.user.id
                morning = form.cleaned_data['morning']
                afternoon = form.cleaned_data['afternoon']
                workpackage = form.cleaned_data['workpackage']
                f.save()

                return render_to_response( 'no/form.html', {'form' :  form, }, context_instance=RequestContext(request))
        else:
            form = ImputationForm()

        return render_to_response( 'no/form.html', {'form' :  form, }, context_instance=RequestContext(request))

A: Great question. Let's first start by identifying the purpose of various lines of code of your application and see if we can make sense of it. I see that you've got two forms right now which seems to reference the same kinds of data, which is a bit redundant. We'll want to avoid redundancy where possible, so let's start by perhaps cleaning up the code.
We can tell by the code you've shared that you're trying to:

*

*Allow a user to submit a form with data regarding "morning", "afternoon", and "workpackage".

*We're not checking whether or not you're editing an instance, so we can assume that upon successful form submission, a new Imputation record is created in the database with the data passed into it.

*You're asking for a hidden input of a user value on the client side, which binds the submitted user ID to the form for adding a relationship with the user to the newly saved Imputation record.
Generally, you never want to allow hidden variables regarding sensitive or personal data that can be associated with a user on the client side. It's considered a huge security risk. A user may edit the hidden field using Firebug (or other DOM editing tools) and bind the user ID to a different user than which is intended.
With that being said, let's have a gander at the code now:
class ImputationForm(ModelForm):

    class Meta:
        model = Imputation
        fields = [
            'morning',
            'afternoon',
            'workpackage'
        ]

    # assumed fields of morning, afternoon, workpackage

def imputation(request):

        if request.method == 'POST': # If the form has been submitted...

            form = ImputationForm(request.POST) # A form bound to the POST data

            if form.is_valid(): # All validation rules pass
                form.user = request.user
                form.save()

                return render_to_response( 'no/form.html', {'form' :  form, }, context_instance=RequestContext(request))
        else:
            form = ImputationForm()

        return render_to_response( 'no/form.html', {'form' :  form, }, context_instance=RequestContext(request))

With this code, we're no longer asking the user what his ID is on the form, and we're no longer even asking for it in the form altogether. We're allowing Django to determine what the current user ID is and pass it into the model right before saving the form. You'll want to make sure that the user field is set to null=True, blank=True on the model to avoid an exception from being raised.
I hope this helps answer your question.

A: I found it I'm really a newbie in django sorry for disturbing you and thank you very much for your help I would have not change my way of thinking on this issue without you!!!!! here is what I changed:
def imputation(request):

    if request.method == 'POST': # If the form has been submitted...

        form = ImputationForm(request.POST) # A form bound to the POST data

        if form.is_valid(): # All validation rules pass
            #print("%s" % form.user)
            print("%s" % form)
            new = form.save(commit=False) #here
            new.user = request.user #here
            new.save() #here

Thanks again ;)


text:
Q: Android search filter listview Ok I've tried several answers found here and I still couldn't do it, I think mainly because I don't know how the all these filter actually work. So I was wondering if you guys can help me with my code. I'm currently following the answer from here:
Custom Listview Adapter with filter Android
and I don't understand where the "mSeachableAdapter" in his MainActivity came from. Can someone help me fix my code? Also, please confirm whether I'm using the right method to filter listview.
MainActivity:
et.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
           //this one
 mSearchableAdapter.getFilter().filter(charSequence.toString());
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

CustomAdapter.java: (The filter adapter i follow from the link)
public class CustomAdapter extends BaseAdapter implements Filterable {

private List<String>originalData = null;
private List<String>filteredData = null;
private LayoutInflater mInflater;
private ItemFilter mFilter = new ItemFilter();

public CustomAdapter(Context context, List<String> data) {
    this.filteredData = data ;
    this.originalData = data ;
    mInflater = LayoutInflater.from(context);
}

public int getCount() {
    return filteredData.size();
}

public Object getItem(int position) {
    return filteredData.get(position);
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    // A ViewHolder keeps references to children views to avoid unnecessary calls
    // to findViewById() on each row.
    ViewHolder holder;

    // When convertView is not null, we can reuse it directly, there is no need
    // to reinflate it. We only inflate a new View when the convertView supplied
    // by ListView is null.
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.layout_team_list, null);

        // Creates a ViewHolder and store references to the two children views
        // we want to bind data to.
        holder = new ViewHolder();
        holder.text = (TextView) convertView.findViewById(R.id.textViewName);

        // Bind the data efficiently with the holder.

        convertView.setTag(holder);
    } else {
        // Get the ViewHolder back to get fast access to the TextView
        // and the ImageView.
        holder = (ViewHolder) convertView.getTag();
    }

    // If weren't re-ordering this you could rely on what you set last time
    holder.text.setText(filteredData.get(position));

    return convertView;
}

static class ViewHolder {
    TextView text;
}

public Filter getFilter() {
    return mFilter;
}

private class ItemFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        String filterString = constraint.toString().toLowerCase();

        FilterResults results = new FilterResults();

        final List<String> list = originalData;

        int count = list.size();
        final ArrayList<String> nlist = new ArrayList<String>(count);

        String filterableString ;

        for (int i = 0; i < count; i++) {
            filterableString = list.get(i);
            if (filterableString.toLowerCase().contains(filterString)) {
                nlist.add(filterableString);
            }
        }

        results.values = nlist;
        results.count = nlist.size();

        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        filteredData = (ArrayList<String>) results.values;
        notifyDataSetChanged();
    }

}
}

TeamList.java: (I'm just putting this here just in case it is needed)
public class TeamList extends ArrayAdapter<Team> {
private Activity context;
List<Team> teams;

public TeamList(Activity context, List<Team> teams) {
    super(context, R.layout.layout_team_list, teams);
    this.context = context;
    this.teams = teams;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View listViewItem = inflater.inflate(R.layout.layout_team_list, null, true);

    TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
    TextView textViewSport = (TextView) listViewItem.findViewById(R.id.textViewSport);
    TextView textViewDate = (TextView) listViewItem.findViewById(R.id.textViewDate);
    TextView textViewTime = (TextView) listViewItem.findViewById(R.id.textViewTime);
    final TextView textViewNumber = (TextView) listViewItem.findViewById(R.id.textViewNumber);
    ImageView icon = (ImageView) listViewItem.findViewById(R.id.icon);

    final Team team = teams.get(position);
    textViewName.setText(team.getTeamName());
    textViewSport.setText(team.getTeamSport());
    textViewDate.setText(team.getDate());
    textViewTime.setText(team.getTime());

    databaseMembers.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            long childCount = dataSnapshot.child("members").child(team.getTeamName()).child("teamMember").getChildrenCount();
            textViewNumber.setText(childCount + "/" + String.valueOf(team.getTeamNumber()));
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    String mDrawableName = team.getTeamSport();
    try{
        int ImgID = context.getResources().getIdentifier(mDrawableName, "drawable", context.getPackageName());
        Drawable drawable = context.getResources().getDrawable(ImgID);
        icon.setBackground(drawable);
    }
    catch (Exception e){
        e.printStackTrace();
    }

    return listViewItem;
}

}

Really hope someone can guide me through all these, if there's any insufficient information ,let me know. Really appreciate it.


text:
Q: Where does the "type.less" come from and why does it overwrite some of my styles? In my simple MVC application with only one page /Home/Index (for now) I noticed that some of my styles are being overwritten by a mysterious type.less:

Chrome says the file would come from
http://localhost:123/Content/less/type.less

but I couldn't find anything there.
The css files are also included in the right order so the main.css shouldn't actually be overriden:

The history of my actions:
I created a new MVC project in Visual Studio 2013 and I updated all references with the nugget-manager.
Then I and changed the following files:
(I list only changes related to css but I also added knockout and a few custom *.js files written by me)
BundleConfig.cs where I added jquery-ui.min.css:
bundles.Add(new StyleBundle("~/Content/css").Include(
          "~/Content/bootstrap.css",
          "~/Content/site.css",
          "~/Content/jquery-ui.min.css"));

and my main.css
bundles.Add(new StyleBundle("~/Content/Custom").Include(
          "~/Content/Custom/main.css"
));

_Layout.cshtml to render my new bundle and excluded the modernizr because I thought I might be the reason (it didn't help):
@Styles.Render("~/Content/css")
@Styles.Render("~/Content/Custom")
@*@Scripts.Render("~/Scripts/modernizr")*@

then I excluded another three lines there to make the tyle.less go away (but it didn't work either):
<body>
    <div class="container center">
        @RenderBody()
    </div>

    @*@Scripts.Render("~/Scripts/jquery")
    @Scripts.Render("~/Scripts/bootstrap")
    @RenderSection("scripts", required: false)*@
</body>

Index.cshtml contains only the title and html
@{
    ViewBag.Title = "Lorem ipsum";
}

apart of this I didn't change anything else.
I was able to find a reference to the type.less only in the bootstrap.css.map file which is apparently minified and a long line of different styles but the file type.less physically doesn't seem to exist anywhere. I don't understand why it wants to override my css. Do you know what might cause this and how to disable it or load it before my css so that it doesn't distroy anything?

A: I found out that some strange bootstrap that is installed

by default in new MVC5 projects

Bootstrap for ASP.NET MVC
caused all that trouble. Because I wasn't able to find how to prevent it from overwriting my styles I decided to uninstall it and finally I have my styles back.


text:
Q: Can't load images on canvas for my js game I am making a mahjong game in js and I have a problem loading images on canvas

*

*canvas
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 512;
//draw canvas
document.body.appendChild(canvas);

*Arrays
//Array with Tiles & set length to 144 which are the requested tiles
var tiles = new Array(2);//will be 144
//2D map array for showing the images coordinates
var map = [[69,50],[100,150]];//will be 144 coordinates

*my function update()
function update(){
    for(var i=0;i<tiles.length;i++){
            //make the tile object
    tiles[i] = new Object();
    tiles[i].id = i ;
    tiles[i].selected = false;
    //set the coordinates from map Array
    tiles[i].x=map[i][0];
    tiles[i].y=map[i][1];
    //tiles[i].ready=false;
                //These are for the image location works fine
    //convert i to String
    var sourceNumber = i.toString();
    //add .png to String
    var source = sourceNumber.concat(png);
    //add /image
    var source = dest.concat(source);
    tiles[i].img = new Image();
    tiles[i].img.onload = function(){
        //tiles[i].ready=true;
        ctx.drawImage(tiles[i].img,tiles[i].x,tiles[i].y,xdimension,ydimension);
    };
    tiles[i].img.src = source ;

    }
}

I runned it on each of my browser it won't load images , I debugged on chrome and it says on ctx.drawImage(...); -> Uncaught TypeError: Cannot read property 'img' of undefined(repeated many times), So I tried the tiles[I].ready and after load images but still has that error.Any suggestions on how should I implement the loading of the tile images

A: The first time ctx.drawImage is called, the value for i is 2. The problem is that the for-loop (for(var i=0;i<tiles.length;i++)) has finished executing before any of the images have loaded. Consequently, the value of i at the time the onload function is called is the value at which the loop ceased being run. The easiest way around this is to save the index (i) into the img element itself, so that you can retrieve it in the onload handler.
Here's a simple adaption of your code that seems to work just fine.
The important changes are:

*

*tiles[i].img.iVal = i;

*and the body of the onload handler.

I also:
(a) added an array to hold hard-coded image names for convenience, rather than dynamically creating them (I'd have had to name some images into the format that the code computes)
(b) removed the xdimension and ydimension vars from the drawImage call since I dont know what they are.
(c) changed .concat(png) to .concat(".png") since it was easier than declaring a variable called png that holds the string .png
Anyway, here's the sample-code I used:
<!DOCTYPE html>
<html>
<head>
<script>
window.addEventListener('load', onDocLoaded, false);

var canvas, ctx, tiles, map;

function onDocLoaded()
{
    canvas = newEl('canvas');
    ctx = canvas.getContext('2d');
    canvas.width = canvas.height = 512;
    document.body.appendChild(canvas);

    tiles = new Array(2);
    map = [[69,50],[100,150]];

    update();
}

var imgFileNames = ["img/girl.png", "img/redbaron.png"];

function update()
{
    for(var i=0;i<tiles.length;i++)
    {
        //make the tile object
        tiles[i] = new Object();
        tiles[i].id = i ;
        tiles[i].selected = false;
        //set the coordinates from map Array
        tiles[i].x=map[i][0];
        tiles[i].y=map[i][1];
        //tiles[i].ready=false;

        //These are for the image location works fine
        //convert i to String
//      var sourceNumber = i.toString();
        //add .png to String
//      var source = sourceNumber.concat(".png");
        //add /image
//      var source = dest.concat(source);
        tiles[i].img = new Image();
        tiles[i].img.iVal = i;
        tiles[i].img.onload =
        function()
        {
            var curI = this.iVal;
            ctx.drawImage(tiles[curI].img,tiles[curI].x,tiles[curI].y);
            // ctx.drawImage(this,tiles[curI].x,tiles[curI].y); //equiv to above line
        };
        tiles[i].img.src = imgFileNames[i];
    }
}
</script>
<style>
canvas
{
    border: solid 1px red;
}
</style>
</head>
<body>
</body>
</html>


text:
Q: button not sending info to database my button is not submiting and i do not know why, had some friend look over it and they dont see whats wrong.
the function is to change the date you have orderd a flight ticket
     print ("<from method='post' action=''>");
            print ("Ny utreisedato <input type='text' value='$utreisedato' name='utreisedato' id='utreisedato' >");
            print ("Ny returdato<input type='text' value='$retur' name='retur' id='retur' >");
            print ("<input type='submit' value='Endre dato' name='endredato' id='endredato'>");
            print ("</form>");
        }

@$endredato=$_POST["endredato"];
if ($endredato)
{

$utreisedato=$_POST["utreisedato"];
$retur=$_POST["retur"];

    if (!$utreisedato || !$retur)   {
    print ("Alle feltene må være fyllt ut!");
    }
            else {

        $sqlSetning = "UPDATE reiser SET utreisedato='$utreisedato', retur='$retur' WHERE tlf='$tlf';";
        mysqli_query($db,$sqlSetning) or die ("kunne ikke endre informasjonen");

        print ("Reisen med nummer $tlf er endret. Last inn siden på nytt for å se forandringen i tabellen.");
    }
    }

?>

A: I am sure that problem because of you type wrong for form tag.
for this line  print ("<from method='post' action=''>"); you should write  print ("<form method='post' action=''>");.
Hopefully it will be success.


text:
Q: How to make sure PHP instance runs in background? I have a ton of rows in MySQL. I'm going to perform a ping on an ip in each of these rows, so I'd like to split the load. I've made a script that runs a new process for every 100 row in the database. The problem is that the parent script seems to wait for each of the child scripts to finish before starting the next one, which voids the entire purpose.
This is the code of the important part of the parent script
for($i = 0; $i < $children_num; $i++)
{
    $start = $bn["dots_pr_child"] * $i;

    exec("php pingrange.php $i $start $bn[dots_pr_child]");
}

It's worth mentioning that each of these children processes run exec("ping") once per MySQL row. I'm thinking that's a part of the problem.
I'll post more information and code on request.
Is there a way to force the PHP instance to run in the background, and for the foreground to continue? Preferably the parent script should take 0.0001 sek and print "Done". Currently it runs for 120 seconds.
Thanks for any and all help

Edit: I've tried to add a & after the process. One would think that'd make the exec function return instantly, but nope.

Edit: Tried exec("php pingrange.php $i $start $bn[dots_pr_child] 2>&1 &"); without success

Edit: Tried exec("nohup php pingrange.php $i $start $bn[dots_pr_child] &"); without success

A: exec("php pingrange.php $i $start $bn[dots_pr_child] > /dev/null 2>/dev/null & ");

should do the work in background.

A: Try nohup and the ampersand:
exec("nohup php pingrange.php $i $start $bn[dots_pr_child] &");

The Wikipedia article on nohup gives a pretty good description of what it does.

A: While it might be overkill for this specific task, consider Gearman, a message / work queue designed for exactly what you're doing: farming out tasks to workers.  It has comprehensive PHP support.
If you want to pass on Gearman for now, take a peek at proc_open instead of exec.  It's a bit more complex, but it gives you a higher degree of control that might work better for you.

A: <?php
passthru("/path/script >> /path/to/log_file.log 2>&1 &");
?>

This should work since none of default PHP streams are used.

A: Just append > /dev/null 2>&1 & to your command, works for me.


text:
Q: UIButton smooth touch effect I am trying to implement UIButton's smooth touch effect like we use calculator in our iPhone devices. However i have tried some code in Objective c and Swift as well but found the same result which is not up to the desire.
Tried code:
@IBAction func someAction(sender: UIButton){
    button.setBackgroundColor(UIColor.blackColor(), forState: UIControlState.Highlighted)
}

// using extension
extension UIButton {
    func setBackgroundColor(color: UIColor, forState: UIControlState) {
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
        CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        self.setBackgroundImage(colorImage, forState: forState)
    }}

Explanation: the above code works fine as i need but the applied effect is not so smooth. In fact when i touch button it takes a nano second to apply background image on it and when i release touch the background image disappear suddenly.
I also tried this in Objective c using TouchUpInside and TouchDown event but result found same.
Thanks for your time.

A: Complete solution: using CABasicAnimation and adding a layer over button.
@IBAction func someAction(sender: UIButton){
   let colorAnimation = CABasicAnimation(keyPath: "backgroundColor")
   colorAnimation.fromValue = UIColor.redColor().CGColor
   colorAnimation.duration = 1  // animation duration
   // colorAnimation.autoreverses = true // optional in my case
   // colorAnimation.repeatCount = FLT_MAX // optional in my case
   sender.layer.addAnimation(colorAnimation, forKey: "ColorPulse")
}

Reference: as user iOS_devloper comment.

A: Create subclass of UIButton and override highlighted property:
override var highlighted: Bool {
        get {
            return super.highlighted
        }
        set {
            if newValue {
                backgroundColor = UIColor.blackColor()
            }
            else {
                backgroundColor = UIColor.whiteColor()
            }
            super.highlighted = newValue
        }
    }

A: Assign property for your button and put this code in viewDidLoad.
yourButton.setBackgroundColor(UIColor.blackColor(), forState: UIControlState.Highlighted)

The problem was you set it only when user press. This code takes time as it uses CoreGraphics. You can immediately set the background img for highlighted state in viewdidload and it will stay there and be called immediately as u tap the button.


text:
Q: Mousemove issue [jQuery] I've just created #element and #box which detect if it's out of the viewport. If so, it should go above the cursor but here's my issue. When #box is out of the viewport it starts acting weird by flashing over and over. Hope you guys can help me. Cheers.
var box = $("#box");
var element = $("#element");
var PAGEX;
var PAGEY;
var elementTop;
var elementBottom;
var windowHeight;

element.bind({
mousemove: function (e) {
box.show();

PAGEX = e.pageX;
PAGEY = e.pageY;

elementTop = box.offset().top;
elementBottom = elementTop + box.outerHeight();
windowHeight = $(window).height();

if(elementBottom > windowHeight)
{
  box.css({
    top: PAGEY - 65,
    left: PAGEX + 15
  })
}
else
{
  box.css({
    top: PAGEY + 15,
    left: PAGEX + 15
  })
}

},
mouseleave: function () {
box.hide();
}
})

JSFiddle

A: The problem here is that you are doing your out-of-viewport check against the actual box location, rather than the location based on the mousemove.  So, this works the first time the box would move out of the viewport - you adjust it back inside.  But, the next time the mouse moves, your box is safely inside the viewport.  So your check adjusts it based on the mouse position, and it gets put outside the viewport.  The next time the mouse moves, the calculation works, and it gets adjusted back inside, and so on.
The fix is to change this:
if(elementBottom > windowHeight)

To this:
if(PAGEY + 15 + box.outerHeight() > windowHeight)

So that it is always calculating the out-of-viewport based on where the target location would be, and not where its current location is.


text:
Q: How to store a Dataframe in a Dictionary I have a Dataframe that extends column-wise by using a for-loop.
now I want to store certain "stages" of the evolving DF somehow and I thought it would be the best to use a Dictionary.
to give you a picture:
df_dict={}
for i in range(1,13):
    df=pd.read_csv('./test.csv').iloc[:,0:i*4-1]

so I want to store this as "first stage" of the df:
col1     col2     col3     col4
  1        3        5        7
  2        4        6        8

in the "second stage":
col1     col2     col3     col4     col5     col6     col7     col8
  1        3        5        7        9        11       13       15
  2        4        6        8        10       12       14       16

3rd stage contains 12 cols:
col1     col2     col3     col4     col5     col6     col7     col8     ...
  1        3        5        7        9        11       13       15     ...
  2        4        6        8        10       12       14       16     ...

Ongoing till the 12th stage contains 48 cols.
So in general I want to store in the Dict these stages where every new stage has 4 more columns.
And I need to be able to use these different Dataframes seperatly later.
I know that
df_dict.update({i, df})

doesn't work since DFs are mutable, but I did not manage to find a way to work around it.
I'm new to Python so please by gentle with me.
Cheers!
EDIT:
I wasn't searching the Idea of how to get variable variables since I allready mentioned that I want to use a Dict, but I was looking for a way of storing my Dataframe in a Dict.

A: I believe you need to assign each DataFrame in loop:
df_dict={}
for i in range(1,13):
    df=pd.read_csv('./test.csv').iloc[:,0:i*4-1]
    df_dict[i] = df

Another solution is use dictionary comprehension:
df_dict = {i: pd.read_csv('./test.csv').iloc[:,0:i*4-1] for i in range(1,13)}


text:
Q: How to create image on mouse click event using html5 and javascript I an newbie in html5, I want to create an a dot like image on click event. I try to use context but unfortunately not working. The code that i am using is
 document.addEventListener("DOMContentLoaded", init, false);

      function init()
      {
        var canvas = document.getElementById("options");
        canvas.addEventListener("mousedown", getPosition, false);
      }

      function getPosition(event)
      {
        var x = new Number();
        var y = new Number();
        var canvas = document.getElementById("options");

        if (event.x != undefined && event.y != undefined)
        {
          x = event.x;
          y = event.y;
        }
        else // Firefox method to get the position
        {
          x = event.clientX + document.body.scrollLeft +
              document.documentElement.scrollLeft;
          y = event.clientY + document.body.scrollTop +
              document.documentElement.scrollTop;
        }

        x -= canvas.offsetLeft;
        y -= canvas.offsetTop;

        alert("x: " + x + "  y: " + y);
           var b_canvas = document.getElementById("b");
    var b_context = b_canvas.getContext("2d");
    b_context.fillRect(50, 25, 150, 100);

Please suggest where I am doing mistake. Give your suggestions

A: Not sure if that's the problem, but to draw a dot on canvas, you can start a path, draw a completely closed arc (from 0 rad to 2pi rad) and fill that:
     b_context.beginPath();
     b_context.arc(x, y, 5 , 0,  2 * Math.PI,true);
     b_context.fillStyle = "blue";
     b_context.fill();

Further it is important to set width and height directly on canvas and not in css to prevent distortion. (just found that out myself ;) )
Complete example fiddle: http://jsfiddle.net/wHsMJ/  (click inside the rectangle on the right to test)


text:
Q: asp.net C# sql query dependant on session data I have a Session, which is list int, and I need to make a query that will take from a database only those rows that have the PK value that exists in Session.
I was thinking of doing it with the IN function, or making a new datatable with 1 collumn and values from the Session and doing a double join, probably left...
I just dont know how to make a table from a list.
What I have so far:
String ConnString = "Data Source=BRACO-PC\SQL1;Initial Catalog=DiplomskiSQL1SQL;Integrated Security=True";
SqlConnection Conn = new SqlConnection(ConnString);
Conn.Open();
DataTable ukosarici = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("Select Proizvodi.ime, TipProizvoda.tip, Proizvodi.dimenzije, Proizvodi.cijena from Proizvod LEFT JOIN TipProizvoda On Proizvod.tip=TipProizvoda.id_t WHERE Proizvod.id_p IN ", Conn);
SqlCommandBuilder cmd = new SqlCommandBuilder(da);
da.Fill(ukosarici);
GridView1.DataSource = ukosarici;
GridView1.DataBind();
Conn.Close();

A: Create a temporary table or table variable, insert the ints into it using INSERT or BULK INSERT, do a join in the SQL query then drop the temp table or table variable.

A: There are many ways you could do this, but one of my preferred methods is to serialize the list to a CSV, e.g. '1,3,5,33'.  I then use a custom SQL Table function to de-serialize the list and filter in the database:
SELECT * FROM mytable t
JOIN dbo.ufn_CSVtoTextList('1,3,5,33' , ',') csv
ON csv.[Entry] = t.Id

The ufn_CSVtoTextList function CREATE script is below:
CREATE FUNCTION [dbo].[ufn_CSVToTextlist] ( @StringInput nVARCHAR(max) ,@SepChar nchar(1) = ',')
RETURNS @OutputTable TABLE ( [Entry] nVarchar(255), [index] int identity (0,1) )
AS
BEGIN

    DECLARE @Entry   nVarChar(255)

    WHILE LEN(@StringInput) > 0
    BEGIN
        SET @Entry      = LEFT(@StringInput,
                                ISNULL(NULLIF(CHARINDEX(@SepChar, @StringInput) - 1, -1),
                                LEN(@StringInput)))
        SET @StringInput = SUBSTRING(@StringInput,
                                     ISNULL(NULLIF(CHARINDEX(@SepChar, @StringInput), 0),
                                     LEN(@StringInput)) + 1, LEN(@StringInput))

        INSERT INTO @OutputTable ( [Entry] )
        VALUES ( @Entry )
    END

    RETURN
END

A: Try by changing your SqlDataAdapter Call as follows
 List<int> list ; // Assign with your session int list values
            List<string> l2 = list.ConvertAll<string>(delegate(int i) { return i.ToString(); });
            string query = "Select Proizvodi.ime, TipProizvoda.tip, Proizvodi.dimenzije, Proizvodi.cijena from Proizvod LEFT JOIN TipProizvoda On Proizvod.tip=TipProizvoda.id_t WHERE Proizvod.id_p IN (";
            query = query + string.Join(",", l2.ToArray()) + ")";
            SqlDataAdapter da = new SqlDataAdapter(query, Conn);


text:
Q: Selenium and PhantomJS : webpage thinks Javascript is disabled I am running a small script that is mostly checking small things on a website. Today I've come across a really interesting situation I've never seen before, which is the webpage i'm going to thinks Javascript is disabled. This is only happening in PhantomJS, but works fine in Chromedriver. I've even tried changing the driver's headers to ones similiar to Chrome, but still no luck. Is there anyway to get this page to work in PhantomJS without having to use ChromeDriver and PyVirtualDisplay? i'm running the code on Ubuntu Server and would rather not use the extra system resources of having to use them. I've also tried running driver.save_screenshot(), but it's returning a blank image since there is no content of the page being displayed.
simple code to reproduce the problem:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

service_args = [
    '--ignore-ssl-errors=true',
    '--ssl-protocol=any'
]

capabilities = dict(DesiredCapabilities.PHANTOMJS)
capabilities['phantomjs.page.settings.userAgent'] = ('Mozilla/5.0 (X11; Linux x86_64) '
                                                     'AppleWebKit/537.36 (KHTML, like Gecko) '
                                                     'Chrome/60.0.3112.113 Safari/537.36)')

driver = webdriver.PhantomJS(desired_capabilities=capabilities, service_args=service_args)
driver.get(EDIT: URL REMOVED)
print driver.page_source

html response:
<!DOCTYPE html><html class=" no-blobworkers adownload applicationcache no-audiodata no-webaudio no-audio no-lowbattery no-batteryapi no-battery-api blobconstructor blob-constructor canvas todataurljpeg todataurlpng no-todataurlwebp canvastext contenteditable no-contentsecuritypolicy no-contextmenu cookies cors cssanimations backgroundcliptext bgpositionshorthand bgpositionxy bgrepeatround bgrepeatspace backgroundsize bgsizecover borderimage borderradius boxshadow boxsizing csscalc checked csscolumns cubicbezierrange displayrunin display-runin displaytable display-table ellipsis cssfilters flexbox flexboxlegacy no-flexboxtweener fontface generatedcontent cssgradients hsla lastchild cssmask mediaqueries multiplebgs no-objectfit no-object-fit opacity no-overflowscrolling csspointerevents csspositionsticky no-csspseudoanimations csstransitions no-csspseudotransitions cssreflections regions cssremunit cssresize rgba cssscrollbar shapes siblinggeneral subpixelfont no-supports textshadow csstransforms csstransforms3d userselect cssvhunit cssvmaxunit cssvminunit cssvwunit no-wrapflow no-customprotocolhandler no-dart dataview classlist no-createelementattrs no-createelement-attrs dataset no-microdata draganddrop datalistelem details outputelem progressbar meter ruby no-time no-texttrackapi no-track no-emoji no-strictmode no-contains no-devicemotion no-deviceorientation filereader no-filesystem fileinput formattribute no-localizednumber placeholder no-speechinput no-formvalidation fullscreen gamepads no-geolocation hashchange history no-ie8compat sandbox seamless srcdoc indexeddb json olreversed no-mathml no-lowbandwidth eventsource xhr2 xhrresponsetypearraybuffer xhrresponsetypeblob xhrresponsetypedocument no-xhrresponsetypejson xhrresponsetypetext xhrresponsetype notification pagevisibility performance no-pointerevents no-pointerlock postmessage no-quotamanagement requestanimationframe raf scriptasync scriptdefer localstorage sessionstorage websqldatabase no-stylescoped svgclippaths svgfilters inlinesvg smil svg touchevents typedarrays unicode no-userdata no-vibrate no-video no-webintents no-webgl no-getusermedia no-peerconnection websocketsbinary websockets no-framed sharedworkers webworkers no-dataworkers no-exiforientation no-apng no-webplossless no-webp svgasimg datauri" style="">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="CacheControl" content="no-cache">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="shortcut icon" href="data:;base64,iVBORw0KGgo=">

Please enable JavaScript to view the page content.

EDIT: Yes, I understand that PhantomJS is old, but it's what we have to use. My question is about getting something to work in PhantomJS, not about what alternatives are available. All of our servers run Ubuntu Server, including all server images, so we have to use headless browsing. Virtual Displays, such as PyVirtualDisplay and any other Xvfb routing method are too heavy on system resources. All of our codebase uses PhantomJS so as of right now I have to use it. As well, we use proxies with username and password authentication which Chrome has not supported, so the Headless Chrome option is out.
As well, i just tested this code with Headless Chrome and it also is not working.
python code:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(executable_path='/path/to/chromedriver', chrome_options=chrome_options)
driver.get("https://www.EDIT-REMOVED.com")
print driver.page_source
driver.quit()

html response:


text:
Q: OpenCV - face_cascade = new cv.CascadeClassifier(classifier) I got this error message when execute node script
/Users/ZERO/node_modules/opencv/lib/opencv.js:22
    face_cascade = new cv.CascadeClassifier(classifier);
                   ^

TypeError: Error loading file
    at TypeError (native)
    at Matrix.detectObject (/Users/ZERO/node_modules/opencv/lib/opencv.js:22:20)
    at /Users/ZERO/RM1/index.js:14:8
    at /Users/ZERO/RM1/index.js:13:6
    at Array.forEach (native)
    at Object.<anonymous> (/Users/ZERO/RM1/index.js:12:12)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)

My script
var cv = require('opencv');

var color       = [0, 255, 0];
var thickness   = 2;
var cascadeFile = '/Users/ZERO/RM1/classifier/cascade.xml';

var inputFiles = [
  '/Users/ZERO/RM1/recognize/recognize_this_1.jpg',
  '/Users/ZERO/RM1/recognize/recognize_this_2.jpg',
  '/Users/ZERO/RM1/recognize/recognize_this_3.jpg',
  '/Users/ZERO/RM1/recognize/recognize_this_4.jpg',
  '/Users/ZERO/RM1/recognize/recognize_this_5.jpg',
  '/Users/ZERO/RM1/recognize/recognize_this_6.jpg'
];

inputFiles.forEach(function(fileName) {
  cv.readImage(fileName, function(err, im) {
    im.detectObject(cascadeFile, {neighbors: 2, scale: 2}, function(err, objects) {
      console.log(objects);
      for(var k = 0; k < objects.length; k++) {
        var object = objects[k];
        im.rectangle(
          [object.x, object.y],
          [object.x + object.width, object.y + object.height],
          color,
          2
        );
      }
      im.save(fileName.replace(/\.jpg/, 'processed.jpg'));
    });
  });
});


text:
Q: Inline css for several elements I'm trying to use inline css because I have some parameters I need to pass which I can't do it in css files. Everything is fine if I set the style for one element, for example :
<div class="example" style="background-color:#**<?=$model->color?>**">

But because there are lots of elements need that color parameter, can I put all of them in one style?
If in css, I do it like this :
.example h1, h2, li, p a {color: red};

I'm trying this in inline css but it doesn't work :
<div class="example" style="h1, h2, li, p a color:#**<?=$model->theme_color;?>**">

Does anyone know how to do this? And may I do it inline?

A: What you probably need is internal CSS (instead of inline CSS) - that's where you include your CSS within style tags. So something like

A: This should do it
<?php
echo "";
?>

Another way:

A: Why not apply classes instead of internal/inline CSS? Something like
<div class="color-<?=$model->color?>">

CSS
.color-red {color:red;}

A: Try this way:
<?php
echo "

";
?>


text:
Q: I have a json file and I want to add new field to it I have a json file
[{
    "sport": "football",
},
{
    "sport": "swimming",
}]

I want to add a new field to each document a uniqueID field which have this form A-11 and increase the number by one for each object
I have tried this in Node
const fs = require('fs');
const filenameAppo = './app.json';
const requireFile = require(filenameAppo);

requireFile.uniqueID = 'A-11';
const test = fs.writeFile(filenameAppo,JSON.stringify(requireFile), function(err) {
    if (err) return console.log(err);

});

But it didn't work as expected so what is my error in that or if there is another way I can do it

A: I believe the best way to approach this is to create an object wrapper for the file array data, then add the uniqueID property, something like this:
const fs = require('fs');
const filenameAppo = './app.json';
const requireFile = require(filenameAppo);

const inputData = requireFile.data || requireFile;
let id = 11;
const output = {
    data: inputData.map(row => {
        row.uniqueID = "A-" + (id++);
        return row;
    })
}

const outputString = JSON.stringify(output , null, 4);
console.log(`Writing ${outputString.length} bytes to file: ${filenameAppo}...`);
fs.writeFile(filenameAppo, JSON.stringify(output , null, 4), function(err) {
    if (err) {
        console.error(`An error occurred writing output file: ${filenameAppo}:`, err);
    } else {
        console.log(`Successfully wrote ${outputString.length} bytes to file: ${filenameAppo}.`)
    }
});

You app.json file will then look like so:
{
    "data": [
        {
            "sport": "football",
            "uniqueID": "A-11"
        },
        {
            "sport": "swimming",
            "uniqueID": "A-12"
        }
    ]
}


text:
Q: Using "Script Table As CREATE To ..." option in SQL Server 2008 R2 SSMS I have come up against a very strange problem when using the 'Script Table As CREATE To' option using SQL Server 2008 R2 SSMS.
In my original Northwind database I have this check constraint:
ALTER TABLE [dbo].[Employees]  WITH NOCHECK

   ADD  CONSTRAINT [CK_Birthdate]
        CHECK  (([BirthDate] < getdate()))
GO

Now, when I run this against a Northwind_Test database I get this:
ALTER TABLE [dbo].[Employees]
      WITH NOCHECK
        ADD  CONSTRAINT [CK_Birthdate]
             CHECK  (([BirthDate]<getdate()))
GO

The difference is the spacing has been removed from the CHECK text.
I need the spacing to remain intact when running scripts from within SSMS.  Is there any SET statement I can use to preserve this spacing and any other formatting?  The reason for this is I am writing a database compare utility and need the formatting to remain intact otherwise the utility will keep saying the database schema is different.


text:
Q: time series minute data - how to select data for given interval I have timeseries data like this:
  ticker        close
created_at
2020-06-10 17:02:00+00:00   TSLA  1014.354980
2020-06-10 18:30:00+00:00   TSLA  1017.419312
2020-06-10 18:31:00+00:00   TSLA  1018.344971
2020-06-10 18:32:00+00:00   TSLA  1018.340027
2020-06-10 18:33:00+00:00   TSLA  1017.919983
2020-06-10 18:34:00+00:00   TSLA  1015.210022
2020-06-10 18:35:00+00:00   TSLA  1015.772583
2020-06-10 18:36:00+00:00   TSLA  1016.775024
2020-06-10 18:37:00+00:00   TSLA  1015.679993
2020-06-10 18:38:00+00:00   TSLA  1014.080017
2020-06-10 18:39:00+00:00   TSLA  1013.000000
2020-06-10 18:40:00+00:00   TSLA  1008.880005
2020-06-10 18:41:00+00:00   TSLA  1011.369995
2020-06-10 18:42:00+00:00   TSLA  1012.400024
2020-06-10 18:43:00+00:00   TSLA  1013.000000
2020-06-10 18:44:00+00:00   TSLA  1014.459412
2020-06-10 18:45:00+00:00   TSLA  1014.070007
2020-06-10 18:46:00+00:00   TSLA  1015.575012
2020-06-10 18:47:00+00:00   TSLA  1014.419983
......................

I want to pick the close price at every 5 minute interval for example at 18:30,18:35,18:40 etc. It was suggested to use resample, however I don't wish to resample the data per se. All I want to do is get the close price at every 5 minute interval, whats the best way of going about doing that
Thanks

A: The following df,
| date                | tick   |   price |
|:--------------------|:-------|--------:|
| 2020-06-10 18:30:00 | TSLA   | 1017.42 |
| 2020-06-10 18:31:00 | TSLA   | 1018.34 |
| 2020-06-10 18:32:00 | TSLA   | 1018.34 |
| 2020-06-10 18:33:00 | TSLA   | 1017.92 |
| 2020-06-10 18:34:00 | TSLA   | 1015.21 |
| 2020-06-10 18:35:00 | TSLA   | 1015.77 |
| 2020-06-10 18:36:00 | TSLA   | 1016.78 |
| 2020-06-10 18:37:00 | TSLA   | 1015.68 |
| 2020-06-10 18:38:00 | TSLA   | 1014.08 |
| 2020-06-10 18:39:00 | TSLA   | 1013    |
| 2020-06-10 18:40:00 | TSLA   | 1008.88 |
| 2020-06-10 18:41:00 | TSLA   | 1011.37 |
| 2020-06-10 18:42:00 | TSLA   | 1012.4  |
| 2020-06-10 18:43:00 | TSLA   | 1013    |
| 2020-06-10 18:44:00 | TSLA   | 1014.46 |
| 2020-06-10 18:45:00 | TSLA   | 1014.07 |
| 2020-06-10 18:46:00 | TSLA   | 1015.58 |
| 2020-06-10 18:47:00 | TSLA   | 1014.42 |

can be shown every 5min with iloc:
df.iloc[::5]

which results in:
| date                | tick   |   price |
|:--------------------|:-------|--------:|
| 2020-06-10 18:30:00 | TSLA   | 1017.42 |
| 2020-06-10 18:35:00 | TSLA   | 1015.77 |
| 2020-06-10 18:40:00 | TSLA   | 1008.88 |
| 2020-06-10 18:45:00 | TSLA   | 1014.07 |

if the data has a new entry every minute, otherwise you can adapt the stride value of 5.

A: If you just want to return the data at 5 min intervals, you can just get the minutes that are multiples of 5:
df['created_at'] = pd.to_datetime(df['created_at'])
df = df[df['created_at'].dt.strftime('%M').astype(int) % 5 ==0]
print(df)

                  created_at ticker        close
1  2020-06-10 18:30:00+00:00   TSLA  1017.419312
6  2020-06-10 18:35:00+00:00   TSLA  1015.772583
11 2020-06-10 18:40:00+00:00   TSLA  1008.880005
16 2020-06-10 18:45:00+00:00   TSLA  1014.070007


text:
Q: How to fill the matrix with values from other matrix matching rows and columns? I'm trying to make a new matrix using values from other matrix with R. I'm trying to match the names of rows and columns while importing the values. This is what what trying to do:
I have two matrices;
     X1  X2  X3  X4
 X1   0   9   8   0
 X2   1   2   3   5
 X4   6   1   2   4

     X1  X2  X3  X4
 X1  NA  NA  NA  NA
 X2  NA  NA  NA  NA
 X3  NA  NA  NA  NA
 X4  NA  NA  NA  NA

I want to do
     X1  X2  X3  X4
 X1   0   9   8   0
 X2   1   2   3   5
 X3  NA  NA  NA  NA
 X4   6   1   2   4

These matrices are just simple examples of my dataset, my real data is more complicated.
Many thanks,

A: checking for rownames and colnames matches in both matrices will prevent subscript out of bounds error. See below.
mat2[rownames(mat2) %in% rownames(mat1),
     colnames(mat2) %in% colnames(mat1)] <- mat1[rownames(mat1) %in% rownames(mat2),
                                                 colnames(mat1) %in% colnames(mat2)]
mat2
#    X1 X2 X3 X4
# X1  0  9  8  0
# X2  1  2  3  5
# X3 NA NA NA NA
# X4  6  1  2  4

Data:
mat1 <- read.table(text = '    X1  X2  X3  X4
 X1   0   9   8   0
                   X2   1   2   3   5
                   X4   6   1   2   4', header = TRUE)

mat1 <- as.matrix(mat1)
mat2 <- matrix(NA, nrow = 4, ncol = 4, dimnames = list(paste0("X", 1:4),
                                                       paste0("X", 1:4)))

A: If I understood your question you can do this:
# Building your matrices
mat1 <- matrix(runif(12), nrow = 3, ncol = 4)
mat2 <- matrix(NA, nrow = 4, ncol = 4)
labs <- paste0("x", 1:4)
colnames(mat1) <- colnames(mat2) <- labs
rownames(mat2) <- labs
rownames(mat1) <- labs[c(1:2, 4)]

#
rows <- sort(unique(c(rownames(mat1), rownames(mat2))))
result <- matrix(NA, nrow = length(rows), ncol = ncol(mat1))
result[match(rownames(mat1), rows), ] <- mat1


text:
Q: I have two circuits, how will the second one interact with the first one? Suppose we have 2 circuits :
One is this:

simulate this circuit – Schematic created using CircuitLab
We call that a circuit.
And the second is this :

simulate this circuit
How will the 2nd circuit react to the 1st circuit? Here's what I think it should happen.
Since the current in the 1st is alternating , the magnetic field created by the coil will also constantly changing direction and strength ( direction every 2/f sc and strength constantly)
When the magnetic field of the 1st circuit hits the wire of the 2nd circuit an alternating current will be induced ( due to the costant change of strength and direction of magnetic field in the 1st circuit).
The natural frequency of the tuning circuit(L1,C1) will not be the same with the frequency of induced alternating current cause big reactance -> big impendance -> low average current.
Since we have a half wave rectifier connected parralel to a diode every 2/f sc the mic will 'beep' in a periodic fashion.
Is that correct?

A: I decided to take a look at what those circuits will do when built and driven as shown.
Since both are thrown together from random components, I tossed them both together with whatever random components I found in my junk box.

*

*Inductors: two rolls of wire each of about 450µH inductance - more or less.  I measured one at about 466µH.  The other is missing a couple of meters so its inductance will be lower.

*Capacitor: I pulled a couple of 0.04µF capacitors out of a scrap PCB and soldered them in parallel to make a 0.08µF capacitor.

*Diode:  some small signal diode from the same PCB the capacitors came from.

*Microphone:  you'd normally use a speaker to hear things.  I used an earphone.  I have no idea of the impedance.

*Signal generator: I slapped together an audio signal generator using a pair of powered speakers and purr data running on my PC to do the actual sound generation.  The speakers have an amplified output that can deliver a couple of watts of power.

The circuits look like this:

simulate this circuit – Schematic created using CircuitLab
"Thing 1" is just a coil connected to my signal generator.  I left out the resistor because that would only reduce the power to the coil - and the coil is going to need all the power it can get.
"Thing 2" is the OP's "circuit 2" modified to reflect what I really used.
I made a few measurements at the indicated spots, using the respective ground for each circuit.
This is at the "TX" flag of "thing 1:"

No surprises there.  That's a 1000 hertz signal at the maximum amplitude my speaker amplifier can produce without obvious distortion.
This is the the voltage at the spot marked "RX" in "thing 2:"

Again no great surprises.  That's a 1kHz signal, and at a lower amplitude than measured on "thing 1."
Now to the voltage at "RX diode," which is the part the question actually asked about:

This is not what the question stated should happen.  It is, however, not terribly surprising.  The earphone pretty much bypasses the diode, and we end up with a slightly distorted version of the 1kHz signal at a slightly lower amplitude.  The diode might as well not even be there - or the capacitor, either for that matter.
In the end, the OP's circuit 2 could be replaced by this circuit and perform better:

simulate this circuit
That is a simple inductive transmitter with a simple inductive receiver.  It works well, if you can afford to throw piles of power at it.  With the two coils literally laying on each other, the received signal is loud and clear - with a couple of watts driving the transmit coil.
If I move the coils just 20 centimeters apart, the signal becomes almost inaudible.
An AM receiver contains almost the same parts, but the arrangement of the circuit and the exact values of the components makes a world of difference.
It would be better to start from a known circuit for a simple AM receiver than randomly string parts together in hopes of hitting on a functional combination.


text:
Q: Mongo to convert timestamp to numeric value to use with $divide I want to use timestamp value as an integer value i.e. the total number of seconds/milliseconds (the converted timestamp value into seconds/milliseconds) and use it with $divide accumulator/operator
I tried that as this code but get error

pymongo.errors.OperationFailure: $divide only supports numeric types, not date and int

I google for convert datetime to int though get little helpful result
So how can we get around it i.e. to get $divide work with timestamp?


text:
Q: Accessing real and imaginary parts of cusp::complex vector I need to access the real and imaginary parts of a cusp::complex type vector, for the purpose of sending it to a matlab variable through, mex.
How do I access the real and imaginary parts separately of a vector of type.
    cusp::array1d<cusp::complex<double>,cusp::host_memory> x;

I am at the moment making two std::vectors and looping through it.
    std::vector<double> xreal(n);
    std::vector<double> ximag(n);
    for(int i=0;i<n;i++){
        xreal[n]=x[i].real();
        ximag[n]=x[i].imag();
    }

And then transfering it to a matlab variable using thrust.
    mxArray *T = mxCreateDoubleMatrix(n, 1, mxCOMPLEX);
    double *tp_real  = mxGetPr(T);
    double *tp_imag  = mxGetPi(T)
    thrust::copy(xreal.begin(), xreal.end(), tp_real);
    thrust::copy(ximag.begin(), ximag.end(), tp_imag);
    plhs[0] = T;

I want to know how I can use thrust for accessing the real and imaginary parts of the complex array
    cusp::array1d<cusp::complex<double>,cusp::host_memory> x;

to transfer it through the corresponding real and imaginary pointers of the mxArray. directly, so that I can avoid the loop.

A: Ok so I have managed to solve it using functors, I made two functors (not sure if this is called a functor, but anyways)
    __host__ double realpart(cusp::complex<double> val){
        return val.real();
    }

    __host__  double imagpart(cusp::complex<double> val){
        return val.imag();
    }

And used thrust::transform
    cusp::array1d<double,cusp::host_memory>xreal(n);
    cusp::array1d<double,cusp::host_memory>ximag(n);
    thrust::transform(x.begin(),x.end(),xreal.begin(),realpart);
    thrust::transform(x.begin(),x.end(),ximag.begin(),imagpart);

It worked, and then I could fill it normally using thrust::copy to the pointer. It doesnt work for a device_memory array. I tried adding __device___ to the functor, but it did not work.


text:
Q: Extract text from PDF file that's saved as image only on Python I am trying to extract text from pdf file using python. So I am using pdftotext to convert pdf files to txt.
My code below works fine with files where I can left click and drag words or search(ctrl+f) by words.
import pdftotext
import os

directory = "/Downloads/test" # path where PDF files are saved

for filename in os.listdir(directory):
    if filename.endswith(".pdf"):
        pathname = os.path.join(directory, filename)

        with open(pathname, 'rb') as f:
            pdf = pdftotext.PDF(f) # ERROR : poppler error creating document

        txtname = pathname.replace('.pdf', '.txt')
        with open(txtname, 'w', encoding='utf-8') as text_file: # edit: encoding utf-8 added
            for page in pdf:
                text_file.write(page)
        continue

However for some pdf files like the one in the link below, where I can open the file and read but can't drag any words, code does not properly work. It only extracts draggable text.
How can I fix this problem? Do I have to use any other parameter or is there any other package to solve this problem?
https://drive.google.com/file/d/1UtyGRmyKIV5O3Fx2-Ug_oTpv-7anXuKU/view?usp=sharing


text:
Q: Blender. Настройка компиляции pythona в bge Набираю скрипты, а затем сразу их подключаю все работает, но если попробовать протестить на ошибки, запустить скрипты в текстовом редакторе то вылезет ошибка.
ImportError: No module named 'bge'
Возможно ли это как нибудь настроить?


text:
Q: Render dynamic html in React I want to use html instead of jsx code.
Various issues regarding this are:
1)How to take my html out of the component file and put it in the other file and then import that file in to my component file ..
2) We are using the proxy server to externalize the html template in current angular project. I want to achieve the same result with react.
3) Is there any way to separate out the JSX code in template so that i can be externalize using some proxy being a http resource.


text:
Q: Android:how to convert html code into image and send this image using ShareIntent? I have used webView to display and capture the content as an image and send using share option.
But I need a to convert html code to image without using webview.
Please help me.
Thanks in advance.

A: I have done this using webView.
webview = (WebView) findViewById(R.id.webView1);

WebSettings settings = webview.getSettings();
settings.setBuiltInZoomControls(true);
settings.setUseWideViewPort(false);
settings.setJavaScriptEnabled(true);
settings.setSupportMultipleWindows(false);

settings.setLoadsImagesAutomatically(true);
settings.setLightTouchEnabled(true);
settings.setDomStorageEnabled(true);
settings.setLoadWithOverviewMode(true);

WebView webview = (WebView) findViewById(R.id.webview);
WebView.enableSlowWholeDocumentDraw();

String RESULTDATA = "
It's working
";
if (!RESULTDATA.equals(null)) {
    Log.e("info", RESULTDATA);
    webview.loadData(RESULTDATA, "text/html", null);
}

circleButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {

        shareResultAsImage(webview);
    }
});

And shareResultAsImage(WebView) method need to define.
private void shareResultAsImage(WebView webView) {
    Bitmap bitmap = getBitmapOfWebView(webView);
    String pathofBmp = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "data", null);
    Uri bmpUri = Uri.parse(pathofBmp);
    final Intent emailIntent1 = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent1.setType("image/png");
    emailIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    emailIntent1.putExtra(Intent.EXTRA_STREAM, bmpUri);

    startActivity(emailIntent1);
}

private Bitmap getBitmapOfWebView(final WebView webView) {
    Picture picture = webView.capturePicture();
    Bitmap bitmap = Bitmap.createBitmap(picture.getWidth(), picture.getHeight(), Bitmap.Config.RGB_565);
    Canvas canvas = new Canvas(bitmap);
    canvas.drawColor(Color.WHITE);
    picture.draw(canvas);
    return bitmap;
}

A: There can be many possible solutions. You can achieve it somehow by showing the full screen web view and programmatically capturing the screen shot of device and sending the data through a background service.
For capturing screenshot through program ; you can use following link:
http://amitandroid.blogspot.in/2013/02/android-taking-screen-shots-through-code.html

A: Check out this SO Answer https://stackoverflow.com/a/64853392/4944007. The library used in it really helped a lot in generating a bitmap from HTML


text:
Q: FacebookLikeView crashing all the time iOS I've been using the FacebookLikeView classes in a lot of apps to enable Facebook profile liking within apps. Recently the code has started crashing in every app I've put it in. The Facebook app is setup correctly and everything. This is the line it is giving an EXC_BAD_ACCESS on:
 else if ([fbEvent isEqualToString:@"xfbml.render"] && [_delegate respondsToSelector:@selector(facebookLikeViewDidRender:)])
        [_delegate facebookLikeViewDidRender:self];

And it's being implemented like so:
_facebook = [[Facebook alloc] initWithAppId:fbAppID andDelegate:self];
self.facebookLikeView = [[FacebookLikeView alloc]init];
[self.facebookLikeView setFrame:CGRectMake(117, 140, 82, 19)];
self.facebookLikeView.delegate = self;

self.facebookLikeView.href = [NSURL URLWithString:user];
self.facebookLikeView.layout = @"button_count";
self.facebookLikeView.showFaces = NO;
[self.facebookLikeView load];

A: You should set your facebookLikeView to nil in your dealloc method or viewdidunload method


text:
Q: Ajax tabs for configurable product with description of child products I need to create custom tab in configurable product that will check is there a description in child product that is selected now and load description of child product. So for example in configurable product i select color: Red, after this, it should check, does this child product have description, if yes, load custom tab with description. Any suggestions even extension would be nice, thank you.

A: I added custom tab and used this https://magento.stackexchange.com/a/295051/55392 to show description and name of child products


text:
Q: Yosemite Terminal weirdly says Meia:/ My Yosemite Terminal App say "Meia:/ username$"?
I don't know what Meia stands for.
Normally I would expect something else. Can I change it?

A: That is the name given to your computer!
Change it here, no need for terminal command.
System Preferences > Sharing
Change your Computer Name here.

A: I ran this command and it changed to MYHOSTNAME.
sudo scutil --set HostName MYHOSTNAME.local


text:
Q: Reference Nuget Package that targets different .NET Framework After recently migrated from ASP.NET Core RC1 to RC2, I am unable to reference dlls directly anymore. Visual Studio tells me that I can only reference Nuget packages.
So I have built a local Nuget package from the assembly. I am able to install the package without any errors. I have no issues performing a dotnet restore. However, I am unable to reference any of the namespaces of the assembly.
The referenced package name is spfcommon.dll, and the assembly targets .Net Framework 4.0. My project targets .Net Framework 4.5.1. I don't know if the difference in target frameworks is causing this issue.
My project.json file:
"frameworks": {
  "net451": {
    "dependencies": {
    },
    "frameworkAssemblies": {
      "System.Runtime": "4.0.10.0"
    }
  }
},
"dependencies": {
  "Common": "4.0.0-*",
  "Data": "4.0.0-*",
  "spfcommon.dll": "1.0.1"   <-- Cannot reference namespaces
},

The error is:

The type or namespace name 'SPF' could not be found (are you missing a
  using directive or an assembly reference?)

Any help is appreciated.

A: Had a very similar problem today, caused me a few hours grief but I found that if I deleted the "wrap" folder and then restored the packages it would work again.
Hopefully it's the same as your issue.


text:
Q: Google Sheets: How to combine multiple rows in their own cells according to an ID? I tried searching for this question very hard, and only managed to find one solution that sort of works. Here's the reference: how to merge rows together if duplicate id (google spreadsheet)
His question is exactly the same as mine, and the solution partially works because sometimes google sheets have an error with custom functions and the cell just get stuck on "Loading.."
I am writing this question in hopes of being able to achieve the same results, without a custom function, using sheets native formulas.
Here's another reference to something similar to what I need: How to combine rows with same ID in Google Sheets?. It is only similar because I need the combined data to be in their own cells, and not merged into one cell.
In other words, the input:
Col A(ID)     Col B(values)     Col C(values)
1               sample1            sample2
2               sample2            sample4
1               newsample1         newsample2

Expected output:
Col A(ID)     Col B(values)     Col C(values)     Col D(values)     Col E(values)
1               sample1            sample2         newsample1         newsample2
2               sample2            sample4

Essentially, again it is exactly the same requirements as how to merge rows together if duplicate id (google spreadsheet), but looking for a solution using google native formula rather than a custom formula if possible.

A: try:
=ARRAYFORMULA(SUBSTITUTE(REGEXREPLACE(SPLIT(TRIM(FLATTEN(QUERY(QUERY(SPLIT(
 FLATTEN(A1:A5&"×"&ROW(B1:C5)&COLUMN(B1:C5)&"¤"&SUBSTITUTE(B1:C5, " ", "♦")), "×"),
 "select max(Col2) where Col2 is not null group by Col2 pivot Col1"),,9^9))),
 " ")&"", "(^.+¤)", ), "♦", " "))

fix:
=ARRAYFORMULA(SUBSTITUTE(REGEXREPLACE(SPLIT(TRIM(FLATTEN(QUERY(QUERY(SPLIT(
 FLATTEN(A3:A&"×"&TEXT(ROW(B3:H), "000000")&TEXT(COLUMN(B3:H), "000000")&"¤"&
 SUBSTITUTE(B3:H, " ", "♦")), "×"),
 "select max(Col2) where Col2 is not null group by Col2 pivot Col1"),,9^9))),
 " ")&"", "(^.+¤)", ), "♦", " "))


text:
Q: two date cells - i want 3rd cell to some value I have two cells with completed installation dates. I have a 3rd cell where I need to input outstanding installations.
If the 2 cells have dates, it means the installation is complete so I want the 3rd cell to show 1 or 2 to show 1 or 2 completed installs.
How do I do this in excel?
Thanks

A: Like @Máté mentioned, it depends on what exactly you want to see.
If you need to see the specific details summarized, you can use a combination of IF() and AND() statements, like:
=IF(AND(A2<>"",B2<>""), "#1 & #2 Completed",IF(A2<>"","#1 Completed", IF(B2<>"", "#2 Completed", "None Completed")))

If you just wanted to see an overall count of progress, you can use what @Máté mentioned in the comments (COUNT works because dates are stored as numbers):
=COUNT(A2:B2) & " installs completed."

I'm assuming you Dates are in A2 & B2.


text:
Q: Workaround for a very weird bug in lualatex math-mode? In this MWE, of a math equation
\documentclass{article}
\begin{document}
\begin{equation}
\sqrt{\frac{\left(E-\frac{N_c e^d}{b}\right)}{a}}
\end{equation}
\end{document}

I find that lualatex (Version beta-0.70.2-2013031016 (TeX Live 2013/dev)) produces a very strange result:

The result is however as expected with pdflatex 3.1415926-2.5-1.40.13 (TeX Live 2013/dev) and xelatex (3.1415926-2.5-0.9999-2013031016 (TeX Live 2013/dev))
The example is really minimal to reproduce the bug.
The question is: I really need to type an equation like this and I really need to use lualatex for other reasons. What is a workaround (trick with commands) or a permanent solution (e.g. load package, add something to the preamble)?
A secondary question is how one reports a bug in lualatex?, (or for any TeX program for that matter)

A: use
\usepackage{unicode-math}

It should be fixed in the current version 0.75. See also:
How to report a bug in LuaTeX?


text:
Q: How to use time.get_tick() When I left click, a line should show from the origin, and if left clicked with two seconds, white circles should appear. After two seconds, another line is drawn and then after two seconds the previous line should disappear. Right now, when I click, a line shows from the origin and then when I click again, two lines show.
from pygame import *
import random

init()
size = width, height = 700, 700
screen = display.set_mode(size)
button = 0

BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
color = RED

mx = 0
my = 0
cx = 0
cy = 0

def drawScene(screen, button):
  if button == 1:
    draw.circle(screen, RED, (mx,my), 5)
    draw.line(screen, color, (mx,my),(lx,ly), 2)
    cx = lx
    cy = ly
    draw.circle(screen, RED, (mx,my), 5)

    display.flip()
  if button == 3:
    draw.line(screen, color, (mx,my),(lx,ly), 2)
    draw.circle(screen, color, (lx,ly), 5)

    display.flip()

running = True
myClock = time.Clock()

# Game Loop
while running:
  lx = mx
  ly = my

  for evnt in event.get():             # checks all events that happen
    if evnt.type == QUIT:
      running = False

    if evnt.type == MOUSEBUTTONDOWN:
      mx,my = evnt.pos
      button = evnt.button

      if time.get_ticks() <= 2000 and time.get_ticks() > 0 :
        draw.circle(screen, WHITE, (mx,my), 5)
      else:
        draw.line(screen, WHITE, (cx,cy),(lx,ly), 2)

      if button == 3:
        if  color == RED:
          color = BLUE
        elif color == BLUE:
          color = GREEN
        elif color == GREEN:
          color = RED

  drawScene(screen, button)

  myClock.tick(60)

quit()

A: Lets start with setting up a basic window first
from pygame import *
import random

init()
size = width, height = 700, 700
screen = display.set_mode(size)
button = 0

BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
color = RED
running = True
myClock = time.Clock()

def drawScene():
    screen.fill(BLACK)
    display.update() #update is the same as flip()

# Game Loop
while running:
    myClock.tick(60)
    drawScene()

    for evnt in event.get():             # checks all events that happen
        if evnt.type == QUIT:
            running = False

After helping someone else with this problem (the question i linked), i found that using lists would be the best idea
So lets create a list for the points where the circles go and lines connect to
points = [] #put this before the drawScene function so it can reference it

Now, when the user clicks, we want to add the point to the list and draw it on the screen
def drawScene():
    screen.fill(BLACK)

    for point in points:
        draw.circle(screen,color,point,5)

    display.update() #update is the same as flip()

if evnt.type == MOUSEBUTTONDOWN:
    points.append(evnt.pos)

now we can create points on the screen by clicking. Lets create the lines
We want to start at the origin so add the origin to the list at the start
points = [(0,0)]

Now we want to loop through every point and draw a circle and a line in between. so change the loop to
for i in range(1,len(points)): #loop through all but the first point as you dont want circle at origin
        draw.circle(screen,WHITE,points[i],5)
        draw.line(screen,color,points[i - 1],points[i])

Now we can draw lines and circles. But we only want to draw the circles if we clicked within 2 seconds, so lets create a timer, we will make one for each line so lets make a list as each line disappears after 2 seconds aswell
timers = []

Once we click, we want to start the timer, we can do that with
if evnt.type == MOUSEBUTTONDOWN:
    points.append(evnt.pos)
    timers.append(time.get_ticks())

this gets the current time in milliseconds we want to know once its been 2 seconds so if we get the current time and minus the start time, we get the difference so
for i in range(len(timers)-1,-1,-1):
    if time.get_ticks() - timers[i] > 2000: #if been 2 seconds
        del timers[i]  #delete the timer
        del points[i + 1] #delete the point for the line

this gets pretty close after 2 seconds the new line moves to the origin, to fix this, we need to delete the origin point
del points[i]

but now after the lines disappear, it starts at the last place clicked instead of the origin. so lets check if there is no lines, make sure the origin is the first point
if len(points) == 1:
    points[0] = (0,0)

Awesome, the last thing is the circles appearing within the 2 seconds, which also means more than 1 line so
if points[0] != (0,0) or len(points) > 2:
    draw.circle(screen,WHITE,points[i],5)

Here is the full code:
from pygame import *
import random

init()
size = width, height = 700, 700
screen = display.set_mode(size)
button = 0

BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
color = RED
running = True
myClock = time.Clock()

points = [(0,0)]
timers = []

def drawScene():
    screen.fill(BLACK)

    for i in range(1,len(points)): #loop through all but the first point as you dont want circle at origin
        if points[0] != (0,0) or len(points) > 2:
            draw.circle(screen,WHITE,points[i],5)
        draw.line(screen,color,points[i - 1],points[i])

    for i in range(len(timers)-1,-1,-1):
        if time.get_ticks() - timers[i] > 2000: #if been 2 seconds
            del timers[i]  #delete the timer
            del points[i] #delete the point for the line

    if len(points) == 1:
        points[0] = (0,0)

    display.update() #update is the same as flip()

# Game Loop
while running:
    myClock.tick(60)
    drawScene()

    for evnt in event.get():             # checks all events that happen
        if evnt.type == QUIT:
            running = False
        if evnt.type == MOUSEBUTTONDOWN:
            points.append(evnt.pos)
            timers.append(time.get_ticks())


text:
Q: how to insert unique string into a string builder even if it is a substring i have the below code, and the contents of self.asStringToCopyFromStatment is as shown below. the problem i have is, given a row with the following values 4.0   -99 13.07   -99 i it will not be inserted into the string self.asStringToCopyFromStatment
because the in operator will assume, that it is already exists as it contains the value 44.0 -99 13.07   -99
i want the strings like:
4.0 -99 13.07   -99
-99 19.0    -99 13.9
0   -99 14.8    -9

for example to be inserted into self.asStringToCopyFromStatment because they are unique. as long as a particular string is unique i want to add it to self.asStringToCopyFromStatment
code:
def appendDataRow(self):
    row = "{0}\t{1}\t{2}\t{3}\n".format(str(self.getAoC1()),str(self.getAoC2()),str(self.getAvgH1()),str(self.getAvgH2()))
    if (not row in self.asStringToCopyFromStatment()):
        self.inputStringToCopyFromStatement+="{0}\t{1}\t{2}\t{3}\n".format(str(self.getAoC1()),str(self.getAoC2()),str(self.getAvgH1()),str(self.getAvgH2()))

data/contents of self.inputStringToCopyFromStatement:
51.0    -99 14.26   -99
-99 29.0    -99 13.21
-99 19.0    -99 13.94 #<====================HERE
-99 27.0    -99 14.11
-99 7.0 -99 13.84
-99 3.0 -99 11.25
-99 10.0    -99 11.4
-99 15.0    -99 11.15
23.0    -99 11.43   -99
44.0    -99 13.07   -99 #<====================HERE
85.0    -99 14.66   -99
86.0    -99 14.78   -99
92.0    -99 14.8    -99 #<====================HERE
91.0    -99 14.76   -99

A: You can use regex to check that row is indeed found at the beginning of a line:
import re

def appendDataRow(self):
    row = "{0}\t{1}\t{2}\t{3}\n".format(str(self.getAoC1()),str(self.getAoC2()),str(self.getAvgH1()),str(self.getAvgH2()))
    if not re.search(rf'^{row}', self.asStringToCopyFromStatment(), re.MULTILINE):
        self.inputStringToCopyFromStatement+="{0}\t{1}\t{2}\t{3}\n".format(str(self.getAoC1()),str(self.getAoC2()),str(self.getAvgH1()),str(self.getAvgH2()))

^ combined with the flag re.MULTILINE matches the beginning of a line.


text:
Q: CMake Boost linking problems I'm using  Boost::Python and Boost::Asio writing my sources and next write CMakeLists.txt to create my own shared library from sources like that (a part of file):
`find_package(Boost REQUIRED COMPONENTS python system thread regex)
if (Boost_FOUND)
    set(Boost_USE_STATIC_LIBS     OFF)
    set(Boost_USE_MULTITHREADED    ON)
    include_directories(${Boost_INCLUDE_DIRS})
    link_directories(${Boost_LIBRARY_DIRS})
endif()
find_package(PythonLibs 3 REQUIRED)
find_package(PythonInterp 3 REQUIRED)
if (PYTHONLIBS_FOUND)
    include_directories(${PYTHON_INCLUDE_DIRS})
    link_directories(${PYTHON_LIBRARIES})
endif()
add_library(my_lib SHARED ${MY_SOURCES})
set_target_properties(my_lib PROPERTIES PREFIX "" SUFFIX ".pyd")
target_link_libraries(my_lib ${Boost_LIBRARIES} ${PYTHON_LIBRARIES})`

(As Boost::Asio is header-only library I added just system thread regex since I've found out it depends on it). So CMake results look correct:
-- Boost version: 1.65.0
-- Found the following Boost libraries:
--   python
--   system
--   thread
--   regex
--   chrono
--   date_time
--   atomic
-- Configuring done
-- Generating done
(But why is it searching for chrono etc.? Additional dependencies?)
Well, when I'm running make my_lib, there are some linker errors like: In function PyInit_my_lib: undefined reference to boost::python::detail::init_module(PyModuleDef&, void (*)()) and  In function boost::asio::detail::posix_thread::~posix_thread():
/usr/local/include/boost/asio/detail/impl/posix_thread.ipp:35: undefined reference to pthread_detach
, so Boost wasn't linked properly.
I've read a lot of docs and similar questions, but couldn't understand what am I doing wrong.
P.S. When I disabled -Wl,--no-undefined linker option, linking was successful, but undefined references are still there and I can't import module using python.

A: Finally, the solution was found by myself. The problem was indeed Boost::Python wasn't built properly. I don't know completely was it a bug or my own fault, but in my case just editing Boost Build's user-config.jam for using python3.5 wasn't enough: running build script resulted to libboost_python3.so, but internally  python2.7 interpreter was used by it for reasons unknown to me.
So, what I did is launched Boost initial bootstrapping as ./bootstrap.sh --with-python=/usr/bin/python3.5m, i.e. pointed the absolute path to required interpreter. After rebuilding Boost::Python, all symbols was resolved successfully.


text:
Q: How do I output a netstat command every 2 seconds to a text file I am trying to make the following happen, but having a hard time getting it to work as expected.
Tried using the watch command, but the output is just a mess.
I found the following, but haven't been able to make it work for my needs:
watch 2 "netstat -a | grep 20427 | grep ESTABLISHED | wc -l"

I would like to the run the following command and output to a file with the following two columns every two seconds.
netstat -a | grep 20427 | grep ESTABLISHED | wc- l

DATE_TIME | NUMBER_OF_CONNECTIONS
Fri Nov  6 14:57:37 | 5
Fri Nov  6 14:57:39 | 10
Fri Nov  6 14:57:41 | 5
Fri Nov  6 14:57:43 | 2

Thank you for any help you can provide.
Take care and be safe.

A: watch is a good tool when you want to… well, to watch. It interacts with the terminal. If you redirect its output to a file then eventually you will find terminal control sequences written to the file. If this is what you tried then such sequences are probably the mess you mentioned.
A straightforward way to run a command in a loop is to… well, to use a loop. :)
You said you wanted to run netstat | … "every 2 seconds". In a loop you have two options:

*

*You run the pipeline asynchronously, sleep for 2 seconds and run the new one; and so on. This way it's almost perfectly "every 2 seconds". But if the execution of a single iteration takes more than the interval, the output from it may appear after the output from the next one, or even interleave with it.

*You run the pipeline synchronously, sleep for 2 seconds and run the new one; and so on. This way it's not "every 2 seconds", it's rather "2 seconds in between". But since there is at most one pipeline running at any given moment, there is no risk the overall output gets mangled.
Note watch -n 2 'sleep 10; date' runs date about every 10 seconds. The watch itself uses the "2 seconds in between" method, not "every 2 seconds".
A loop that runs whatever with 2 seconds in between and redirects the output to a file can be:
while :; do whatever; sleep 2; done >output_file

In your case there are two additional problems:

*

*You want a header. Place it in the file first and then append (>>) to the file.

*You want the date to be in the same line as what follows. The output from date (even with a custom format) ends with a newline character. You can remove it with tr. Or capture the output to a variable (with $() which removes all trailing newlines) and print it later.
Like this:
echo 'DATE_TIME | NUMBER_OF_CONNECTIONS' >output_file
while :; do
   date="$(date)"
   printf '%s | ' "$date"
   netstat -a | grep 20427 | grep ESTABLISHED | wc -l
   sleep 2
done >>output_file


text:
Q: Why can't a flame from a lighter touch water from a running faucet I was conducting an experiment to see if my sink faucet is flammable. I did this by putting a lighter near a running facet. My first guess was that the flame will go out because of the water. But I slowly realized the actual source has to be wet not the flame itself. But I noticed something else that was weird. When I put the flame closer to the running faucet it seems as though the water is surrounded by a force field and the actual flame can never touch it. My guess is that it has something to do with a magnetic field, and either ions or electrons are repelling the flame from the water. Since water is not ionized I'm guessing it's the latter. What are your thoughts on this? I also posted a picture to further illustrate my question.

A: My guess would be the air expands from the heat near the flame. The expanded air pushed the water away from the flames. Hotter air will have less density and floats away, which then will be replaced by colder air below it. The air expands and repeat. This will create a constant "wall" of air surrounding the flames that constantly pushes the water away. The closer the fire to the water, the less air to be expanded, the less the water is pushed.

A: this is caused by entrainment, in which the moving jet of water drags along with it the air in its boundary layer right next to the jet. this tends to slow down the jet and speed up the air in the boundary layer, which then sweeps the flame out of contact with the jet.
To visualize this, shoot the jet sideways and put the flame under it, so its tip is close to the underside of the jet. You will see the tip of the flame brushed sideways in the direction of the jet movement.
In your example, if the jet were moving fast enough, the tip of the flame would bend downwards.


text:
Q: Animated Swing effect to display full-resolution image I've got an editor with lots of image thumbnails.  I'd like a double-click on an image to display the full resolution image using a modal undecorated dialog.  Ideally, this would be animated, to show the image zooming up to full resolution on the center of the screen, then any click would make the image go away, either zooming back out or fading away.
I'm not concerned with establishing an exact behavior, I just want something slick.  I've found plenty of JavaScript examples for this, but is there anything built for Swing?

A: This piece of code does more or less the trick...
There is still a problem in the way I'm setting the dialog's location...
Hope it helps.
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.lang.reflect.InvocationTargetException;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class OpenImageZooming {

 private static final int NB_STEPS = 30;

 private static final long OPENING_TOTAL_DURATION = 3000;

 public static void main(String[] args) {
  OpenImageZooming me = new OpenImageZooming();
  me.openImage(args[0]);
 }

 private JFrame frame;
 private JDialog dialog;
 private JPanelZooming panelZooming;

 private void openImage(final String imagePath) {
  SwingUtilities.invokeLater(new Runnable() {
   public void run() {
    frame = new JFrame();
    frame.setTitle("Open image with zoom");
    JPanel p = new JPanel(new BorderLayout());
    p.add(new JLabel("click on button to display image"), BorderLayout.CENTER);
    JButton button = new JButton("Display!");
    frame.setContentPane(p);
    button.addActionListener(new ActionListener() {

     public void actionPerformed(ActionEvent e) {
      Thread t = new Thread() {

       @Override
       public void run() {
        displayImaggeWithProgressiveZoom(imagePath);
       }

      };
      t.start();

     }

    });
    p.add(button, BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 100);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
   }
  });
 }

 protected void displayImaggeWithProgressiveZoom(String imagePath) {
  try {
   final BufferedImage image = ImageIO.read(new File(imagePath));

   for (int i = 0; i < NB_STEPS; i++) {
    displayDialog(i, NB_STEPS, image);

    Thread.sleep(OPENING_TOTAL_DURATION / NB_STEPS);
   }

  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

 private void displayDialog(final int i, final int nbSteps, final BufferedImage image) {

  try {
   SwingUtilities.invokeAndWait(new Runnable() {
    public void run() {
     if (dialog == null) {
      dialog = new JDialog(frame);
      dialog.setUndecorated(true);
      dialog.setModal(false);
      panelZooming = new JPanelZooming(image);
      dialog.setContentPane(panelZooming);
      dialog.setSize(0, 0);
      dialog.setLocationRelativeTo(frame);
      dialog.setVisible(true);

     }
     int w = (i + 1) * image.getWidth() / nbSteps;
     int h = (i + 1) * image.getHeight() / nbSteps;

     panelZooming.setScale((double) (i + 1) / nbSteps);
     dialog.setSize(w, h);
     dialog.setLocationRelativeTo(null);
    }
   });
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (InvocationTargetException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

 @SuppressWarnings("serial")
 public static class JPanelZooming extends JPanel {

  private BufferedImage image;

  private double scale = 1.0d;

  public JPanelZooming(BufferedImage image) {
   this.image = image;
  }

  @Override
  protected void paintComponent(Graphics g) {
   super.paintComponent(g);
   Graphics2D g2 = (Graphics2D) g;
   AffineTransform at = g2.getTransform();
   AffineTransform oldTransform = (AffineTransform) at.clone();
   at.scale(scale, scale);
   g2.setTransform(at);
   g2.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
   g2.setTransform(oldTransform);

  }

  public void setScale(double scale) {
   this.scale = scale;
  }

 }
}

A: You can create a custom control that displays the image at the scale you want.
1) Create a BufferedImage from the image file you want using ImageIO.read(file) (you can also create it from an InputStream)
2) Extend the JComponent or Canvas class and overload the paint function to draw the animated image using Graphics.DrawImage() and set the width and height based on how long the window has been open.  Set a timer or use another thread to repeatedly have the component redraw itself for however long you want the animation to play.
I haven't done much with customized modal dialogs (I mostly find them annoying), but you can use a JDialog and and your component to it.


text:
Q: LambdaJ: why can't we apply operation in select clause? select(list, having(on(Integer.class).intValue() % 2, equalTo(0)));

the code above throws exception.

A: The % operation has to be evaluated before select() whereas what you want it to be evaluated for each entry. i.e. what you want is closures which is available in Java 8.
If you were using a loop you could write
for(int i: list)
    if(i % 2 == 0)
       // do something with i.

Java's syntax often makes using a loop the cleanest solution when ideally you should have a choice (its also a lot faster).

A: You'll want to define your own matcher:
Matcher<Integer> even = new Predicate<Integer>() {
 public boolean apply(Integer item) {
 return item % 2 == 0;
} };

Adapted from:http://code.google.com/p/lambdaj/wiki/LambdajFeatures