text:
Q: Mysql workbench timestamp change format I have a table with a column in which are inserted timestamps.
exactTime : ' 2017-12-17 05:00:12 ' and i want to change this format into '2017-12-17 05:00'
i would need some help with this .

A: You can truncate to the nearest minute using:
select str_to_date('2017-12-17 05:00:12', '%Y-%m-%d %H:%i')

To actually output without seconds, you need to convert back to a string.  Or just use string operations:
select left('2017-12-17 05:00:12', 16)

A: You could use date_format for this.
select date_format(your_date,'%Y-%m-%d %H:%i')
from your_table;

Resource

A: SELECT date_format('2017-12-17 05:00:12','%Y-%m-%d %h:%i')


text:
Q: Multi parameter query for tags search My database is composed by 2 tables:

*

*'tests

*'tags'

'tags' table is related to 'tests' table with a 'many to one' relation. The purpose of the 'tags' table is to assign tags to each test so the user is able to query the records in the table 'tests' which have specific tags.
For this purporse I made a parameter query but I'm able to input only one parameter per time where instead I need to input multiple parameter (tags) because each record in the 'tests' table can have multiple tags. I saw it's possible to use operators such as 'AND' and 'OR' in the criteria field of the query coloumns but I have no idea how to do that.

A: First of all you need to collect tags for searching. You can do this using list box with multi selection or custom form with checkboxes similar to quick filters in Excel. Collecting tags as free text is possible, but users don't like this method.
Then save collected tags to special new table and join it with your existing tables. Query results will be limited by selected tags only.
As alternative you can create dynamic record source for the form with results and use In. Generate SQL string like this:
"SELECT * FROM MyQueryWithFullResults WHERE tag IN ('tag1','tag2','tag3')"

And use it as record source for form or as SQL for recordset

redpajama_set_name: RedPajamaStackExchange


text:
Q: app has unfortunately stopped (facebook login) I have no clue why it shows "app unfortunately stopped" error. I have seen the DDMS session and all it says is "Could not find appcompat_v7.apk!"
The mainactivity.java is:
package com.example.iwashere;
import java.io.IOException;
import java.net.MalformedURLException;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class MainActivity extends ActionBarActivity implements OnClickListener {

Facebook fb;

ImageView button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String facebook_app_id = getString (R.string.facebook_app_id);
        fb = new Facebook (facebook_app_id);
        button = (ImageView)findViewById(R.id.login);
        button.setOnClickListener(this);
        updateButtonImage();
    }

       private void updateButtonImage() {
        // TODO Auto-generated method stub

        if(fb.isSessionValid())
        {
            button.setImageResource(R.id.logout);
        } else{
            button.setImageResource(R.id.login);
        }
    }

        @Override
        public void onClick(View v)

        {
             if(fb.isSessionValid()){
            //button close our session - logout of facebook
                try {
                   fb.logout(getApplicationContext());
                   updateButtonImage();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
             else {

            //login to facebook
             fb.authorize(this, new DialogListener() {

             @Override
             public void onFacebookError(FacebookError e) {
                // TODO Auto-generated method stub

            }

             @Override
        public void onError(DialogError e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onComplete(Bundle values) {
            // TODO Auto-generated method stub

             }

             @Override
             public void onCancel() {
                // TODO Auto-generated method stub

            }
        });
         }
    }

      @Override
       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        fb.authorizeCallback(requestCode, resultCode, data);
    }

}
and xml is:
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
     android:layout_height="match_parent"
      android:background="@drawable/background1"
     android:paddingBottom="@dimen/activity_vertical_margin"
     android:paddingLeft="@dimen/activity_horizontal_margin"
     android:paddingRight="@dimen/activity_horizontal_margin"
     android:paddingTop="@dimen/activity_vertical_margin"
     tools:context="com.example.iwashere.MainActivity" >

     <TextView
        android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="@string/hello_world"
        android:textColor="#FFFF"/>

     <ImageView
         android:id="@+id/login"
        android:layout_width="wrap_content"
         android:layout_height="wrap_content"
        android:src="@drawable/login" />

          <ImageView
             android:id="@+id/logout"
             android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:src="@drawable/logout"
              android:visibility="invisible"/>

     </RelativeLayout>

A:   extends ActionBarActivity

replace by
   extends Activity

Remove this:
     import android.support.v4.app.FragmentActivity;
    import android.support.v7.app.ActionBarActivity;


text:
Q: Storing an array of searchable values in MongoDB I need to store the role ID and role name in each document in my Users collection. I need to be able to say "Get Users that have xyz role" or "Get users that have a role who's name contains 'XYZ'", stuff like that.
Is that even possible in Mongo?
Right now, I'm storing data like this:
{
    "_id": {
        "$id": "4fe30e3db92f5d2a5c000000"
    },
    "alias": "rogue_coder",
    "display_name": "Rogue Coder",
    "email": "rogue@example.com",
    "roles": {
        "4fe30e5fb92f5d6f53000000": "Super Administrator"
    }
}

With that, I can see if a user has a given role, but I can't get all users who have a role that contains the word "Super" for example. Any ideas on how to do this?

A: MongoDB has support for the regular expression for matching key's values.
Take look at this MongoDB Regular Expression

A: Not sure but you may try a bit like this
db.collection.find( { roles: { /super.*/i } );

A: Based on what your attempting to do, you may have to store role_id & role_name in separate arrays, like such:
{
    "_id": {
        "$id": "4fe30e3db92f5d2a5c000000"
    },
    "alias": "rogue_coder",
    "display_name": "Rogue Coder",
    "email": "rogue@example.com",
    "role_names": [
        "Super Administrator"
    ],
    "role_ids" : [
        "4fe30e5fb92f5d6f53000000"
    ]
}


text:
Q: OsmDroidBonusPack OnMarkerClickListener not called I have a strange issue with the OnMarkerClickListener in OsmBonusPack. The listener would not be called on click if I add the marker at OnCreate. However, if I add the marker after all initial set up, let say when the user interacts with the app, the OnMarkerClickListener would be called when the marker is clicked.
To illustrate, the OnMarkerClickListener added by this code will not be responsive:
@Override public void onCreate(Bundle savedInstanceState) {
    MapView mapView = (MapView) findViewById(R.id.map);
    mapView.setTileSource(TileSourceFactory.MAPNIK);

    Marker marker = new Marker(mapView);
    marker.setPosition(new GeoPoint(latitude, longitude));
    marker.setOnMarkerClickListener(MyOnMarkerClickListener);
    mapView.getOverlays().add(marker);
    mapView.invalidate();
}

The OnMarkerClickListener added by this code will be responsive (I am even using the same marker and mapView reference):
public void markerAddedbyUser() {
    mapView.getOverlays().add(marker);
    mapView.invalidate();
}

I am wondering if it is related to the mapView.getOverlays() method not fully ready until the UI is completely drawn. However, I tried to put the first code in onCreateOptionMenu and it still doesn't work.

A: Shortly after I posted this question, I found the solution. I listed all the objects from MapView.getOverlays() using:
List<Overlay> overlays = mapView.getOverlays();
for(Overlay overlay : overlays) {
    System.out.println(overlay.getClass());
}

I found I have added a MapEventsOverlay some elsewhere and the overlay is at the top of all overlays (last item of the list). That MapEventsOverlay is avoiding the OnMarkerClickListeners to listen to click events. I solved the issue by adding the MapEventsOverlay to the first of the list:
mapView.getOverlays().add(0, mMapEventsOverlay);


text:
Q: openvms 7.1 install create program.exe utility hangs When attempting to install a program as a known image, instally hangs, there is no response, control Y fails and the only way out is to stop the process.
install create logical_path:program.exe/header

Program and subroutines are compiled nodebug and it is linked notraceback.
Logical path is in lnm$system. Directory is owned by system, and has protection rwe,rwe,re,re. program.exe has protection rwed,rwed,re,re. I think the problem lies with program.exe, but what ? There must be a simple explanation. BTW, am logged in as system, with cmknl set.
Many thanks in advance.

A: I can't comment, so asking as an "answer" (site rule - admins delete this if you want) - installing an image requires free global sections. Not sure why it would ever "hang" trying to do that, but that's the only thing I can think of that would prevent the INSTALL from not working.
Suggest checking free global sections and free global pages.

A: Well ... its a loooong time ago but it could be the actual name of your exe!  I remember a customer problem where they installed a program of their own called ... 'install.exe'.  Boy did VMS get its knickers in a twist over that!!  So try 'myprogram.exe' instead of 'program.exe'  The other reason may be because you shouldn't install a program called abc.exe if abc.exe is already installed.  This is because the second abc.exe cannot replace the first abc.exe until the first abc.exe has released all its channels.  And if someone is running (the first) abc.exe, or has it open for some other reason, then the install of the second abc.exe won't complete. VMS (because it is a properly written O/S) loves to do things 'in order'.  Hope this helps


text:
Q: Windows 8.1 App certification fails for invalid OSVersion and image size I'm trying to update my WinJS app to the new Windows Dev Center.
I checked the app before uploading with the App Cert Kit 3.4 on Windows 8.1 and everything was fine.
On the submission process the app failed at certification:

*

*OSMinVersion/OSMaxVersion attribute is invalid

*Splashscreen image size is wrong (should be 480x800)

My appxmanifest defines the OS version:
<Prerequisites>
   <OSMinVersion>6.3.1</OSMinVersion>
   <OSMaxVersionTested>6.3.1</OSMaxVersionTested>
</Prerequisites>

I thought 6.3.1 was right for Windows 8.1.
The strange thing about the image size is that Visual Studio 2013 on Win8.1 tells me that the size of the asset splashscreen should be 620x30. It won't even let me build a appx package with a size of 480x800. Installed Visual Studio 2015 on a Windows 10 machine - same with the image size.
I also installed the latest WACK tool from the Win10 SDK and I got the same errors on this certification process as the ones on the Store submission.
Which OS version should I define? How can I apply a image size that is marked as invalid on the corresponding IDE? (do I need to manipulate the appxbundle afterwards?)
Thanks for your help!

A: Okay I found the solution to the problem:
My app package was defined as the following:
<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest"
         xmlns:m2="http://schemas.microsoft.com/appx/2013/manifest"
         xmlns:m3="http://schemas.microsoft.com/appx/2014/manifest"
         xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest">

....

</Package>

I removed the xmlns:mp schema (won't be used anyway on this appxmanifest) and the WACK tool proceeds without any error :)


text:
Q: Anyone know why my webpage that uses jquery doesn't format correctly in IE? I have been working on creating a website for a professor at my college to help teach basic php.  I have been designing it and using Firefox to preview it and didn't really think to test it in IE till now and I discovered that it does not preview correctly.  The jQuery navigation loads vertically when it should load horizontal.  I used the W3C validator to check my code in my homepage and my css sheet and they both check out.  I have read that IE has to have a correct DocType in order to load pages sometimes which I assume mine is correct.  I am using a jquery menu for my navigation bar and a jquery accordion in my body.  Any ideas why they are being displayed incorrectly and why they are not being centered in the middle of the page?

I would like it to be viewable in IE 9 and any newer versions.  So to be specific does anyone have any ideas why this page won't load correctly in IE 9.
Here is the link: http://cite.nwmissouri.edu/projects/php/
Here is the current code of the homepage:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link rel="shortcut icon" href="images/favicon.ico"/>
<link href="css/external.css" rel="stylesheet" type="text/css" media="all" />
<link rel="stylesheet" type="text/css" href="css/jMenu.jquery.css" media="screen" />
<link rel="stylesheet" type="text/css" href="css/jquery-ui-1.10.3.custom.min.css" media="screen" />

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>PHP Practice</title>

    Home

                The Basics

                        Basics

                        Category 2.8

Category 2.3

                        Category 2.7

Category 2.3

                Installation

                        Apache

                        PHP

                HTML

                        Basics

                        Other

                Examples

Basic PHP

Downloading

                        Other

Category 4.3

Category 4.3

Category 4.3

Category 4.3

                MYSQL

                        MYSQL

Category 5.3

Category 5.3

Category 5.3

Category 5.3

Category 5.2

Category 5.2

Category 5.2

PHP

                Help

Category 7.2

Category 7.2

Category 7.2

Category 7.2

What is PHP

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

The Basics

PHP scripting starts with <?php and ends with ?>

              <?php

              ? >

              Can be placed anywhere in the document

              Can have multiple PHP tags in a document

              PHP file contains HTML tags and PHP scripting code

XHTML

Stands for eXtensible Hypertext Markup Language

              Markup in this name refers to the coded tags that allow the web page designer to format documents displayed on the web

              Tool for designing the format of a web page

Resources

 Some web pages you may want to look at for reference are:

                  www.w3schools.com

                  www.stackoverflow.com

                  www.php.net

Examples

 examples

MYSQL

 sql

Here is the CSS as well:
@charset "utf-8";
/* CSS Document */

#container{
    position: relative;
    width: 800px;
    height: auto;
    margin-left: auto;
    margin-right: auto;

    border-top: black thin solid;
    border-right: black thin solid;
    border-bottom: black thin solid;
    border-left: black thin solid;

    background-color: #575757;
}

#header{
    text-align: center;
    background-image: url(../images/header2.png);
    background-size: 100%;
    background-repeat: no-repeat;
    width: 100%;
    height: 125px;
    position: center;
}

#navigation{
    text-align: center;
    width: 100%;
    height:40px;
    background-repeat: no-repeat;
    background-color: #322f32;
    position: center;
    /*
    border-top: #99989d thin solid;
    border-bottom: #99989d thin solid;
    */
    border-bottom: black thin solid;
    border-top: black thin solid;
}

#main {
width:730px;
height:auto;
position:relative;
top:20px;
left:30px;
bottom:20px;
right:30px;

padding-left:3px;
padding-right:3px;
padding-bottom:3px;
padding-top:3px;

background-color:#d1d1d4;
}

#information{
    padding: 2px;

;}

#editable{
    padding: 1px;
}

A: Since it seems that my comment above fixed it, I will add it as an answer:
You cannot have any element before your doctype (not even a comment) or IE will switch to quirksmode... so remove your comment above the doctype and see if that will fix the issue.


text:
Q: How to divide two lengths and get a result as an integer? I have a problem dividing two lenghts and getting a result as an integer. I was trying to use this package:
\usepackage[nomessages]{fp}
It didn't really work for me. I tried it multiple ways, but it still didnt work.
Can you help me with an alternative way?

A: You can use \numexpr and \dimexpr, but this rounds rather than truncate:
\documentclass{article}

\newcommand{\getlengthratio}[2]{%
  \number\numexpr
    \dimexpr#1\relax
     /
    \dimexpr#2\relax
  \relax}

\newcounter{test}

\begin{document}

There are \getlengthratio{\textwidth}{\parindent} parindents in a line

\setcounter{test}{\getlengthratio{\textwidth}{\parindent}}

The same number: \thetest

\end{document}

A different approach, where you can choose between floor, ceil and round, is with expl3:
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\DeclareExpandableDocumentCommand{\getlengthratio}{mm}
 {
  \fp_eval:n { floor ( \dim_to_fp:n { #1 } / \dim_to_fp:n { #2 } , 0 ) }
 }
\ExplSyntaxOff

\newcounter{test}

\begin{document}

There are \getlengthratio{\textwidth}{\parindent} parindents in a line

\setcounter{test}{\getlengthratio{\textwidth}{\parindent}}

The same number: \thetest

\end{document}


text:
Q: No C# Exception code coverage in SonarCloud We are using SonarCloud for code analysis in Azure DevOps on a C# .NET Core application.
There is a recurring issue with lines throwing exceptions showing as uncovered, as shown below

The total code coverage for this file is shown as 36.8%, with all of the thrown exceptions being highlighted as uncovered.
However, these exceptions are being explicitly tested in a test file using xUnit:
[Fact]
public void It_should_not_allow_empty_importance_value()
{
    try
    {
        _validator.ValidateImportance("", 0);
    }
    catch (FileFormatException ex)
    {
        Assert.Equal("Missing importance value in row 1", ex.Message);
    }
}

the 'Assert.Throws' assertion was also used:
[Fact]
public void It_should_not_allow_empty_importance_value()
{
    Assert.Throws<FileFormatException>(() => _validator.ValidateImportance("", 0));
}

Inspecting the .coverage file generated by the build pipeline showed this file as 100% covered:

The Prepare Analysis Configuration task is configured as follows, excluding certain files from analysis:
# Additional properties that will be passed to the scanner,
# Put one key=value per line, example:
sonar.exclusions=**/*.bin,**/WebApi/Migrations/*,**Tests.Unit/*,**Tests.Integration/*,**/WebApi/Extensions/EfCoreExtensions.cs
sonar.cs.vstest.reportsPaths=$(Agent.TempDirectory)/TestResults/*.trx

Running the tests locally returns 100% coverage for the given file.
Is there an issue with C# code coverage of exceptions? This has been an issue throughout the project where thrown exceptions are shown as not being covered.
Please let me know if any additional information is needed. Any suggestions are appreciated. Thanks!


text:
Q: Doctrine 2 Postgresql stored procedure mapping I'd like to associate to a doctrine entity a postgresql stored procedure (which returns a table as result) instead of a table.
Ex: the procedure Get_Uuser(sexe, age) search all the users for the selected parameters and returns a collection of user_id (names user_id_rech for example).
In pgsql, I can use this stored procedure as a table :
select user_name
from User
left join  Get_User('H', 45)
where User.user_id = user_id_rech

The stored procedure is used like a table here.
I don't think that doctrine 2 allows to map a stored procedure, but I'd like that someone can confirm that to me.
Thanks

A: (Writing this as an answer, because it's too long as a comment.)
Whether Doctrine allows this or not, I'd like to volunteer that your query will be inefficient (perhaps terribly so), because Postgres will have no means to estimate how many rows Get_User() will return.
Chances are that your function is a mere wrapper around return query select ... in plpgsql, or the SQL equivalent if the written in plain sql. If so, consider creating a view instead. This will allow Postgres to rewrite the query if needed, as well as use proper statistics on your table's contents, and probably allow you to get rid of the join altogether.
Better yet, issue the query directly. If you use it frequently, create a function that returns it ready for further filtering.


text:
Q: R Highlight point on ecdf line graph I'm creating a frequency plot using ggplot and the stat_ecdf function. I would like to add the Y-value to the graph for specific X-values, but just can't figure out how. geom_point or geom_text seems likely options, but as stat_ecdf automatically calculates Y, I don't know how to call that value in the geom_point/text mappings.
Sample code for my initial plot is:
x = as.data.frame(rnorm(100))
ggplot(x, aes(x)) +
stat_ecdf()

Now how would I add specific y-x points here, e.g. y-value at x = -1.

A: The easiest way is to create the ecdf function beforehand using ecdf() from the stats package, then plot it using geom_label().
library(ggplot2)
# create a data.frame with column name
x = data.frame(col1 = rnorm(100))
# create ecdf function
e = ecdf(x$col1)

# plot the result
ggplot(x, aes(col1)) +
  stat_ecdf() +
  geom_label(aes(x = -1, y = e(-1)),
             label = e(-1))

A: You can try
library(tidyverse)
# data
set.seed(123)
df = data.frame(x=rnorm(100))
# Plot
Values <- c(-1,0.5,2)
df %>%
  mutate(gr=FALSE) %>%
  bind_rows(data.frame(x=Values,gr=TRUE)) %>%
  mutate(y=ecdf(x)(x)) %>%
  mutate(xmin=min(x)) %>%
  ggplot(aes(x, y)) +
   stat_ecdf() +
   geom_point(data=. %>% filter(gr), aes(x, y)) +
   geom_segment(data=. %>% filter(gr),aes(y=y,x=xmin, xend=x,yend=y), color="red")+
   geom_segment(data=. %>% filter(gr),aes(y=0,x=x, xend=x,yend=y), color="red") +
   ggrepel::geom_label_repel(data=. %>% filter(gr),
                             aes(x, y, label=paste("x=",round(x,2),"\ny=",round(y,2))))

The idea is to add the y values in the beginning, together with the index gr specifing which Values you want to show.
Edit:
Since this code adds points to the actual data, which could be wrong for the curve, one should consider to remove these points at least in the ecdf function stat_ecdf(data=. %>% filter(!gr))


text:
Q: How to generate uncorrelated white noise sequence in R without using arima.sim? I want to know how to generate uncorrelated white noise sequence $WN(0,\sigma^2)$ in R **without using ** arima.sim(list(order=c(0,0,0)),200) ?
The reason I post this in here instead of stackoverflow is because I feel like this requires understanding the mathematical structure of a white noise such that we can build a program about it. If viewers feel that this question really belong to stackoverflow, please do not downvote this question. Just let me know, then I will migrate it to stackoverflow.

A: You will have to specify some distribution, but if you are happy to go with the default choice of a normal distribution (as, in fact, does arima.sim, unless you override the default with some other choice of its rand.gen argument), then rnorm(200) will do the trick: it yields a series of uncorrelated (in fact, even independent) and identically distributed r.v.s.

A: White noise is simply a sequence of i.i.d random variables. Due to that, you could just use:
rnorm(n, mean = 0, sd = 1)
To give you a little more insight, here's how I would use it to generate a random walk:
set.seed(15)
x=NULL
x[1]=0
for (i in 2:100) {
   x[i] = x[i-1] + rnorm(1,0,1)
}
ts.plot(x, main = 'Random walk 1(Xt)', xlab = 'Time', ylab = '', col='blue', lwd = 2)


text:
Q: How to use LoadKeyboardLayout in a background thread? I'm using the LoadKeyboardLayout function to load and activate the keyboard layout this way:
procedure TfrmMain.eSearchEnter(Sender: TObject);
begin
  LoadKeyboardLayout('00000429', KLF_ACTIVATE);
end;

It works perfectly, but it freezes the active form for 1-2 seconds, since this change takes some time. For preventing this, I've moved this code to a background thread like this:
type
  FLangChangeThread = class(TThread)
  private
    FLang: string;
  protected
    procedure Execute; override;
  public
    property Lang: string read FLang write FLang;
  end;

implementation

procedure FLangChangeThread.Execute;
begin
  if FLang = 'EN' then
    LoadKeyboardLayout('00000409', KLF_ACTIVATE)
  else
  if FLang = 'FA' then
    LoadKeyboardLayout('00000429', KLF_ACTIVATE);
end;

This background thread I'm then running this way:
procedure TfrmMain.ChangeWritingLanguage(ALang: string);
begin
  with FLangChangeThread.Create(True) do
  begin
    FreeOnTerminate := True;
    Lang := ALang;
    Resume;
  end;
end;

procedure TfrmMain.eSearchEnter(Sender: TObject);
begin
  ChangeWritingLanguage('FA');
end;

The problem is, that it doesn't change the keyboard layout as expected.
I've debugged the code and all lines were execeuted; just the LoadKeyboardLayout function hasn't made its job.
How can I make the LoadKeyboardLayout function work from a background thread ?

A: First of all, you should check the result of the LoadKeyboardLayout function and if it fails, you should check the error returned by the GetLastError function to determine what is wrong.
But even if this function call succeed, it will activate the input locale identifier, but for your worker thread. As the LoadKeyboardLayout reference states for the KLF_ACTIVATE flag (emphasized by me):

KLF_ACTIVATE
If the specified input locale identifier is not already loaded, the
  function loads and activates the input locale identifier for the
  current thread.

Although, if you want to load and activate keyboard layout for the whole process, you may try to combine the KLF_ACTIVATE flag with the KLF_SETFORPROCESS one:
const
  KLF_SETFORPROCESS = $00000100;
begin
  if LoadKeyboardLayout('00000429', KLF_ACTIVATE or KLF_SETFORPROCESS) = 0 then
    RaiseLastOSError;
end;


text:
Q: Rspec/capybara have_text fail but include pass Can't figure out this very strange behavior.
This will pass
expect(html_string).to include reset_url
These will fail
expect(html_string).to have_text reset_url
expect(html_string).to have_link reset_url
And the error message is expected to find text but there were no matches. So it's not a forgetting to include spec_helper mistake.
And I have double checked the html_string does have the entire reset_url. They are NOT invisible content
Plus I have other specs (in the same spec file) that use have_text and have_link passing.
edit: Not sure why the vote down without comment. But if you are voting down, please provide a comment or and thought you have. Thanks!

A: What stands out to me here is that the include matcher is built into RSpec, while have_text and have_link are included via the Capybara::RSpecMatchers module.
If your other specs are passing as expected, your rails_helper should be requiring the capybara/dsl just fine.
Is it possible that you're missing require 'rails_helper' in this particular spec, but including it in the others?


text:
Q: [iPhone]How to deploy a app with Application Preferences to real device Every thing is OK in simulator but when I deploy my app to real device (jailbroken) I can't find app's Application Preferences in Setting or my iPhone!
What wrong?! Please help me!

A: I presume that you mean the settings bundle within the project. If it works in the simulator and not in the device there is a good chance that the problem is case sensitivity. Check that the name of the settings bundle is Settings.bundle


text:
Q: Using ant with nitrous.io I'm trying to use ant with nitrous to build my application. However, due to lack of sudo privileges, I can't install ant. Is there a way to circumvent this?
sudo apt-get -u install ant
WARNING: sudo access is not available; running without sudo.
E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?

A: If your Nitrous box supports Autoparts (newer ones do), you can just type parts install ant.
If not, follow the directions at http://blog.nitrous.io/2013/09/18/introducing-autoparts-for-nitrous-io.html to install Autoparts, and then install ant with it.


text:
Q: php mail not sending "invalid email address" im getting the "invalid email address"
all is hardcoded for testing, what is missing? thanks!

<title>PHP Mail Sender</title>

<?php

/* All form fields are automatically passed to the PHP script through the array $HTTP_POST_VARS. */
$email = $HTTP_POST_VARS['example@example.com'];
$subject = $HTTP_POST_VARS['subjectaaa'];
$message = $HTTP_POST_VARS['messageeeee'];

/* PHP form validation: the script checks that the Email field contains a valid email address and the Subject field isn't empty. preg_match performs a regular expression match. It's a very powerful PHP function to validate form fields and other strings - see PHP manual for details. */

if (!preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/", $email)) {
  echo "
Invalid email address
";
  echo "Back";
} elseif ($subject == "") {
  echo "
No subject
";
  echo "Back";
}

/* Sends the mail and outputs the "Thank you" string if the mail is successfully sent, or the error string otherwise. */
elseif (mail($email,$subject,$message)) {
  echo "
Thank you for sending email
";
} else {
  echo "
Can't send email to $email
";
}
?>

A: Change
$email = $HTTP_POST_VARS['jaaanman2324@gmail.com'];
$subject = $HTTP_POST_VARS['subjectaaa'];
$message = $HTTP_POST_VARS['messageeeee'];

to
$email ='jaaanman2324@gmail.com';
$subject ='subjectaaa';
$message = 'messageeeee';

A: I think you want it to be hardcoded like this:
$email = 'jaaanman2324@gmail.com';

Otherwise you are trying to get the value out of HTTP_POST_VARS with the key of jaaanman2324@gmail.com

A: First, don't use $HTTP_POST_VARS, it's $_POST now.
Second, by writing $HTTP_POST_VARS['jaaanman2324@gmail.com'] you're looking for table element with juanman234@gmail.com key.
That's not what you wanted to do.
If you want to hardcode it, write
$email = 'jaaanman2324@gmail.com';`

if not, write
$email = $_POST['email'];

to get email field from form.


text:
Q: Выходит из авторизации пользователя через 5 минут Возникает проблема, что после авторизации через 5 минут пропадает авторизация, в startup:
services.Configure<IdentityOptions>(options =>
        {
            options.User.RequireUniqueEmail = true;
            options.Password.RequireNonAlphanumeric = false;

            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(2);
            options.Lockout.MaxFailedAccessAttempts = 3;
            options.Lockout.AllowedForNewUsers = true;
        });

        services.ConfigureApplicationCookie(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromDays(150);
            o.SlidingExpiration = true;
        });

        services.AddSession(options =>
        {
            options.Cookie.IsEssential = true;
            options.Cookie.Name = ".MyApp.Session";
            options.IdleTimeout = TimeSpan.FromDays(150);
        });

Как можно сделать, чтобы авторизация не пропадала?


text:
Q: cron task four hour later I have this task in my crontab
0 14 * * * command

but in my /var/log/syslog, I have
Jun 21 19:00:01 debian-squeeze-base /USR/SBIN/CRON[12810]: (user) CMD (command)

why the task run 5 hours later ?

A: How is your locale set?  How is your timezone set?
Perhaps the user running the cron (root) is using something in UTC and you are expecting it in localtime?

A: If memory serves me correctly, you have to restart the cron daemon after changing your timezone.
Have you changed your timezone since your last reboot?


text:
Q: Doubt about why to consider partial pressures in calculating vapour pressure I am confused as to why the partial pressure is considered while calculating whether a liquid will evaporate in atmosphere or not.
But doesn't the reasoning given of molecules colliding also consider effect of random collisions or is it just molecules' going in and going out?
Does Dalton's law not consider the effect of collisions and pressure by foreign particles? Because by molecular picture, it makes some sense to me that pressure of any overbearing fluid will affect vaporization, as we see by example that substances liquefy when kept in pressurized atmospheres.
So why do we consider only partial pressure? My guess is that at low enough pressures, such collision and interactions are negligible and Dalton's law is valid for vaporization considerations only for low pressures. Please clarify.

A: The vapor pressure of a pure substance is only a function of temperature, and it is not a function of the presence of an air atmosphere.  When the vapor pressure of a pure substance is higher than the partial pressure of that same substance on top of the liquid surface, the liquid will evaporate.  When the partial pressure of the substance on top of the liquid surface is greater than the vapor pressure of that substance, condensation will occur.  Note that this is a dynamic process, where molecules are continuously leaving the liquid and returning to the liquid, usually at different rates.  For more info on vapor pressure, see the following: https://en.wikipedia.org/wiki/Antoine_equation


text:
Q: C# textbox programming I'm trying to program the textboxes, so they do their instructions AFTER the textbox is left. Any ideas on how to do it? I tried smth with KeyUp, but don't really know how it works
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace For_homework
{
    public partial class Form1 : Form
    {
        public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        var LoopResult = new List<int>();
        var LoopParameters = new List<int>();
        LoopParameters = TakeInput();
        LoopResult = Looping(LoopParameters);
        Result(LoopResult);
        FinalResult(LoopResult);
    }
    private List<int> TakeInput()
    {
        var Loop = new List<int>();
        Loop.Add(int.Parse(textBox1.Text));
        Loop.Add(int.Parse(textBox2.Text));
        Loop.Add(int.Parse(textBox3.Text));
        Loop.Add(int.Parse(textBox4.Text));
        Loop.Add(int.Parse(textBox5.Text));
        Loop.Add(int.Parse(textBox6.Text));
        return Loop;
    }//Take the input
    private List<int> Looping(List<int> LoopParam)
    {
        var LoopSum = new List<int>();
        LoopSum.Add(0);
        LoopSum.Add(0);
        for (int i = LoopParam[0]; i <= LoopParam[1]; i += LoopParam[2])
        {
            LoopSum[0]+=i;
        }
        for(int i = LoopParam[3]; i <= LoopParam[4]; i += LoopParam[5])
        {
            LoopSum[1]+=i;
        }
        return LoopSum;
    }//Do the loop and summarize
    void Result (List<int> LoopResult)
    {
        resultA.Text = ""+LoopResult[0];
        resultB.Text = ""+LoopResult[1];
    }//Give result
    void FinalResult(List<int> LoopResult)
    {
        if(LoopResult[0]>LoopResult[1])
        {
            WhoWins.Text = "Player A wins";
        }
        else if(LoopResult[1]>LoopResult[0])
        {
            WhoWins.Text = "Player B wins";
        }
        else
        {
            WhoWins.Text = "It's a draw";
        }
    }//Give final result
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        int i = int.Parse(textBox1.Text);
        if (i < 1 || i > 6)
            label3.Text = "Wrong number";
    }//Texbox evaluation

    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        int i = int.Parse(textBox2.Text);
        if (i < 7 || i > 18)
            label4.Text = "Wrong number";
    }

    private void textBox4_TextChanged(object sender, EventArgs e)
    {
        int i = int.Parse(textBox4.Text);
        if (i < 1 || i > 6)
            label7.Text = "Wrong number";
    }//Textbox evaluation

    private void textBox5_TextChanged(object sender, EventArgs e)
    {
        int i = int.Parse(textBox5.Text);
        if (i < 7 || i > 18)
            label8.Text = "Wrong number";
    }
}
}

The form itself
It told me my post is mostly code so I need to add more details

A: There is LostFocus TextBox Event that might be useful for you in this case:
private void textBox1_LostFocus(object sender, System.EventArgs e)
{
    //Do something
}

And don't forget to register event in your designer file as
textBox1.LostFocus += new EventHandler(textBox1_LostFocus);


text:
Q: Running a jar which contain the junit I compiled a java project which contains implementation as well as junit . I work fine in eclipse. But After converting to jar and Run in Linux terminal it is showing some Exceptions.
I have done the implementation in main class and excecuting the test class by  junit.textui.testrunner.run (xyz.class) command
I am getting the exception on running the jar in linux console as NoClassDefFoundError for junit/framework/testcase.
On commenting the junit.textui.testrunner.run (xyz.class) and create a jar of same implementation ,it works fine in console

A: The jar you created has dependency on junit.jar so download it from here
and include it in the classpath while running your jar
One more thing as you are using terminal to run the jar
A small note - When you use -jar option, the JAR file is the source of all user classes, and other user class path settings are ignored. That means you cannot use -cp with -jar


text:
Q: Counting Occurrences of Zip Codes in Big Data Set w/Python I'm a python newbie looking to count the 100 most occurring zip codes in several .csv files (6+). There are literally 3 million+ zip codes in the data set, and I'm looking for a way to pull out only the top 100 most occurring. Here is a sample of code below that was inspired from another post, although I'm trying to count across several .csv files. Thanks in advance!
import csv
import collections

zip = collections.Counter()
with open('zipcodefile1.csv', 'zipcodefile2.csv', 'zipcodefile3.csv') as input file:
   for row in csv.reader(input_file, delimiter=';'):
       ZIP[row[1]] += 1

print ZIP.most_common(100)

A: I'd suggest using Python's generators here, as they will be nice and efficient. First, suppose we have two files:
zc1.txt:
something;00001
another;00002
test;00003

and zc2.txt:
foo;00001
bar;00001
quuz;00003

Now let's write a function that takes several filenames and iterates through the lines in all of the files, returning only the zip codes:
import csv

def iter_zipcodes(paths):
    for path in paths:
        with open(path) as fh:
            for row in csv.reader(fh, delimiter=';'):
                yield row[1]

Note that we write yield row[1]. This signals that the function is a generator, and it returns its values lazily.
We can test it out as follows:
>>> list(iter_zipcodes(['zc1.txt', 'zc2.txt']))
['00001', '00002', '00003', '00001', '00001', '00003']

So we see that the generator simply spits out the zip codes in each file, in order. Now let's count them:
>>> zipcodes = iter_zipcodes(['zc1.txt', 'zc2.txt'])
>>> counts = collections.Counter(zipcodes)
>>> counts
Counter({'00001': 3, '00002': 1, '00003': 2})

Looks like it worked. This approach is efficient because it only reads one line in at a time. When one file is completely read, it moves on to the next.


text:
Q: How to compare two counters using TeX conditionals in ConTeXt? I have two counters, \definenumber[words] and \definenumber[items]. I have tried to use TeX conditionals to compare them, e.g.:
\ifnum\getnumber[words]=\getnumber[items]
    This will print some text if the two counters have the same value.
fi

This does not work. How can I use TeX conditionals to compare two counters in ConTeXt?

A: \definenumber is a synonym for \definestructurecounter. You can use the expandable version \rawstructurecountervalue to get the value of the structure counter and use them in TeX conditionals.
An alternative is to use the commands.doifelse(...) lua function to do the comparison.
I present both versions below (using named arguments so that the macro is easy to understand. Either save this in a file with an extension .mkvi or use % macros=mkvi on the first line of the .tex file).
% macros=mkvi

\unprotect

\unexpanded\def\strc_helper_compare#if#else#operator#counterA#counterB%
    {\ctxcommand{doifelse(\rawstructurecountervalue[#counterA] #operator \rawstructurecountervalue[#counterB])}
        {#if}{#else}}

\unexpanded\def\doifelsecomparestructurecounter
    {\strc_helper_compare\firstoftwoarguments\secondoftwoarguments}

\unexpanded\def\doifcomparestructurecounter
    {\strc_helper_compare\firstofoneargument\gobbleoneargument}
\protect

\definestructurecounter[one]
\definestructurecounter[two]

\setstructurecounter[one][1]
\setstructurecounter[two][2]

\starttext
\ifnum\rawstructurecountervalue[one]>\rawstructurecountervalue[two]\relax
  One is bigger
\else
  Two is bigger
\fi

\doifelsecomparestructurecounter{>=}{one}{two}{Counter one is bigger}{Counter two is bigger}
\doifelsecomparestructurecounter{<}{one}{two}{Counter one is smaller}{Counter two is smaller}
\doifcomparestructurecounter{<}{one}{two}{Counter one is smaller}
\doifcomparestructurecounter{>}{one}{two}{Counter two is smaller}
\stoptext


text:
Q: Spring Java Config: PropertyPlaceholderConfigurer's "locations" equivalent I have a Spring boot application where i wan't to inject properties. In our previous projects we defined a PropertyPlaceholderConfigurer in our context.xml to load the property files from all dependent modules at once:
<bean id="propertyPlaceholderConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="ignoreResourceNotFound" value="true" />
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="locations">
            <list>
                <value>classpath:test.properties</value>
                <value>classpath*:/META-INF/*.properties</value>
            </list>
        </property>
    </bean>

Now I am looking for a worthy alternative in Java config style. I tried to annotate my configuration class as follows:
@PropertySources(value = { @PropertySource("classpath:application.properties"),
    @PropertySource("classpath*:/META-INF/*.properties") })

But the @PropertySource annotation doesn't like wildcards (which makes sense as it is responsible for fetching a single resource).
Any ideas, hints, solutions?

A: Ya, this is awkward as PropertySource doesnt support wildcards. A reasonable solution has been offered up on a previous question and I've used it successfully.
classpath wildcard in @PropertySource


text:
Q: Are there any other Narcissus-like characters Are there other Narcissus-like characters recorded in any mythology? To be more precise, I need a metaphor for an egoistic person who is in love with themself.
I need a proper noun, the name of this person, like Narcissus but somebody else.  I am not looking for common nouns like egoist, egomaniac, and such — only for proper nouns or personifications.

A: If you are looking for a proper noun,
Dorian Gray (not a mythological character) is the narcissistic protagonist of The Picture of Dorian Gray by Oscar Wilde.
Your metaphor could be "a Dorian Gray Personality" or "someone suffering from the Dorian Gray Syndrome".

A: Ovid' famous tale of Narcissus has for good reason long stood as unrivaled archetype for this. Guillaume de Lorris' unnamed first-person narrator in his section of The Romance of the Rose, usually termed "the Dreamer," is explicitly linked to Ovid's archetype, initially espying his lady-love, the perfect rose, reflected in Narcissus' watery mirror (so much does erotic infatuation often prove to be a kind of projection of self-love). I have found no parallel in Norse myth, though the tale of Óðinn's sacrificing an eye in Mímir's well (for wisdom, or in Wagner for Fricka) distinctly presages Guillaume's image of round crystal stones, representing eyes, sunk within the limpid water. I have found no parallel in Ojibwe myth either. It is worth noting, however, that intellectual vanity has sometimes been read as Eve's motive for partaking of the fruit of the tree of knowledge in the Hebrew myth of the Fall. The villainous matriarch in the tale of Snow White, with her peculiar relation to a mirror and her obsession with being "fairest," also merits mention here.

A: Willoughby Patterne, from Meredith's The Egoist, was created as an archetype for vanity and is sometimes used as such.


text:
Q: Why threads not switching? I want to get a file contains a letter from other files in random order. I must to do it with Threads. And I don't know why I have in output file content from 1 file, after it content from 2 file and after that content from 3 file. I have Main:
public static void main(final String[] args) throws Exception {
    for(int i=1;i<args.length; i++) {
        new Thread1( args[i], args[0]).start();
    }
}

And class Thread1:
public class Thread1 extends Thread {
    String path;
    FileWriter fw;
    private String desc;
    public Thread1( String path, String desc) {
        super();
        this.desc=desc;
        this.path=path;
    }

    @Override
    public void run() {
        FileReader f = null;
        try {
             f = new FileReader(path);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int c;
        try {
            fw = new FileWriter(desc, true);
            while((c = f.read()) != -1) {
                fw.write(c);
            }
            fw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Please, explain me, why it don't work in way, what I think it should be work.

A:
Please, explain me, why it don't work in way, what I think it should be work.

Your problem is that all of your threads are appending to the same file but using different FileWriter instances.  This sounds like it would work but they are all overwriting each other.  When you open a file for appending it opens it and positions the write marker at the end of the file.  When two threads do this, they both will be at the same marker.  If thread #1 writes a character then thread #2 will write a character and overwrite the first.
You could use a single FileWriter and share it with each of your threads.  Then you synchronize on it for mutex purposes and do the write.
public Thread1( String path, String desc, FileWriter fw) {
    this.fw = fw;
    ...
}
...
// when you write to it, you will need to synchronize on the writer
sychronized (fw) {
   fw.write(c);
}
// don't close it in the threads but close it later after you have joined with
// the threads

Another option is to share a PrintStream which is already synchronized internally.


text:
Q: Does lead or steel become radioactive when exposed to intense gamma ray? There is a similar question like this in the database but there are significant differences so I will attempt to post this.   The motivation is that I read a documentary that says some of the bulldozer's used in the Chernobyl clean up had to be entirely abandoned and buried on the spot.  I presume they dumped dirt and concrete from a helicopter on the bulldozer's.
Realizing there was most probably not only intense gamma rays but also intense neutron bombardment of the steel in the bulldozer I am wondering if the gamma rays had any play into this.
I can see how neutrons are able to do this with "induced radioactivity" although I don't quite understand if  the metal has transmuted or just briefly unstable. However , I  have a harder time seeing how high energy photons such as in gamma ray can interact with metals such as steel or possibly lead as another example.
Thank you

A: Yes it can but in low amounts due to the cross sections involved. The process is known as photodisintegration.  For heavy elements, like lead or iron, the gamma rays need an energy of 10 MeV or greater. You can read more about this and other references at [here.]  1 The reference for the 10 MeV limit is given in link as well.


text:
Q: Hibernate: overriding the (entity) superclass's OneToMany mapped field? Is it possible to make a subclass (entity) override a OneToMany mapping from its superclass (entity)?  Currently I'm getting "HibernateException: Found shared references to a collection", presumably because the superclass entity and subclass entity both link to the same list.
(My understanding is that @AssociationOverride can only be used when the superclass is @MappedSuperclass, not @Entity.  I do not want to change the superclass from @Entity to @MappedSuperclass, because I want the table for the superclass and the ability to query on it.)
How can I have Hibernate map something like the following?
@Entity
public abstract class PetOwner {
    @OneToMany(targetEntity = Pet.class, mappedBy = "owner")
    public <T extends Pet> List<T> getPets()
    ...
}

@Entity
public abstract class Pet {
    @ManyToOne(targetEntity = PetOwner.class)
    @JoinColumn(name = "owner_id", referencedColumnName = "id")
    public <T extends PetOwner> T getOwner()
    ...
}

@Entity
public class CatOwner extends PetOwner {
    @Override
    @OneToMany(targetEntity = Cat.class, mappedBy = "owner")
    public List<Cat> getPets()
    ...
}

@Entity
public class Cat extends Pet {
    @Override
    @ManyToOne(targetEntity = CatOwner.class)
    @JoinColumn(name = "owner_id", referencedColumnName = "id")
    public CatOwner getOwner()
    ...
}

A: In the end I marked the subclasses' getters (CatOwner.getPets() and Cat.getOwner()) with @Override @Transient.


text:
Q: Precise contour finding algorithm in Python My task at hand is finding specific contours in a cloud of points. They need to be determined as accurately as possible. Therefore higher order polynomial interpolation must be used. I have data consisting of points in a grid, each point having its own height.
I had great success finding contours with matplotlib.contours function. Then I directly used matplotlib.cntr (C++ algorithm) to determine specific contours. But because the file uses marching squares algorithm (linear interpolation) the precision of found contours is not good enough.
I am looking for alternative ways to solve this problem. A suggested solution was to

*

*Use bicubic interpolation to find analytical function around a specific point.

*Followed by calculation of the function derivative.

*Derived function is then used to determine direction in which derivative stays at 0 (using point as a point of view). By moving a small distance in that direction height should remain constant.

Using this algorithm a contour should be found. Would this algorithm work, can I take any shortcuts when implementing it (by using already implemented functions)?
Implementing this algorithm would take quite the effort on my part, and besides  it may only work in theory.  I am guessing that the numerical error should still be present (the derivative may not be exactly 0) and may in the end even surpass the current one (using marching squares). I want to consider other, easier and faster methods to solve this problem.
What other algorithm could be used to solve it?
Did anyone ever face a similar problem? How did you solve it?


text:
Q: How to visualize the result of data augmentation that we configured in pipeline.config of tensorflow model garden? I am training an object detection model out of the TensorFlow Model Garden (namely, 'http://download.tensorflow.org/models/object_detection/tf2/20200711/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8.tar.gz'). I configure my data augmentation in the pipline.config file. The full list of data augmentation options are in the preprocessor.proto under the tensorflow/models/research/object_detection/protos.
Here is my pipeline.config content:
model {
  ssd {
    num_classes: 2
    image_resizer {
      fixed_shape_resizer {
        height: 320
        width: 320
      }
    }
    feature_extractor {
      type: "ssd_mobilenet_v2_fpn_keras"
      depth_multiplier: 1.0
      min_depth: 16
      conv_hyperparams {
        regularizer {
          l2_regularizer {
            weight: 4e-05
          }
        }
        initializer {
          random_normal_initializer {
            mean: 0.0
            stddev: 0.01
          }
        }
        activation: RELU_6
        batch_norm {
          decay: 0.997
          scale: true
          epsilon: 0.001
        }
      }
      use_depthwise: true
      override_base_feature_extractor_hyperparams: true
      fpn {
        min_level: 3
        max_level: 7
        additional_layer_depth: 128
      }
    }
    box_coder {
      faster_rcnn_box_coder {
        y_scale: 10.0
        x_scale: 10.0
        height_scale: 5.0
        width_scale: 5.0
      }
    }
    matcher {
      argmax_matcher {
        matched_threshold: 0.5
        unmatched_threshold: 0.5
        ignore_thresholds: false
        negatives_lower_than_unmatched: true
        force_match_for_each_row: true
        use_matmul_gather: true
      }
    }
    similarity_calculator {
      iou_similarity {
      }
    }
    box_predictor {
      weight_shared_convolutional_box_predictor {
        conv_hyperparams {
          regularizer {
            l2_regularizer {
              weight: 4e-05
            }
          }
          initializer {
            random_normal_initializer {
              mean: 0.0
              stddev: 0.01
            }
          }
          activation: RELU_6
          batch_norm {
            decay: 0.997
            scale: true
            epsilon: 0.001
          }
        }
        depth: 128
        num_layers_before_predictor: 4
        kernel_size: 3
        class_prediction_bias_init: -4.6
        share_prediction_tower: true
        use_depthwise: true
      }
    }
    anchor_generator {
      multiscale_anchor_generator {
        min_level: 3
        max_level: 7
        anchor_scale: 4.0
        aspect_ratios: 1.0
        aspect_ratios: 2.0
        aspect_ratios: 0.5
        scales_per_octave: 2
      }
    }
    post_processing {
      batch_non_max_suppression {
        score_threshold: 1e-08
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 100
        use_static_shapes: false
      }
      score_converter: SIGMOID
    }
    normalize_loss_by_num_matches: true
    loss {
      localization_loss {
        weighted_smooth_l1 {
        }
      }
      classification_loss {
        weighted_sigmoid_focal {
          gamma: 2.0
          alpha: 0.25
        }
      }
      classification_weight: 1.0
      localization_weight: 1.0
    }
    encode_background_as_zeros: true
    normalize_loc_loss_by_codesize: true
    inplace_batchnorm_update: true
    freeze_batchnorm: false
  }
}
train_config {
  batch_size: 4
random_horizontal_flip {
      keypoint_flip_permutation: 1
      keypoint_flip_permutation: 0
      keypoint_flip_permutation: 2
      keypoint_flip_permutation: 3
      keypoint_flip_permutation: 5
      keypoint_flip_permutation: 4
      probability: 0.5
    }
  }
data_augmentation_options {
    random_vertical_flip {
      keypoint_flip_permutation: 1
      keypoint_flip_permutation: 0
      keypoint_flip_permutation: 2
      keypoint_flip_permutation: 3
      keypoint_flip_permutation: 5
      keypoint_flip_permutation: 4
      probability: 0.5
    }
  }

  data_augmentation_options {
    normalize_image{
      original_minval: 0.0
      original_maxval: 255.0
      target_minval: -1.0
      target_maxval: 1.0
    }
  }

  data_augmentation_options {
    random_image_scale{
       min_scale_ratio: 0.8
        max_scale_ratio: 2.2
    }
  }
  sync_replicas: true
  optimizer {
    momentum_optimizer {
      learning_rate {
        cosine_decay_learning_rate {
          learning_rate_base: 0.08
          total_steps: 50000
          warmup_learning_rate: 0.026666
          warmup_steps: 1000
        }
      }
      momentum_optimizer_value: 0.9
    }
    use_moving_average: false
  }
  fine_tune_checkpoint: "C:/Users/abukwah/source/repos/Edge_Detection/Tensorflow/workspace/pre-trained-models/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8/checkpoint/ckpt-0"
  num_steps: 50000
  startup_delay_steps: 0.0
  replicas_to_aggregate: 8
  max_number_of_boxes: 100
  unpad_groundtruth_tensors: false
  fine_tune_checkpoint_type: "detection"
  fine_tune_checkpoint_version: V2
}
train_input_reader {
  label_map_path: "C:/Users/Katzoos/source/repos/Edge_Detection/Tensorflow/workspace/annotations/label_map.pbtxt"
  tf_record_input_reader {
    input_path: "C:/Users/Katzoos/source/repos/Edge_Detection/Tensorflow/workspace/annotations/train.record"
  }
}
eval_config {
  metrics_set: "coco_detection_metrics"
  use_moving_averages: false
}
eval_input_reader {
  label_map_path: "C:/Users/Katzoos/source/repos/Edge_Detection/Tensorflow/workspace/annotations/label_map.pbtxt"
  shuffle: false
  num_epochs: 1
  tf_record_input_reader {
    input_path: "C:/Users/Katzoos/source/repos/Edge_Detection/Tensorflow/workspace/annotations/test.record"
  }
}

My question is how can I visualize the results of the data augmentation that is part of the training pipeline? And can I see it after the training is done (is saved somewhere) or should I edit the code in the Tensorflow\models\research\object_detection\model_main_tf2.py file?
I am using Tensorflow 2.10.0, Python 3.9.15, CUDA 11.2, CuDNN 8.1.
I tried to find answers on the Tensorflow Model Garden documentation and couldn't find answer to my question.


text:
Q: .Net Distributed Cache like MongoDB Is there any library/ framework/ distributed cache solution that operates like MongoDB's replication does?
That is it synchronizes data between the nodes pretty quickly and in case of failure the system automatically elects a new master so there is little to no downtime.
I need something that will give all nodes which are C# applications (about 5) ,the same data and replicates changes quickly between them so they are always consistent.
Aside from MongoDB anyone knows anything else out there that does this? or behaves somewhat similar?


text:
Q: Pushpad: subscribe prompt only showed up the first time a user clicks on enable button on chrome Hello,
I already checked the answers from the question PushPad: Subscribe is removed after site refresh, but it did not help me.
I created a subscribe/unsubscribe button, following the doc, and the prompt is showing up on Firefox each time i click on the subscribe button so i guess my flow is correct but i don't understand why it's not working on Chrome => the prompt is only showing the first time i launch Chrome.
Here is what i do
pushpad('init', #projectID);
var pushId = $("#main").data("pushid");
var pushSig = $("#main").data("pushsig");

var updateButton = function (isSubscribed) {
    var btn = $('#activate-push-notif');
    if (isSubscribed) {
        btn.html('Unsubscribe');
        btn.addClass('subscribed');
    } else {
        btn.html('Subscribe');
        btn.removeClass('subscribed');
    }
};
// check whether the user is subscribed to the push notifications and
// initialize the button status (e.g. display Subscribe or Unsubscribe)
pushpad('status', updateButton);

// when the user clicks the button...
$('#activate-push-notif').on('click', function (e) {
    e.preventDefault();

    // if he wants to unsubscribe
    if ($(this).hasClass('subscribed')) {
        pushpad('unsubscribe', function () {
            updateButton(false);
        }, {
            uid: pushId,
        });

        // if he wants to subscribe
    } else {
        // try to subscribe the user to push notifications
        pushpad('subscribe', function (isSubscribed) {
            if (isSubscribed) {
                updateButton(true);
            } else {
                updateButton(false);
                alert('You have blocked notifications from your browser preferences.');
            }
        }, {
            uid: pushId,
            uidSignature: pushSig
        });
    }
});

Thanks for your help to figure it out.

A: *

*Make sure that you wrap all your code inside $(function () { ... }, so that your code is run when the page is fully loaded, otherwise your click handler may not work properly.

*Probably the point is that when you see the Firefox prompt you click "Not now" (instead of "Never allow" which is hidden under the ▼ menu). That is why you can see the prompt multiple times. In other browsers, like Chrome, the default option is "Block" (which is a permanent block, like "Never allow").

*When the user blocks the notifications you cannot display the browser prompt again, due to browser restrictions... however there are some alternative solutions. For example you can display a custom prompt as many times as you want, and then display the browser prompt only if the user says yes to your custom prompt. See this example. Otherwise you can display a prompt only to users who have blocked the notifications, asking to unblock the notifications. See this example. Another option is to display a button in the page to allow the users to subscribe to notifications when they decide to do that.


text:
Q: Xcode 7 beta 5, Swift 2: UITableViewCell's subviews are not added to the contentView at runtime Following phenomena happens when using Xcode 7 beta 5 and Swift 2:
When using a custom UICollectionViewCell that is created in the storyboard, the cell's subviews are not added to the cell's contentView. Thus the cell remains blank on runtime.
If I however create a custom cell class for the cell and then programmatically add the subviews to the contentView and set their frame the cell's content is displayed:
class Cell : UITableViewCell {

    @IBOutlet weak var label: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

        NSLog("subiews.count=%d", contentView.subviews.count) // prints "0"

        contentView.subviews.count
        contentView.addSubview(label)

        label.frame = CGRect(x: 0, y: 0, width: 200, height: 21)
    }
}

Again, without manually adding the label (that has been added in the storyboard!) and setting its frame, it would not be visible at runtime! In the storyboard the label is a subview of the content view. At run time it is not.
I cannot observe this behavior in latest Xcode 6 with Swift 1.2.
Can somebody confirm this silly behavior? And maybe provide an easier workaround?
Edit:
Luckily view constraints on the cell's subviews are applied after these views have been added programmatically to contentView. Thus at least manually setting their frames is not necessary.

A: There is a similar question here UITableView Empty with iOS 9 beta 5 update
And my answer for it https://stackoverflow.com/a/32052154/2674336
I can't say if this is a universal solution, but in the exact same scenario (tablviewcell content empty at runtime after updating to XCode 7 beta 5) this solved it for me:
I had to go through every single item inside the content view (including all constraints) and tick the checkbox "Installed" in the properties inspector. Initially only wR hR was checked.


text:
Q: displaying output from command prompt in JTextArea I am trying to direct cmd output for tshark -i <interface> (wireshark utility) to JTextArea in a java program . I tried an alternate way,like storing output from the prompt to a text file and then opening the file in the program with FileInputStream / BufferedInputStream. But this does not work as the output is real time(data is displayed according to transaction over interface) and I want the data to be displayed in the JTextArea on real time basis. Since, the file cannot be read until it is completely written and closed the program gives me FileNotFoundException. The code fragment may give you a better insight to what I'm trying to do.
public void controlfunc(int n) {
/*
this is the complete function that takes the serial number of adapter as input,
then runs a command that starts tshark for listening on the adapter
and saves output to prec file
*/
String input = JOptionPane.showInputDialog(null, "Please enter the device
serial number you want to start listening to ?", "Record manager Query",QUESTION_MESSAGE);
int id = Integer.parseInt(input);
    //send id value to a batch file for processing with tshark...
    try {
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec("powershell.exe TSHARK -i " + id + " >> C:\\Users\\HP\\Documents\\response\\Server_Analyser\\src\\server_analyser\\sreverdump\\prec");
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, "Error in processing command !\nCheck Software Integrity !", "FATAL ERROR OCCURED !", ERROR_MESSAGE);
        e.printStackTrace();
}
// I need your help here. I cannot open this file and display data in real time. Any other approach is welcomed.
    //get output data from prec to text area output...
    try {
        int ch;
        FileInputStream fin = new FileInputStream("C:\\Users\\HP\\Documents\\response\\Server_Analyser\\src\\server_analyser\\sreverdump\\prec");
        BufferedInputStream bin = new BufferedInputStream(fin);
        while ((ch = bin.read()) != -1) {
            report.append("" + (char) ch);
        }
/*
There is a stop button that sends 0 as argument to the function and the
code closes the file as no more data is to be read and kills the tshark
process that was running.
*/
        if (n == 0) {
            bin.close();
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec("powershell.exe killproc tshark.exe");
        }

    } catch (FileNotFoundException fe) {
        JOptionPane.showMessageDialog(null, "Source file is corrupted or lost !");
    } catch (IOException ex) {
        Logger.getLogger(recordman.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, "The program has encountered an IOException !", "record manager Error ", ERROR_MESSAGE);
    }
}

I'm sorry if this is exaggerating. Also pardon me for my english.


text:
Q: Downgrade Python version in virtual environment I am always getting the same error regarding TensorFlow:
ModuleNotFoundError: No module named 'tensorflow.contrib'.
I am actually using Python version 3.9 but, reading online, it seems that version 3.7 is the last stable one that can work with TensorFlow version >2.0.
Unfortunately I have started my project in a venv with the wrong version of Python and I would like to downgrade it, how can I do that?

A: There's the venv --upgrade <ENV_DIR> command, but it's mainly intended to update between patch versions (e.g. from 3.9.15 to 3.9.16).
You'll need extra steps to update between different minor versions. Let me walk you through it.
Assuming you have both versions of Python installed:
$ python3.9 --version
Python 3.9.16
$ python3.7 --version
Python 3.7.16

And that your environment was created using version 3.9, and it's in a venv subdirectory:
$ . venv/bin/activate
$ python --version
Python 3.9.16
$ deactivate

Use these commands to downgrade from 3.9 to 3.7:
$ python3.7 -m venv --upgrade venv
$ cd venv/bin
$ ln -sf python3.7 python
$ ln -sf python3.7 python3
$ rm {python,pip}3.9
$ cd -

Here's the result:
$ . venv/bin/activate
$ python --version
Python 3.7.16

A: tf.contrib is deprecated from the latest version of TensorFlow 2.x and is replaced with TF Slim.
It is recommended to use the upgraded version of TensorFlow to have the benefit of the latest features and functionalities provided by TensorFlow.
However, To downgrade python

*

*You need to uninstall the existing python version and re-install the required python version and set up your environment.

*If you are using Anaconda IDE, then use the below command:

conda search python  #to check available python version
conda install python=<version>

conda create --name <env_name> python=<python_version> # Which also creates virtual environment
activate <env_name>

Please check this link for more details.


text:
Q: How to visualize counts of different categories Suppose we have $10$ boxes and we are interested in measuring the number of apples, oranges and pears in each. What is a good way to visualize how the boxes relate to each other in terms of the distribution of fruits? For example, box 1 might have 5 apples, 10 oranges, and 6 pears while box 10 might have 1 apple, 1 orange and 1 pear.
Added. Is looking at a distance matrix appropriate? Is there a way to visualize a distance matrix?

A: What about a spineplot? That way you can simultaneously display both the differences in proportions per box and differences in the size of the boxes. Your example with two boxes would look like this:

A: I agree broadly with Maarten, as a click on his link will imply, but other answers are possible.
Note first that many people would regard a spineplot as just a special case of a mosaic plot. Programs or functions in your favourite software are perhaps more likely to use the second term.
That said, a good old-fashioned bar chart or (Cleveland) dot chart can work as well here as anything else, although some designs are better than others. In particular, stacked (divided) bar charts divide the world: some love them, some hate them.
Pie charts? Just say no.
Yet further, your question leaves open quite what you want your graph to show. Do you want to emphasise frequencies or to emphasise proportions or (quite reasonably) to have it both ways? The spineplot implementation in Stata used by Maarten can show absolute numbers as well as conveying the fractional breakdown, and that's surely a standard feature in other environments.


text:
Q: Cleaning up a parent theme and creating a child theme. We are in the process of creating a child theme for a theme that is being used: Ultimo. A number of customisations were made to the parent theme which should have been made to a child theme. We do not have a comprehensive list of those changes.
Is there a means of comparing the Original files of the theme and the customised theme to highlight the changes so that we can transfer these across from parent to child theme?
Thanks

A: So there are a few ways of doing this.

*

*Simply commit the original unchanged version to some form of source control and then make your changes and the source control software should highlight the changes.

*Using a magerun plugin from Kalen Jordan. This will allow you to specify two themes and then the output will be the differences between the two themes.


text:
Q: How to pass multiple arguments in a JAX-RS method using JSON-B provider I have a service class exposed through JAX-RS using JSON-B as the provider for (de)serialization, all wired using CDI. The environment is a Jakarta/Java EE 8 (Java SE 8) server (e.g. Wildfly 22):
@RequestScoped
public class PersonService {

   public Long addPerson(String name, Pet pet, Country bornCountry) {
      //Pet and Country are custom classes that may be annotated with JSON-B annotations.
   }
}

@RequestScoped
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@Path("/PersonService")
public class PersonServiceRS {

   @Inject
   private PersonService personService;

   @POST
   @Path("/addPerson")
   public Response addPerson(AddPersonParameters parameters) {
      return Response
         .ok(personService.addPerson(
            parameters.name,
            parameters.pet,
            parameters.bornCountry
         ))
         .build();
   }
}

public class AddPersonParameters {

   public String name;
   public Pet pet;
   public Country bornCountry;

   public AddPersonParameters() { this(null, null, null); }

   public AddPersonParameters(String name, Pet pet, Country bornCountry) {
      this.name = name;
      this.pet = pet;
      this.bornCountry = bornCountry;
   }
}

Using the JAX-RS Client API, the call to the service is something like this:
response = client
   .target("...")
   .request(APPLICATION_JSON)
   .post(Entity.json(new AddPersonParameters(
      aName,
      aPet,
      aBornCountry
   )));

Because JAX-RS has no automatic (de)composing of multiple arguments, I have to declare the class AddPersonParameters just to be a wrapper of the arguments of the method and satisfy JSON-B automatic (de)serialization.
A: Is there any way to avoid the argument wrapper class AddPersonParameters definition?
Suppose a JsonEntity custom general class similar in usage to a Map<String, Object> that could be used like this:
//Service
public Response addPerson(JsonEntity parameters) {
   return Response
      .ok(personService.addPerson(
         parameters.get(String.class, "name"),
         parameters.get(Pet.class, "pet"),
         parameters.get(Country.class, "bornCountry")
      ))
      .build();
}

//Client
response = client
   .target("...")
   .request(APPLICATION_JSON)
   .post(Entity.json(new JsonEntity() {
      {
         add("name", aName),
         add("pet", aPet),
         add("bornCountry", aBornCountry)
      }
   }));

B: How could JsonEntity be implemented in such a way it fulfills JSON-B?
NOTE: I know REST practitioners would say this is too RPC stylish ;)


text:
Q: zsh is not finding my php executable I'm using zsh on my Ubuntu VPS.
When I try to find version
php -v
zsh: command not found: php

and my php executable somehow got into
whereis php
php: /usr/share/php

How can I point it to right path?

A: export PATH=$PATH:/usr/share/php/bin

Add this to your .zshrc (assuming /usr/share/php/bin is the directory in which the php binary lives).

A: Ho you have to over write all commands to zsh
try this
PATH=/bin:/usr/bin:/usr/local/bin:${PATH}
export PATH

A: Just reinstall PHP and overwrite any previous installation with this:
brew link --overwrite php


text:
Q: Model works perfectly but GridSearch causes error While working on a project I have come across a weird error, where fitting my model works perfectly but when I apply gridsearch it gives me an error.
The code puts all the necessary objects created and uses them in the pipeline.
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV
import pandas as pd
import numpy as np
import time
from numpy.fft import fft

class DataPreprocess(BaseEstimator, TransformerMixin):
    def __init__(self):
        pass
    def fit(self, X, y=None):
        self.X_m = X.merge(y, on= ['year', 'weekofyear'])

        return self

    def transform(self, X):
        dt = pd.to_datetime(self.X_m["week_start_date"], format="%Y-%m-%d")
        unix = []
        for i in dt:
            unix.append(time.mktime(i.timetuple()))
        X_t = (self.X_m).reset_index().assign(date = unix).set_index(['date'])

        return X_t

class FourierComponents(BaseEstimator, TransformerMixin):
    """creat features based on sin(2*pi*f*t) and cos(2*pi*f*t)"""
    def __init__(self, n=10):
        self.n = n

    def fit(self, X, y= None):
        self.labels = X['total_cases']

        self.Y_t = fft(self.labels - (self.labels).mean())
        self.Y_t = self.Y_t[:len(self.labels)//2]

        self.ind_max = np.abs(self.Y_t).argsort()

        self.t_span = len(self.labels)

        self.f = np.linspace(0, len(self.Y_t), len(self.Y_t)) / self.t_span

        self.f_ind = self.f[self.ind_max]

        self.ind = pd.RangeIndex(start = 1, stop=(len(X.index.get_level_values('date')) +1)).values.reshape(-1, 1)

        return self

    def transform(self, X):

        Xt = np.zeros((X.shape[0], 2*len(self.f_ind[-self.n:])))

        for i, f in enumerate(self.f_ind[-self.n:]):
            Xt[:, 2*i]     = np.cos(2*np.pi*f*self.ind).reshape(-1)
            Xt[:, 2*i + 1] = np.sin(2*np.pi*f*self.ind).reshape(-1)

        return Xt

Unixdata = DataPreprocess()
fourier = FourierComponents()

model = Pipeline([
    ('indices', Unixdata),
    ('fourier', fourier),
    ('scalar', StandardScaler()),
    ('regressor', Ridge())
])

param_grid = {'fourier__n' : list(range(3,5)),
              'regressor__alpha' : np.logspace(1, 4, 20)}

grid_search = GridSearchCV(model, param_grid, cv = 5, verbose = 1, scoring='neg_mean_absolute_error')

grid_search.fit(sj_train_features, sj_train_labels)

fitting the grid_search here gives me this error:
    Fitting 5 folds for each of 40 candidates, totalling 200 fits
[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-167-cfce20172a59> in <module>
----> 1 grid_search.fit(sj_train_features, sj_train_labels)

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in inner_f(*args, **kwargs)
     71                           FutureWarning)
     72         kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 73         return f(**kwargs)
     74     return inner_f
     75

~\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in fit(self, X, y, groups, **fit_params)
    734                 return results
    735
--> 736             self._run_search(evaluate_candidates)
    737
    738         # For multi-metric evaluation, store the best_index_, best_params_ and

~\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in _run_search(self, evaluate_candidates)
   1186     def _run_search(self, evaluate_candidates):
   1187         """Search all candidates in param_grid"""
-> 1188         evaluate_candidates(ParameterGrid(self.param_grid))
   1189
   1190

~\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in evaluate_candidates(candidate_params)
    706                               n_splits, n_candidates, n_candidates * n_splits))
    707
--> 708                 out = parallel(delayed(_fit_and_score)(clone(base_estimator),
    709                                                        X, y,
    710                                                        train=train, test=test,

~\anaconda3\lib\site-packages\joblib\parallel.py in __call__(self, iterable)
   1027             # remaining jobs.
   1028             self._iterating = False
-> 1029             if self.dispatch_one_batch(iterator):
   1030                 self._iterating = self._original_iterator is not None
   1031

~\anaconda3\lib\site-packages\joblib\parallel.py in dispatch_one_batch(self, iterator)
    845                 return False
    846             else:
--> 847                 self._dispatch(tasks)
    848                 return True
    849

~\anaconda3\lib\site-packages\joblib\parallel.py in _dispatch(self, batch)
    763         with self._lock:
    764             job_idx = len(self._jobs)
--> 765             job = self._backend.apply_async(batch, callback=cb)
    766             # A job can complete so quickly than its callback is
    767             # called before we get here, causing self._jobs to

~\anaconda3\lib\site-packages\joblib\_parallel_backends.py in apply_async(self, func, callback)
    206     def apply_async(self, func, callback=None):
    207         """Schedule a func to be run"""
--> 208         result = ImmediateResult(func)
    209         if callback:
    210             callback(result)

~\anaconda3\lib\site-packages\joblib\_parallel_backends.py in __init__(self, batch)
    570         # Don't delay the application, to avoid keeping the input
    571         # arguments in memory
--> 572         self.results = batch()
    573
    574     def get(self):

~\anaconda3\lib\site-packages\joblib\parallel.py in __call__(self)
    250         # change the default number of processes to -1
    251         with parallel_backend(self._backend, n_jobs=self._n_jobs):
--> 252             return [func(*args, **kwargs)
    253                     for func, args, kwargs in self.items]
    254

~\anaconda3\lib\site-packages\joblib\parallel.py in <listcomp>(.0)
    250         # change the default number of processes to -1
    251         with parallel_backend(self._backend, n_jobs=self._n_jobs):
--> 252             return [func(*args, **kwargs)
    253                     for func, args, kwargs in self.items]
    254

~\anaconda3\lib\site-packages\sklearn\model_selection\_validation.py in _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score, return_parameters, return_n_test_samples, return_times, return_estimator, error_score)
    558     else:
    559         fit_time = time.time() - start_time
--> 560         test_scores = _score(estimator, X_test, y_test, scorer)
    561         score_time = time.time() - start_time - fit_time
    562         if return_train_score:

~\anaconda3\lib\site-packages\sklearn\model_selection\_validation.py in _score(estimator, X_test, y_test, scorer)
    605         scores = scorer(estimator, X_test)
    606     else:
--> 607         scores = scorer(estimator, X_test, y_test)
    608
    609     error_msg = ("scoring must return a number, got %s (%s) "

~\anaconda3\lib\site-packages\sklearn\metrics\_scorer.py in __call__(self, estimator, *args, **kwargs)
     85         for name, scorer in self._scorers.items():
     86             if isinstance(scorer, _BaseScorer):
---> 87                 score = scorer._score(cached_call, estimator,
     88                                       *args, **kwargs)
     89             else:

~\anaconda3\lib\site-packages\sklearn\metrics\_scorer.py in _score(self, method_caller, estimator, X, y_true, sample_weight)
    210                                                  **self._kwargs)
    211         else:
--> 212             return self._sign * self._score_func(y_true, y_pred,
    213                                                  **self._kwargs)
    214

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in inner_f(*args, **kwargs)
     71                           FutureWarning)
     72         kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 73         return f(**kwargs)
     74     return inner_f
     75

~\anaconda3\lib\site-packages\sklearn\metrics\_regression.py in mean_absolute_error(y_true, y_pred, sample_weight, multioutput)
    176     0.85...
    177     """
--> 178     y_type, y_true, y_pred, multioutput = _check_reg_targets(
    179         y_true, y_pred, multioutput)
    180     check_consistent_length(y_true, y_pred, sample_weight)

~\anaconda3\lib\site-packages\sklearn\metrics\_regression.py in _check_reg_targets(y_true, y_pred, multioutput, dtype)
     82
     83     """
---> 84     check_consistent_length(y_true, y_pred)
     85     y_true = check_array(y_true, ensure_2d=False, dtype=dtype)
     86     y_pred = check_array(y_pred, ensure_2d=False, dtype=dtype)

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in check_consistent_length(*arrays)
    254     uniques = np.unique(lengths)
    255     if len(uniques) > 1:
--> 256         raise ValueError("Found input variables with inconsistent numbers of"
    257                          " samples: %r" % [int(l) for l in lengths])
    258

ValueError: Found input variables with inconsistent numbers of samples: [188, 748]

but
model.fit(sj_train_features, sj_train_labels)

fits perfectly.
Now I am wondering why and where is the mistake in the code?
Can anyone point me in the right direction?
A small example (hopefully representative):
sj_train_features = pd.DataFrame({
    'year': [1990] * 10,
    'weekofyear': np.arange(18, 28),
    'week_start_date': pd.date_range('1990-04-30', periods=10, freq='w'),
    'ndvi_ne': np.random.random(10),
    'station_precip': np.random.random(10)*10,
}).set_index(['year', 'weekofyear'])

sj_train_labels = pd.Series(np.random.random(10)*20, index=sj_train_features.index, name='total_cases')

A: A little more than halfway through your traceback, you see a snippet from _fit_and_score, which indicates that the fitting has succeeded, but that scoring is what fails.  Indeed, when I call model.predict, I always get out the same length array as the training set.  When comparing that against the true labels then, the scorer correctly complains that the number of predictions does not match the number of labels.
I don't entirely understand what your FourierComponents is supposed to do, but I think its transform method needs to pay attention to the time index.


text:
Q: Vast data replacement between two tables in Oracle Assume that we have two tables, named Tb1 and Tb2 and we are going to replace data from one to another. Tb1 is the main source of data and Tb2 is the Destination. This replacement operation has 3 parts.
In the first part we are going to validate all rows in Tb1 and check if they are correct. For example National security code must exactly have 10 digits or a real customer must have a valid birth date so according to these validation rules, 28 different validation methods and error codes have been considered. During the validation every spoiled row's description and status will be updated to a new state.
Part 2 fixes the rows' problems and the third one replace them to the Tb2.
For instance this row says that it has 4 different error.

-- Tb1.desc=6,8,14,16
  -- Tb1.sts=0

A correct row of data

-- Tb1.desc=Null  i
  -- Tb1.sts=1

I have been working on the first part recently and have come up with a solution which works fine but it is too slow. Unfortunately It takes exactly 31 minutes to validate 100,000 rows. In a real situation we are going to validate more than 2 million records so it is totally useless despite all it's functionality.
Let's take look at my package :
procedure Val_primary IS
      begin
        Open X_CUSTOMER;
              Loop
                fetch X_CUSTOMER bulk collect into CUSTOMER_RECORD;
                EXIT WHEN X_CUSTOMER%notfound;
                For i in CUSTOMER_RECORD.first..CUSTOMER_RECORD.last loop
                Val_CTYP(CUSTOMER_RECORD(i).XCUSTYP);
                Val_BRNCH(CUSTOMER_RECORD(i).XBRNCH);

                --Rest of the validations ...

                UptDate_Val(CUSTOMER_RECORD(i).Xrownum);
                end loop;
                CUSTOMER_RECORD.delete;
              End loop;
         Close X_CUSTOMER;
      end Val_primary;

Inside a validation procedure :
procedure Val_CTYP(customer_type IN number)IS
  Begin
    IF(customer_type<1 or customer_type>3)then
      RW_FINAL_STATUS:=0;
      FINAL_ERR_DSC:=Concat(FINAL_ERR_DSC,ERR_INVALID_CTYP);
    End If;
  End Val_CTYP;

Inside the update procedure :
procedure UptDate_Val(rownumb IN number) IS
  begin
    update tb1 set tb1.xstst=RW_FINAL_STATUS,tb1.xdesc=FINAL_ERR_DSC where xc1customer.xrownum=rownumb;
    RW_FINAL_STATUS:=1;
    FINAL_ERR_DSC:=null;
  end UptDate_Val;

Is there any way to reduce execution time ?
It must be done less than 20 minutes for more than 2 million records.

A: Maybe each validation check could be a case expression within an inline view, and you could concatenate them etc in the enclosing query, giving you a single SQL statement that could drive an update. Something along the lines of:
select xxx, yyy, zzz  -- whatever columns you need from xc1customer
     , errors  -- concatenation of all error codes that apply
     , case when errors is not null then 0 else 1 end as status
from   ( select xxx, yyy, zzz
              , trim(ltrim(val_ctyp||' ') || ltrim(val_abc||' ') || ltrim(val_xyz||' ') || etc...) as errors
         from   ( select c.xxx, c.yyy, c.zzz
                       , case when customer_type < 1 or customer_type > 3 then err_invalid_ctyp end as val_ctyp
                       , case ... end as val_abc
                       , case ... end as val_xyz
                  from   xc1customer c
                )
       );

Sticking with the procedural approach, the slow part seems to be the single-row update. There is no advantage to bulk-collecting all 20 million rows into session memory only to apply 20 million individual updates. The quick fix would be to add a limit clause to the bulk collect (and move the exit to the bottom of the loop where it should be), have your validation procedures set a value in the array instead of updating the table, and batch the updates into one forall per loop iteration.
You can be a bit freer with passing records and arrays in and out of procedures rather than having everything a global variable, as passing by reference means there is no performance overhead.

A: There are two potential lines of attack.

*

*Specific implementation. Collections are read into session memory. This is usually quite small compared to global memory allocation. Reading 100000 longish rows into session memory is a bad idea and can cause performance issues. So breaking up the process into smaller chunks (say 1000 rows) will most likely improve throughput.

*General implementation. What is the point of the tripartite process? Updating Table1 with some error flags is an expensive activity. A more efficient approach would be to apply the fixes to the data in the collection and apply that to Table2. You can write a log record if you need to track what changes are made.

Applying these suggestion you'd end up with a single procedure which looks a bit like this:
procedure one_and_only is
begin
    open x_customer;
    << tab_loop >>
    loop
        fetch x_customer bulk collect into customer_record
            limit 1000;
        exit when customer_record.count() = 0;
        << rec_loop >>
        for i in customer_record.first..customer_record.last loop
            val_and_fix_ctyp(customer_record(i).xcustyp);
            val_and_fix_brnch(customer_record(i).xbrnch);

            --rest of the validations ...

        end loop rec_loop;

        -- apply the cleaned data to target table
        forall j in 1..customer_record.count()
            insert into table_2
            values customer_record(j);
     end loop tab_loop;
    close x_customer;
end one_and_only;

Note that this approach requires the customer_record collection to match the projection of the target table. Also, don't use %notfound to test for end of the cursor unless you can guarantee the total number of read records is an exact multiple of the LIMIT number.


text:
Q: Lock Master Article when translation in progress I am working on Lightning Knowledge. I need to lock the master article when translation is in progress. I am able to do so using After Update Trigger and Approval.Lock() method. However, the message displayed when we try to edit master article is

'The record is currently locked'

Is there any way we can customize this message?


text:
Q: Location based redirect using .htaccess Is it possible to perform redirect only on a specific list of IPs using .htaccess? What I am trying to do is redirect all traffic from one country to another domain and no redirection for every others. Is it possible to do that using .htaccess?

A: You can but it might be complicated for some countries with many ranges.
A simple example is North Korea unique IP range 175.45.176.0 – 175.45.179.255:
RewriteCond %{REMOTE_ADDR} ^175\.45\.17[6-9]\.[0-9]+$
RewriteRule ^(.*)$ http://www.google.com/ [L,R=301]

It would be easier to use a local library like ip2location and do the redirection in your code.


text:
Q: Hide a string in a txt file? I plan to hide bulm+mNtdeWE/P7ccZzg=w=n. Where ? In a txt file, but not in the content, nor in the extra attributes.
I did it on OSX 10+ and Windows 7, with respective processes. Now I am trying this by using Ubuntu.
Maybe naive, I think of hiding in into the file bits, somewhere outside of the content part and the attributes part. But I dont manage to find any doc' about file Unix skeleton nor Ubuntu software...
How can I hide text into a text file this way?

A: SNOW (package stegsnow) can do this by appending whitespace to the end of lines.


text:
Q: Opera redirect problem Hi everyone i have a problem like this.
For example im in http://localhost/Search.aspx
I have 2 textboxes (txtUserName and txtPassword) in my page for login.
user can press enter key to call Login() method when any of these textboxes focused.
I capture enter key like this
txtUserName.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {Login();return false;}} else {return true}; ");
txtPassword.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {Login();return false;}} else {return true}; ");

Its calling the Login() method, and After doing that method Opera redirects the page to my default page (http://localhost/Default.aspx)
Other browsers is working as it should, in other words they are not redirect me to the default page.
Opera version 10.61

A: Alright, so you're problem here is Opera (bless it) doesn't support the onKeyDown command very well - so you have to look at onKeyUp or onKeyPress instead.  There's a really handy HTML table on quirksmode explaining this.
Given you're only trying to trap a control key onKeyUp is probably your best bet.  I've been forced to combine onKeyDown and onKeyPress in order to catch text input AND control keys (but since you want text input to work as normal you don't need to go this far).
It should be simply a matter of switching "onkeydown" to "onkeyup" in your example fragment.
There is, perhaps, a question of why you'd be doing the above.  I don't know what Login() does, but building a form with 3 parts (input-text, input-password, and input-submit button) will -by default- submit the form when enter is pressed in either of the input boxes, you could just add an onSubmit event to the form calling Login();


text:
Q: Phonegap StatusBar notifications on closed Application I am creating a simple app thats only job is to inform the user if something has changed(something in the database). If something is changed the user gets a status bar notification.
I am using this plugin: https://github.com/katzer/cordova-plugin-local-notifications/tree/example.
It works perfectly if lets say I update database something manually from the application. But this wont be the way in the future. Is it possible to achieve this?
For example a user is not using the app at the moment and his wifi is offline. At that time I change something in the database. When the user turns the wifi on, he should get the news that something has been updated. Is this possible to do with phonegap?
Do I need to create some script? But how to execute it if the app is not being used?