text:
Q: ImportError when importing scipy.stats, undefined symbol (scipy version 0.14.0) I just upgraded to Scipy 0.14.0 and Ubuntu 14.04. Now when I try to import stats I get an ImportError.
import scipy.stats as stats

Traceback (most recent call last):
  File "/home/user1/Documents/test/importTest/importScipy.py", line 1, in <module>
    import scipy.stats as stats
  File "/usr/local/lib/python2.7/dist-packages/scipy/stats/__init__.py", line 334, in <module>
    from .stats import *
  File "/usr/local/lib/python2.7/dist-packages/scipy/stats/stats.py", line 181, in <module>
    import scipy.special as special
  File "/usr/local/lib/python2.7/dist-packages/scipy/special/__init__.py", line 548, in <module>
    from .basic import *
  File "/usr/local/lib/python2.7/dist-packages/scipy/special/basic.py", line 17, in <module>
    from . import orthogonal
  File "/usr/local/lib/python2.7/dist-packages/scipy/special/orthogonal.py", line 90, in <module>
    from scipy import linalg
  File "/usr/local/lib/python2.7/dist-packages/scipy/linalg/__init__.py", line 159, in <module>
    from .misc import *
  File "/usr/local/lib/python2.7/dist-packages/scipy/linalg/misc.py", line 5, in <module>
    from . import blas
  File "/usr/local/lib/python2.7/dist-packages/scipy/linalg/blas.py", line 145, in <module>
    from scipy.linalg import _fblas
ImportError: /usr/local/lib/python2.7/dist-packages/scipy/linalg/_fblas.so: undefined symbol: clange_

A: Installing from source solved the issue.
First download the numpy and scipy tarballs.
Then locate the BLAS and LAPACK *.so files on my machine. I found them in /usr/lib/. If they are not there you can install them. I used the standard Ubuntu finder to locate them:
find -iname 'libblas.so'
find -iname 'liblapack.so'

So I set some environment variables for the installation.
export BLAS=/usr/lib/libblas.so
export LAPACK=/usr/lib/liblapack.so

Then I downloaded the source tarballs of numpy and scipy, untarred the tarball and then installed by cd into the install directories and
python setup.py build
sudo python setup.py install

NOTE: You may want to specify the install directory.
Comments welcome. Perhaps there is a better way.

A: The problem is related to Scipy missing proper reference to LAPACK. I followed the instructions suggested by @jtorca and found that you don't even need to install via tarballs. For me, the following did the trick:
apt-get install libopenblas-dev liblapack-dev
export BLAS=/usr/lib/libblas.so
export LAPACK=/usr/lib/liblapack.so
pip install numpy
pip install scipy


text:
Q: Mounting network drives with Terminal in OSX 10.12 / Sierra I just updated to OSX 10.12 / Sierra.
Usually when I reboot my computer, I run the following in a script to mount my network drives:
mount -t afp afp://user:password@10.1.1.10/SKYDEDAGE /Volumes/SKYDEDAGE2015

This has always worked. However after updating to OSX 10.12 / Sierra, this command no longer works. In the script I run, Prior to using the mount command, I make a directory/mountpoint in 'Volumes'. The command still doesn't work, even though the directory/mountpoint exists.
I get this error code:
mount_afp: AFPMountURL returned error 1, errno is 1

Any ideas why this aren't working anymore?

A: Just in case anyone else stumbles over this question and needs a solution, in OS X 10.12, you can use "open":
open smb://<user>:<password>@server/<Volume>

The extra step with creating the folder in /Volumes can be omitted

A: this worked for me:
mount -t smbfs //user@10.1.1.10/SKYDEDAGE   /Volumes/SKYDEDAGE2015

I prefer to enter passwords manually
macOS Sierra 10.12.6

A: This is probably because around Sierra, Apple changed /Volumes so that it was no longer globally readable or writeable.
You have to create a mount folder with sudo, and mount with sudo:
sudo mkdir -p /Volumes/mount && sudo mount -t AFP afp://user:pass@redlantern.apple.com/mount /Volumes/mount

You can also use:
open smb://<user>:<password>@server/<Volume>

But that will prompt the user, so won't work in in a startup script.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not getting the relevant output in my 32-bit ALU using gate-level verilog code Below is the code for 32 bit ALU with 3 different modules with their individual codes as well. I am not getting any warning now but I am also not getting the expected 32-bit output as shown in the figure below. No changes can be made in the stimulus as that is pre-defined. Below I am attaching the image of the ALU as well as the image of the output screen I am getting on running in the Xilinx.
       module shifter(
   output [31:0]   shifted_y
  ,input  [4:0]    x, Const_amount, const_var
  ,input  [31:0]   y
  ,input           shift_direction
);
wire [4:0] amount, m, n;

assign m = Const_amount & const_var;
assign n = x && const_var;
assign amount = m || n;

assign shifted_y = (shift_direction == 1'b1) ? y << amount : y >> amount ;

endmodule

module fulladd(ss, cc, a, b, c);
output ss, cc;
input a, b, c;
wire s1, c1, c2;

//logic gates
xor (s1, a, b);
and (c1, a, b);
xor (ss, s1, c);
and (c2, s1, c);
or (cc, c2, c1);

endmodule

//////////////////32-bit adder/subtractor/////////////
module adder_sub (ss, cc, a, b, c);
output cc;
output [31:0] ss;
input[31:0] a, b;
input c;
wire [30:0] d;
wire [31:0] t;

//instantiate and logic gates
xor x0(t[0], b[0], cc);
fulladd as0(ss[0], d[0], a[0], t[0], c);

xor x1(t[1], b[1], cc);
fulladd as1(ss[1], d[1], a[1], t[1], d[0]);

xor x2(t[2], b[2], cc);
fulladd as2(ss[2], d[2], a[2], t[2], d[1]);

xor x3(t[3], b[3], cc);
fulladd as3(ss[3], d[3], a[3], t[3], d[2]);

xor x4(t[4], b[4], cc);
fulladd as4(ss[4], d[4], a[4], t[4], d[3]);

xor x5(t[5], b[5], cc);
fulladd as5(ss[5], d[5], a[5], t[5], d[4]);

xor x6(t[6], b[6], cc);
fulladd as6(ss[6], d[6], a[6], t[6], d[5]);

xor x7(t[7], b[7], cc);
fulladd as7(ss[7], d[7], a[7], t[7], d[6]);

xor x8(t[8], b[8], cc);
fulladd as8(ss[8], d[8], a[8], t[8], d[7]);

xor x9(t[9], b[9], cc);
fulladd as9(ss[9], d[9], a[9], t[9], d[8]);

xor x10(t[10], b[10], cc);
fulladd as10(ss[10], d[10], a[10], t[10], d[9]);

xor x11(t[11], b[11], cc);
fulladd as11(ss[11], d[11], a[11], t[11], d[10]);

xor x12(t[12], b[12], cc);
fulladd as12(ss[12], d[12], a[12], t[12], d[11]);

xor x13(t[13], b[13], cc);
fulladd as13(ss[13], d[13], a[13], t[13], d[12]);

xor x14(t[14], b[14], cc);
fulladd as14(ss[14], d[14], a[14], t[14], d[13]);

xor x15(t[15], b[15], cc);
fulladd as15(ss[15], d[15], a[15], t[15], d[14]);

xor x16(t[16], b[16], cc);
fulladd as16(ss[16], d[16], a[16], t[16], d[15]);

xor x17(t[17], b[17], cc);
fulladd as17(ss[17], d[17], a[17], t[17], d[16]);

xor x18(t[18], b[18], cc);
fulladd as18(ss[18], d[18], a[18], t[18], d[17]);

xor x19(t[19], b[19], cc);
fulladd as19(ss[19], d[19], a[19], t[19], d[18]);

xor x20(t[20], b[20], cc);
fulladd as20(ss[20], d[20], a[20], t[20], d[19]);

xor x21(t[21], b[21], cc);
fulladd as21(ss[21], d[21], a[21], t[21], d[20]);

xor x22(t[22], b[22], cc);
fulladd as22(ss[22], d[22], a[22], t[22], d[21]);

xor x23(t[23], b[23], cc);
fulladd as23(ss[23], d[23], a[23], t[23], d[22]);

xor x24(t[24], b[24], cc);
fulladd as24(ss[24], d[24], a[24], t[24], d[23]);

xor x25(t[25], b[25], cc);
fulladd as25(ss[25], d[25], a[25], t[25], d[24]);

xor x26(t[26], b[26], cc);
fulladd as26(ss[26], d[26], a[26], t[26], d[25]);

xor x27(t[27], b[27], cc);
fulladd as27(ss[27], d[27], a[27], t[27], d[26]);

xor x28(t[28], b[28], cc);
fulladd as28(ss[28], d[28], a[28], t[28], d[27]);

xor x29(t[29], b[29], cc);
fulladd as29(ss[29], d[29], a[29], t[29], d[28]);

xor x30(t[30], b[30], cc);
fulladd as30(ss[30], d[30], a[30], t[30], d[29]);

xor x31(t[31], b[31], cc);
fulladd as31(ss[31], cc, a[31], t[31], d[30]);

endmodule

module logic(
   output      out
  ,input       p, q
  ,input [1:0] s
);

  wire ns0, ns1;
  wire w0,w1,w2,w3;
  wire t1,t2,t3,t4;

  and  u_gate_inst_0(t1,p,q);
  or   u_gate_inst_1(t2,p,q);
  xor  u_gate_inst_2(t3,p,q);
  nor  u_gate_inst_3(t4,p,q);

  not u_mux_inst_0 (ns0, s[0]);
  not u_mux_inst_1 (ns1, s[1]);
  and u_mux_inst_2 (w0 , t1, ns0 , ns1   );
  and u_mux_inst_3 (w1 , t2, ns1 , s[0]  );
  and u_mux_inst_4 (w2 , t3, ns0 , s[1]  );
  and u_mux_inst_5 (w3 , t4, s[0], s[1]  );
  or  u_mux_inst_6 (out, w0, w1, w2, w3);

endmodule

module logic_unit(
    output [31:0] out
   ,input  [31:0] p,q
   ,input  [1:0]  s
);

 logic logic_m1 [31:0] (out,p,q,s);

endmodule

module mux32bit(i0, i1, i2, sel, muxout);
input [31:0] i0, i1, i2;
input [1:0] sel;
output [31:0] muxout;
reg [31:0] muxout;

always @ (i0 or i1 or i2 or sel)

    begin
     case (sel)
     2'b00: muxout = i0;
     2'b01: muxout = i1;
     2'b10: muxout = i1;
     2'b11: muxout = i2;
     default: muxout = 2'bx;
     endcase
   end
endmodule

//--------stimulu/s module
// The ALU module name and orders of inputs, outputs should be same as the ALU module in the following
module ALU_32bits(output [31:0] s, input [31:0] a, b, input c_0,
input Const_Var, shift_direction, input [1:0] Function_class, input [1:0] Logic_function, input [4:0] Const_amount);

wire [31:0] adder_out, shifter_out, logic_out;
wire [4:0] const_var;
wire [1:0] sel;

mux32bit mux_output(shifter_out, adder_out, logic_out, sel, s);
shifter shifter_output(shifter_out, a[4:0], Const_amount[4:0], const_var[4:0], b, shift_direction);
adder_sub adder_sub_output(adder_out, cc, a, b, c);
logic_unit logic_output(logic_out, a, b, s[1:0]);

endmodule

module stimulus;

//inputs
reg[31:0] A,B;
reg C_0,Const_Var,shift_direction;
reg [1:0] Function_class;
reg [1:0] Logic_function;
reg [4:0] Const_amount;

//outputs
wire[31:0] s;

ALU_32bits my_ALU (s,  A, B,  C_0, Const_Var, shift_direction, Function_class, Logic_function, Const_amount);

initial
begin

$monitor($time,"A=%d, B=%d, C_IN=%b,-- Function_class=%d, shift_direction=%b, Const_Var=%b, Const_amount=%d, shift_direction=%b, Logic_function=%d,--OUTPUT=%d \n",A,B,C_0,Function_class,shift_direction,Const_Var,Const_amount,shift_direction,Logic_function,s);
end

initial
begin
A=4'd0; B=4'd0; C_0=1'b0;
#5 A=8'd19; B=8'd55; Function_class[1]=1; Function_class[0]=0;
#5 A=8'd59; B=8'd168;C_0=1'b1; Function_class[1]=0; Function_class[0]=1;
#5 A=8'd39; B=8'd136; C_0=1'b1;  Function_class[1]=1; Function_class[0]=0;
#5 A=16'd9; B=8'd112; Function_class[1]=0; Function_class[0]=0; shift_direction=1; Const_Var=1;

#5 A=16'd129; B=16'd456;Function_class[1]=0; Function_class[0]=0;shift_direction=0;Const_Var=0;Const_amount=5'd7;
#5 A=16'd656; B=8'd218; C_0=1'b0;Function_class[1]=1; Function_class[0]=1;Logic_function=2'd0;
#5 A=8'd195; B=8'd228; C_0=1'b1;Function_class[1]=1; Function_class[0]=1;Logic_function=2'd1;
#5 A=8'd99; B=16'd286; C_0=1'b1;Function_class[1]=1; Function_class[0]=1;Logic_function=2'd2;
#5 A=8'd77; B=16'd486; C_0=1'b0;Function_class[1]=1; Function_class[0]=1;Logic_function=2'd3;
end

endmodule

Image of ALU

Image of the output

A: If you can't modify the stimulus code, you can lookup your working version of Xilinx ISE or Vivado user manual, you didn't mention the platform you are using, on how to turn off warning flags for truncation. Note that the truncation will still happen, but you only won't be notified for it.

A: one thing can i say , in the elaborated design from the code you have provided observing many top ports are not connected to lower level modules.Please fix those connection issues and revert back the code so someone in the community can help you. please use Ansi-C style of verilog ports and named port connection while instantiating the modules ,this type of coding style will be helpful for any modification, readability and to understand the code at a single glance.


text:
Q: list.files not showing text files with capital letter names? I have the below code for retrieving text files from a specific folder on my computer:
MenthueFolder<-list.files(path = path.source, recursive = TRUE, pattern = "\\.txt$")

path.source is already specified to my working directory. The recursive part tells R to search through all subfolders until it finds .txt files (which is the pattern specification).
My name text files are in two formats: name##.txt and NAME##.txt.
I have managed to retrieve all lower case named text files but I cannot get the capital letter ones. Does anyone know if there is a parameter in the function I have to specify?
Thank you for all the help!

A: Answer: specify ignore.case=TRUE such as:
MenthueFolder<-list.files(path = path.source, recursive = TRUE, pattern = "\\.txt$", ignore.case = TRUE)


text:
Q: viewpager + webview, how to  stop webview loading Hi,
I have created an app that uses ViewPager and all pages contain WebViews.
Every Webview contains server images, videos, mp3 ...
The WebView settings are
      public Object instantiateItem(View collection, int position) {
            .
            .
            .

            final RelativeLayout imageLayout  = (RelativeLayout)
            inflater.inflate(R.layout.omb_webview_layout, null);
            WebView webview = (WebView) imageLayout.findViewById(R.id.video_view);
            ProgressBar pbImage = (ProgressBar) imageLayout.findViewById(R.id.progressBar1);

            webview.requestFocus(View.FOCUS_DOWN);
            webview.getSettings().setBuiltInZoomControls(false);
            webview.getSettings().setSupportZoom(true);
            webview.getSettings().setUseWideViewPort(true);
            webview.getSettings().setJavaScriptEnabled(true);
            webview.getSettings().setLoadWithOverviewMode(true);
            webview.getSettings().setUseWideViewPort(true);
            webview.setWebViewClient(new mWebViewClient());
            webview.getSettings().setPluginsEnabled(true);
            webview.clearCache(true);
            webview.clearHistory();
            if(Pbar != null) {
                webview.setWebChromeClient(new WebChromeClient() {
                 public  void onProgressChanged(WebView view, int progress)     {
                  Log.i(TAG, "webview loading progress : "+ progress);
                    if(progress == 100) {
                        try {
                            Pbar.setVisibility(ProgressBar.GONE);
                        } catch (Exception e) {
                        Log.e(TAG, "timer progress GONE : "+ progress,e);
                        }
                         }
            });
            }

The problem is when pages are swiped then also this line
 Log.i(TAG, "webview loading progress : "+ progress);

is executing which means that webviews are loading in background.
If I swipe 4 or more pages all webviews are loading.
     destroyItem(View collection, int position, Object o) {
    Log.d("DESTROY", "destroying view at position sheetal " + position);

            RelativeLayout view = (RelativeLayout)o;

                    WebView tmp = webviewDictionary.get(position);;

            tmp.getSettings().setJavaScriptEnabled(false);
                            tmp.stopLoading();
        if(tmp != null){
                        Log.i(TAG, "sheetal webview is destroyed " +position );
                        try {
                            tmp.onPause();

                            tmp.loadDataWithBaseURL("about:blank", "","text/html", "UTF-8", null);
                            tmp=null;
                            //  tmp.destroy();
                        }
                        catch (Exception e) {
                            Log.i(TAG, "webview destroyed Exception 0" ,e);
                        }
                    }

How to stop background loading if the pages are not visible? setOffscreenPageLimit(1)(means 3 page prev,cur,next),
In Viewpager, 2 page (means 1 position page) is not loading properly. It shows a blank white page, how do I solve it?
Thanks in advance

A: this solved my problem.
i have created a dictionary, it contains 3 webview with position as key.
here i am adding webviews in dictionary
public Object instantiateItem(View collection, int position) {
    .
    .
    .
    webviewDictionary.put(position, webView);
    .
    .
    .
}

cleaning webviews is from dictionary
public void cleanAllWebViews() {

    try {

        if(webviewDictionary != null){

            Iterator<Integer> webViewIterator = webviewDictionary.keySet().iterator();

            while(webViewIterator.hasNext()) {

                Integer key=(Integer)webViewIterator.next();

                WebView webView = (WebView) webviewDictionary.get(key);

                webView.stopLoading();
                //                  webView.pauseTimers();

                webView.setWebChromeClient(null);
                webView.setWebViewClient(null);

                webView.loadDataWithBaseURL("about:blank", "","text/html", "UTF-8", null);
                webViewIterator.remove();

            }
        }

        webviewDictionary = null;

    }catch (Exception e) {
        Log.e(TAG, "ombook last call onPauseAllWebviews  Exception",e  );
    }
}

    and

    @Override
public void onBackPressed() {

    cleanAllWebViews();

    System.gc();

    super.onBackPressed();
}

A: have you tried "OffscreenPageLimit" set to 1 ? 0 is an invalid value according to this post:
ViewPager.setOffscreenPageLimit(0) doesn't work as expected
also , have you tried to handle some events of switching between the pages , so that each time you switch a page , the current page's webview will stop loading , or start loading an empty html file?


text:
Q: How update plugins in android studio? I ran my android project after almost a week and I got this message:

Plugin is too old, please update to a more recent version, or set
  ANDROID_DAILY_OVERRIDE environment variable to
  "a8faa180fc282060c9b8ec88f9bdcc9072121284"

How do I update my Plugins? I am using android Studio 2.0. Here is my build.gradle project file
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.0.0-alpha1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

A: Change com.android.tools.build:gradle:2.0.0-alpha1 to com.android.tools.build:gradle:2.0.0-alpha3 which is the latest version.

A: Open your IDE. Open a project. Then look for the following:
If you are using Windows you go to Help -> Check for updates
If you are using Mac, you go to Android Studio (next to the Mac symbol, in the top left) -> Check for updates
Alternatively when you launch your SDK Manger, it automatically searches for updates to your plugins. Navigate to SDK Tools.

A: UDPATE (may-2016)
update to lastest
dependencies {
    classpath 'com.android.tools.build:gradle:2.1.0'
  }

You can specify the Gradle version in either the File > Project Structure > Project menu in Android Studio, or by editing the Gradle distribution reference in the gradle/wrapper/gradle-wrapper.properties file
distributionUrl = https\://services.gradle.org/distributions/gradle-2.10-all.zip

check gradle revisions

The Android Gradle Plugin and Gradle
 Android Gradle Plugin    Requires Gradle
 1.0.0 - 1.1.3     2.2.1 - 2.3
 1.2.0 - 1.3.1     2.2.1 - 2.9
 1.5.0     2.2.1+
 2.*   2.10+

check answer for update gradle

A: Change the line
classpath 'com.android.tools.build:gradle:2.0.0-alpha1'
to a latest version like
classpath 'com.android.tools.build:gradle:2.0.0-alpha3
(latest version at the moment of answering)


text:
Q: How to convert a JSON string to an image? I have an application that converts an image to a JSON array and I'm saving it into a blob field:
function getImage(): String;
var
  memorystream : TMemoryStream;
  jsonArray    : TJSONArray;

begin
  memorystream := TMemoryStream.Create;
  myImage.Picture.Graphic.SaveToStream(memorystream);
  memorystream.Position := 0;

  jsonArray := TJSONArray.Create;
  jsonArray := TDBXJSONTools.StreamToJSON(memorystream, 0, memorystream.Size);

  memorystream.Free;

  Result := jsonArray.ToString;
end;

The result of the convertion of a PNG image looks like this:
[137,80,78,71,13,10,26,10,0,0, ... ]

This result is stored in a blob field that I get back with this code:
stream := TStream.Create;
stream := cdsPesquisa.CreateBlobStream(fieldAux, bmRead);
stream.Position := 0;

jsonArray := TJSONArray.Create;
jsonArray := TDBXJSONTools.StreamToJSON(stream, 0, stream.Size);

Here, I have the same JSON string [137,80,78,71,13,10,26,10,0,0, ... ] at the beginning, but I need to convert this JSON array into an image again.
How can I achieve that?

A: As suggested by Ken, it's simplest to forget all about JSON and write directly to the blob field.
Saving
Stream := TMemoryStream.Create;
try
  myImage.Picture.Graphic.SaveToStream(Stream);
  Stream.Position := 0;
  fieldAux.LoadFromStream(Stream);
finally
  Stream.Free;
end;

Loading
Stream := TMemoryStream.Create;
try
  fieldAux.SaveToStream(Stream);
  Stream.Position := 0;
  myImage.Picture.Graphic.LoadFromStream(Stream);
finally
  Stream.Free;
end;

You appear insistent in the comments that JSON is what you need. I'm find that a little hard to believe. But anyway, to convert from your JSON array, held in a string, to an image, do this:
jsonArray := TJSONObject.ParseJSONValue(jsonString) as TJSONArray;
try
  Stream := TDBXJSONTools.JSONToStream(jsonArray);
  try
    Stream.Position := 0;
    myImage.Picture.Graphic.LoadFromStream(Stream);
  finally
    Stream.Free;
  end;
finally
  jsonArray.Free;
end;

Also, to the best of my knowledge, your code that calls TDBXJSONTools.StreamToJSON does not work. It yields an empty JSON array object.

Finally, your code was leaking like a sieve. You are under the mis-apprehension that you don't need to free objects that you create. You also are mistakenly instantiating objects and then overwriting the new object with a different object, thus leaking the first. Take a look at how I created objects, and compare with your code. For example:
jsonArray := TJSONArray.Create ;
jsonArray := TDBXJSONTools.StreamToJSON( memorystream , 0 , memorystream.Size ) ;

Here you instantiate a TJSONArray object and store a reference to that object in jsonArray. It is your job to free that reference. But you immediately abandon that reference in the next line when you overwrite it with the reference to the new object returned by StreamToJSON. Since you never free jsonArray at all you leak not one, but two objects.
You do need to brush up your basic understanding of Delphi lifetime management.


text:
Q: Join repeats records? I have tables in the database that are related. The (RT) has four lines that relate to the other four lines (t.b) The query is realized by means of a (user.id) that exists in both tables.
The problem happens in the query return that repeats over 12 lines? How can I deal with this error? Below is the code and link:
  public function planstypes_head($elev_opename_id) {
$this->db->select('*');
$this->db->from('elev_plans_types');
$this->db->join('elev_share_plans', 'elev_share_plans.elev_opename_id = elev_plans_types.elev_opename_id' , 'left');
$this->db->where('elev_plans_types.elev_opename_id', $elev_opename_id);
$query = $this->db->get();
return $query->result(); }

Follows the layout of the tables


text:
Q: are combinatorics-leaning mathematicians very good at mental math? a common cliché in movies is that mathematicians who specialize in combinatorics are very adept at mental math (arithmetic), is that a real thing? if yes why?

A: I think the reason for that is that combinatorics is one of the easiest to understand disciplines to a non-mathematician. If people start talking about Galois extensions of splitting fields of whatever, no one knows what's going on. However, combinatorial problems are often easy to understand. That doesn't mean that they are easy to solve, not at all, but the problem can be explained in terms known to a wide audience.
I would guess whenever a movie wants to show a "genius mathematician", they take combinatorics, because there people can actually understand the problem, notice that they have no idea how to solve it, and then maybe even understand part of the solution presented. It has nothing to do with higher intellect in combinatorists.


text:
Q: Automate script to run linear regression R I am looking to run Linear Regression on the below data frame.
test<-data.frame(abc=c(2.4,3.2,8.9,9.8,10.0,3.2,5.4),
             city1_0=c(5.3,2.6,3,5.4,7.8,4.4,5.5),
             city1_1=c(2.3,5.6,3,2.4,3.6,2.4,6.5),
             city1_2=c(4.2,1.4,2.6,2,6,3.6,2.4),
             city1_3=c(2.4,2.6,9.4,4.6,2.5,1.2,7.5),
             city1_4=c(8.2,4.2,7.6,3.4,1.7,5.2,9.7),
             city2_0=c(4.3,8.6,6,3.7,7.8,4.7,5.8),                               city2_1=c(5.3,2.6,3,5.4,7.8,4.4,5.5))

Dataframe "test" is sample of the data. But original data frame contains 100 columns. I want to create a script for predicting values using linear regression. In this case, I want to build many models with different input variables.
For example, in the given dataframe, abc is the y variable. I want to build one model
city1_1,city1_2,city1_3,city1_4 (leaving city1_0, city2_0). Then other model with city1_2,city1_3,city1_4 (leaving city1_0,city1_1,city2_0,city2_1)
and then 3rd model with input variable city1_3,city1_4 (leaving city1_0,city1_1,city1_2,city2_0,city2_1), and so on.
These all variables are input to the Linear Regression.
This I have to do for 40 dataframes. O/P variable name remains same for every dataframe.


text:
Q: How to crop the image on opencv and dlib on ubuntu I want to do these on the opencv and dlib using c++ on ubuntu.

*

*Detect the human face using dlib.(I did it already.)

*crop the image of only around mouth part.

here is my code. it is base on dlib sample code.
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include <dlib/image_io.h>
#include <iostream>
#include <opencv2/opencv.hpp>
#include <highgui.h>

using namespace dlib;
using namespace std;

// ----------------------------------------------------------------------------------------

int main(int argc, char** argv)
{
    try
    {
        // This example takes in a shape model file and then a list of images to
        // process.  We will take these filenames in as command line arguments.
        // Dlib comes with example images in the examples/faces folder so give
        // those as arguments to this program.
        if (argc == 1)
        {
            cout << "Call this program like this:" << endl;
            cout << "./face_landmark_detection_ex shape_predictor_68_face_landmarks.dat faces/*.jpg" << endl;
            cout << "\nYou can get the shape_predictor_68_face_landmarks.dat file from:\n";
            cout << "http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2" << endl;
            return 0;
        }

        // We need a face detector.  We will use this to get bounding boxes for
        // each face in an image.
        frontal_face_detector detector = get_frontal_face_detector();
        // And we also need a shape_predictor.  This is the tool that will predict face
        // landmark positions given an image and face bounding box.  Here we are just
        // loading the model from the shape_predictor_68_face_landmarks.dat file you gave
        // as a command line argument.
        shape_predictor sp;
        deserialize(argv[1]) >> sp;
    cv::Mat cimg = cv::imread(argv[1]);

        image_window win, win_faces;
        // Loop over all the images provided on the command line.
        for (int i = 2; i < argc; ++i)
        {
            cout << "processing image " << argv[i] << endl;
            array2d<rgb_pixel> img;
            load_image(img, argv[i]);
/*
            // Make the image larger so we can detect small faces.
            pyramid_up(img);
*/
            // Now tell the face detector to give us a list of bounding boxes
            // around all the faces in the image.
            std::vector<rectangle> dets = detector(img);
            cout << "Number of faces detected: " << dets.size() << endl;

            // Now we will go ask the shape_predictor to tell us the pose of
            // each face we detected.
            std::vector<full_object_detection> shapes;
            for (unsigned long j = 0; j < dets.size(); ++j)
            {
                full_object_detection shape = sp(img, dets[j]);
                cout << "number of parts: "<< shape.num_parts() << endl;
                cout << "pixel position of first part:  " << shape.part(0) << endl;
                cout << "pixel position of second part: " << shape.part(1) << endl;
                // You get the idea, you can get all the face part locations if
                // you want them.  Here we just store them in shapes so we can
                // put them on the screen.
                shapes.push_back(shape);
            }

        // Crop the original image to the defined ROI */
        cv::Rect roi;
        roi.x = 0;
        roi.y = 0;
        roi.width = 200;
        roi.height = 200;

        cv::Mat crop = cimg(roi);
        cv::imshow("crop", crop);

            // Now let's view our face poses on the screen.
/*
            win.clear_overlay();
            win.set_image(img);
            win.add_overlay(render_face_detections(shapes));

            // We can also extract copies of each face that are cropped, rotated upright,
            // and scaled to a standard size as shown here:
            //dlib::array<array2d<rgb_pixel> > face_chips;
            //extract_image_chips(img, get_face_chip_details(shapes), face_chips);
            //win_faces.set_image(tile_images(face_chips));
*/

            cout << "Hit enter to process the next image..." << endl;
            cin.get();
        }
    }
    catch (exception& e)
    {
        cout << "\nexception thrown!" << endl;
        cout << e.what() << endl;
    }
}

but it gives me this error.
OpenCV Error: Assertion failed (0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows) in Mat, file /home/bigadmin/opencv-3.1.0/modules/core/src/matrix.cpp, line 508

exception thrown!
/home/bigadmin/opencv-3.1.0/modules/core/src/matrix.cpp:508: error: (-215) 0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows in function Mat

please teach me the solution to solve this issue.
thanks.

A: You have many errors in your code:

*

*cv::Mat cimg = cv::imread(argv[1]); - argv[1] is detector file, not image - you will get empty image, thats why your program crashes

*you are not iterating through images. try something like this:
for (int i = 2; i < argc; ++i)
{
    cout << "processing image " << argv[i] << endl;
    cv::Mat cvimg = cv::imgread(argv[i]);
    dlib::cv_image<rgb_pixel> img(cvimg);
...

Here you will read file only once and will be able to detect faces

*you should specify cropping region based on face detector function (and even better - based on shape predictor)
...
std::vector<rectangle> dets = detector(img);

here each item in dets is a rectangle, describing face, you can crop like this:
dlib::rectangle r = dets[j];
cv::Rect roi(r.left(), r.top(), r.width(), r.height());
cv::Mat face = cvimg(roi);

But it will be the full face image. If you want to crop only mouth, you should use shape predictor's output (didn't tested - please check if compile well):
full_object_detection shape = sp(img, dets[j]);
auto mouth_left = shape.part(45);
auto mouth_right = shape.part(54);
unsigned long mouth_width = (mouth_right - mouth_left).length();
double padding = 0.2;
cv::Rect roi(mouth_left.x() - mouth_width * padding, mouth_left.y() - mouth_width*0.5, mouth_width * (1 + padding * 2), mouth_width);
cv::Mat mouth = cvimg(roi);

This will produce unaligned image of mouth


text:
Q: TNT field solver - howto handle 'air' between ground plane and wire? I'd like to match the impedance on one of my PCB traces.
For this I chose to use TNT Field Solver.
Suppose that the trace itself looks like this (trace width currently set to 0.8128mm = 812.8 micron):

If I use the TNT like this:

It will iterate the trace width to match 50 Ohms, but in this case trace width is recommended to be 3082 micron (>3 mm) which is really huge so I think this is not the right way to do this.
Now I can add a GND plane also to the top like this, but how can I handle the 'air' between the trace and the top GND plane?
I have 2 questions here:
1.) How can I insert 'air' between the trace and the GND plane? (obviously it is not air, but there is no metallic conductor there)
2.) How to include vias in this calculation?

Update:
I've included now the ground stiching and the top-layer ground plane, however ground plane fills between the stiching and the signal wire which is not correct. For ground planes it is not possible to set the width or position, so I would need to do something around the red circles here:

A: A rough rule of thumb is that a 50 Ohm microstrip will be close to the same width as its distance to the reference plane. So your simulation isn't that surprising.
You can reduce the microstrip width by choosing a thinner board, or using top copper fills as you show in your question. The copper needs to be close to the microstrip to have an effect. And it needs to be well stitched to ground. Google "coplanar waveguide".
A 4-layer board will give you a much closer reference plane :)
As far as TNT, try this: to your cross-section, add "New Rectangle Conductors" and name them "groundWires" (the capitalization is intentional, but don't use the quotes). Then, in the details, choose number=2 and adjust the spacing accordingly. The spacing won't be intuitive :)


text:
Q: IntelliJ Unit Tests throw scalac: Output directory not specified I am running into a weird error with my IntelliJ setup for Scala. When I try to run any Unit Test for my project, I get the below error.
scalac: Output directory not specified for ...

From Maven, I am able to successfully run the tests. No issues there.
To ensure my Scala setup is correct, I created a simple HelloWorld scala project and I am able to successfully add a unit test and run it from IntelliJ.
I am running into this error only for my project repo that I downloaded from Git. Any suggestions on how I can identify what I am missing in the setup?
Things I tried so far:

*

*I ensured that my Java and Maven version in IntelliJ matches what I have on my Mac

*I tried deleting the .idea folder, "invalidate caches and restart". No luck after any of these.

➜  ~ mvn -version
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: /Users/syncmaster/.asdf/installs/maven/3.6.3
Java version: 11.0.14.1, vendor: Azul Systems, Inc., runtime: /Users/syncmaster/.asdf/installs/java/zulu-11.54.25/zulu-11.jdk/Contents/Home


text:
Q: Clear then restore List in zedGraph I designed a real time graph application using zedGraph class RollingPointPairList(). User should be able to hide specific curve when checkBox is checked and show it when unchecked.
The problem is that it never shows a curve again once it had been hidden. Actually, it should show curve with all points which were hide, but it draws straight line & drops specific points from list. How to do it correctly?
This is a sample code I'm using:
if (chkXScale.Checked == true) {
    zedGraphControl1.GraphPane.CurveList[0].Clear();
        zedGraphControl1.Refresh();
}

A: i Guess by calling zedGraphControl1.GraphPane.CurveList[0].Clear(); the data is removed so once you try to bring it back by checking the checkBox it finds no data to Draw !
i suggest that by the time you acquire data do 2 things:

*

*Draw it in your zeGraph control list.Add(x,y);

*Save the data for later use (in case you uncheck/check).

To save the data for late use you can choose any simple way you master, i just suggest using Queue As follows, so the whole operation becomes:
//declaration:
Queue<double> Xholder = new Queue<double>();
Queue<double> Yholder = new Queue<double>();
//when new data comes:
list.Add(x,y);
Xholder.Enqueue(x);
Yholder.Enqueue(y);

//when you uncheck then check the checkBox
for (int i=0; i<Xholder.Count; i++)
{
  list.Add(Xholder.Dequeue(), Yholder.Dequeue());
}

I hope that's all what you need, give me feedback when you try it


text:
Q: Could anyone explain the use of "would" in this sentence
I imagine it would taste mighty good.

Why does this sentence use "would" and not will?

A: It's a question of certainty. "will" implies certainty. In a short timespan you are certainly going to find out that it tastes mighty fine. You Will.
But here the narrator is less certain. He is imagining the food or drink, and there is less certainty. It is possible that it doesn't match his imagination, or that they can't get the ingredients, maybe the store is almost closed?
So: (if all circumstances line up and everything goeds right) I imagine it would tast mighty good.


text:
Q: Postgres - How to fetch escaped data from table The solution seems to be simple but I am finding it hard to get around. In the table, the sample data is as:
 id   |               name               |        created_time
 -------+----------------------------------+----------------------------
41477 | women''s hostels                 | 2016-03-24 13:52:52.855116
41476 | women''s hostels                 | 2016-03-24 13:52:49.895482
41475 | women''s hostels                 | 2016-03-24 13:52:49.735788
41471 | men''s hostel                    | 2016-03-24 13:52:42.907983
41469 | women''s clothing shops          | 2016-03-24 13:52:30.666364

I have inserted this data using PHP's PDO prepared statements so the single quotes have been escaped properly.
Now I want to fetch the records where name exactly matches

women's hostels

I want to accomplish this in both ways using raw SQL query and through PDO. I am trying following for both cases, but not getting any result:
Raw SQL:
SELECT id FROM <TABLE> where name = 'women''s hostels';
SELECT id FROM <TABLE> where name ilike 'women''s hostels';
SELECT id FROM <TABLE> where name::text = 'women''s hostels';

PDO:
$data = "women''s hostels";
$sql = "SELECT id FROM <TABLE> where name=?"; (tried all variations as above)
$stmt->execute(array($data));
$rows = $stmt->fetchAll();

The name field is defined in table as below:
Column    |            Type             |
name      | character varying(255)      |

Please help. Let me know if anything else is needed. Any help will be appreciated.

A: There should be no escaped data in database in the first place.

I have inserted this data using PHP's PDO prepared statements so the single quotes have been escaped properly.

They have been not.
Were they escaped properly, you'd have the original string in database, "women's hostels". But as you have your data in database escaped, it means that escaping occurred twice.
So you have to hunt down and remove that superfluous escaping during insert.
Then select whatever data usual way. It makes no difference whether you have quotes in it or not.


text:
Q: Exception in thread "main" java.lang.NoSuchMethodError. What's the problem? Error log:
Exception in thread "main" java.lang.NoSuchMethodError: 'com.google.common.collect.ImmutableMap com.google.common.collect.ImmutableMap.of(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object)'
    at org.openqa.selenium.chrome.AddHasCasting.getAdditionalCommands(AddHasCasting.java:38)
    at org.openqa.selenium.chrome.ChromeDriver$ChromeDriverCommandExecutor.getExtraCommands(ChromeDriver.java:98)
    at org.openqa.selenium.chrome.ChromeDriver$ChromeDriverCommandExecutor.<init>(ChromeDriver.java:93)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:81)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:49)
    at org.example.lesson3.SeleniumStart.main(SeleniumStart.java:12)

My POM
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>selenium_start</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>selenium_start</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
    </dependency>
    <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
      <version>4.10.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-report-plugin</artifactId>
      <version>3.0.0-M7</version>
    </dependency>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>4.5.3</version>
    </dependency>
    <dependency>
      <groupId>io.github.bonigarcia</groupId>
      <artifactId>webdrivermanager</artifactId>
      <version>5.3.0</version>
      <exclusions>
        <exclusion>
          <groupId>com.google.guava</groupId>
          <artifactId>guava</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>31.1-jre</version>
    </dependency>

  </dependencies>
</project>

I tried to configure chrome driver on Mac m2
version of chrome driver chromedriver_mac_arm64.zip 107.0.5304.62
version of google chrome 107.0.5304.87
I've broke my mind already. Could you help me with this problem.
I run basic code
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver");

WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();

driver.get("https://google.com")

driver.quit();

If I run this code same error
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver");

WebDriver driver = new ChromeDriver();

driver.get("https://google.com")

driver.quit();

I think the problem is version between components.

A: You are explicitly excluding the transitive dependency on Guava from one of your libraries, and including another version. The version you are including isn't compatible with the library. Specifically, the library is calling a version of ImmutableMap.of which isn't available in your version.
The solution is one of these:

*

*Upgrade your dependency on io.github.bonigarcia:webdrivermanager to a version that uses a newer version of Guava

*(politely) ask the maintainer of that library to upgrade their Guava dependency

*Remove your explicit dependency on Guava and use the one provided by the library


text:
Q: Application crashes while retrieving contacts from phone book by using ABAddressBookRef
Application crash when facebook contact syncing is ON from settings.

 While getting normal phone contact ABRecordRef returns "CPRecord: 0x15fd77510 ABPerson".
   While getting facebook contact ABRecordRef returns (ABRecordRef) person = 0x3ff0000000000000.

the code
     ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
            ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
            CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName);
            CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
    for (int i = 0; i < nPeople; i++)
    {
        ContactsData *contacts = [ContactsData new];

        ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);

        //get First Name and Last Name
        contacts.firstNames = (__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
        contacts.lastNames =  (__bridge NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);

        if (!contacts.firstNames) {
            contacts.firstNames = @"";
        }
        if (!contacts.lastNames) {
            contacts.lastNames = @"";
        }

        //get Phone Numbers

        NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];

        ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
        for(CFIndex i=0;i<ABMultiValueGetCount(multiPhones);i++) {

            CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
            NSString *phoneNumber = (__bridge NSString *) phoneNumberRef;
            if (![phoneNumber isEqualToString:@""]) {
                [phoneNumbers addObject:phoneNumber];
            }
        }
        if ([phoneNumbers count] != 0) {
            [contacts setNumbers:phoneNumbers];
        }
    }
}

A: Check the following code:
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
    ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName);
    CFIndex nPeople = CFArrayGetCount(allPeople);


text:
Q: The gradient of a function is an alternating one-tensor I'm currently reading Spivak's Calculus on Manifolds and I seem to have hit a snag in Chapter Four: Integration on Chains. Spivak develops tensors, vector fields, alternating tensors and differential forms. I'm okay with these ideas however he makes the claim that if $f:\mathbb{R}^n\rightarrow\mathbb{R}$, then $Df(p)\in\Lambda^1(\mathbb{R}^n)$. I can see that the gradient of a scalar function is clearly a 1-tensor over $\mathbb{R}^n$ since it maps $\mathbb{R}^n$ to $\mathbb{R}$ but I fail to see how it is alternating (and thus in $\Lambda^1(\mathbb{R}^n)$ rather than just $T(\mathbb{R}^n)$).

A: Any covector is also an alternating one tensor. You should think of an alternating tensor as any tensor $ T : (T\mathbb{R}^n)^p \rightarrow \mathbb{R} $ that is invariant with respect to permutation of the p arguments up to the sign of the permutation. Since there is just one way to permute 1 argument, every one tensor is alternating.


text:
Q: Inspect surroundings-area/neighbors/context of every row selected by a filter condition in R Objective
My solution below seems too messy and low performant. There must be a simpler approach, as this operation already exists in filters for image processing to enlarge/widen selection mask.
I started this code to manually inspect regions of a table without switching to an Spreadsheet which in many cases is not possible due to the large amount of data. My goal was to pass filtered rows to a function that would return one dataframe per row with the surrounding/neighbor rows.
It first played well for duplicated but it doesn't plays well with filter in a pipe.
For example, when printing a DF in Rstudio, having 1 row selected, with depth=2, I want to inspect the 5 contiguous rows surrounding the selected one.
row
row
row <------- neighbor row
row <------- neighbor row
row <-- selected by filter condition
row <------- neighbor row
row <------- neighbor row
row
row

Image processing analogy
: dilate/erode filter in image processing, widens light/dark areas of the active selection filter.
keywords
: increase, expand, enlarge, enhance, widen, dilate, broaden, neighbours, context, surroundings, region
Current Approach
(Reproducible code)
df_inspect_context <-
df_inspect_surroundings <-
df_inspect_neighbors <-
df_inspect_region <-
helper_df_inspect_region <-
  function( DF, logicals, depth=5, limit=4 ){

      looplst  <- logicals %>% which %>% head(limit) %>% na.omit

      filter
      regions  <- lapply( looplst ,    function(rnum){
                  from = max( 1, (rnum-depth) )
                  to   = min( (rnum+depth-1), nrow(DF) )
                  indexes     = from:to
                  highlightX  = c( rep('', rnum-from ), 'X', rep('', to-rnum ) )

                  return( list( idxs=indexes, X=highlightX ) )
                  } )
      lapply(    regions,   function(region) {  cbind(X=region$X, DF[ region$idxs, ])   } )
}

#TEST
helper_df_inspect_region( iris, duplicated(iris) )

See result, the X marks the inspected row
EXPECTATION

*

*Standard R-ish method for the same.

*I want this to play well with normal filter operations.

*It should return either a list of dataframes as current, or one enlarged filtered dataframe.

*It must respect the passed arranging.

Example calls:
df %>% arrange(..) %>% filter(..) %>% dilate(5)
df %>% arrange(..) %>% filter(..) %>% surrounding_rows(5)
df %>% arrange(..) %>% filter(..) %>% neighbor_rows(5)

Constraints of current solution
In order to check for CEROes or Outliers at any cell of all rows, I would filter with a dplyr context like next, which is not compatible with the which function that my function uses to calculate the regions.
dat %>% filter( if_any( everything(), ~.==0 ) )

The filter condition (~.==0,~.=='',is.na,is.empty) has to apply to entire rows, and return TRUE if any row is TRUE.
To work around this, I used apply to apply the condition row by row and return one logical per row.
As apply coerces to chr I had to take care of filtering numeric columns as well.
The result looks messy and still doesn't plays well with filter.
numericcols = lapply(df, is.numeric) %>% unlist
logicals = apply( df[,numericcols], 1, function(x) sum(x==0)>0 )

See result for a CEROs lookup
Note: lag/lead: I found lag and lead as suggested in other questions, but doesn't do the same thing, or they return NA where there must be data.

A: So here is a slightly modified code from here Returning above and below rows of specific rows in r dataframe: Credits to @flodel (2012) :-)
Here we identify the row by rownumber and select n above and n below:
extract.with.context <- function(x, rows, after = 0, before = 0) {

  match.idx  <- which(1:nrow(mtcars) %in% rows)
  span       <- seq(from = -before, to = after)
  extend.idx <- c(outer(match.idx, span, `+`))
  extend.idx <- Filter(function(i) i > 0 & i <= nrow(x), extend.idx)
  extend.idx <- sort(unique(extend.idx))

  return(x[extend.idx, , drop = FALSE])
}

extract.with.context(mtcars, 6, after=2, before = 2)

                  mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2

A: I happen to answer my own question, sorry for that, but I came with this solution. I am not sure how to name it yet. So far, it does what I need, and most of what the question posted asks.
I am still interested in more performant options.
dilate_filter <-
  function( X, df_original, by, depth=5, limit=NA ){
    X <- if ( is.data.frame(X) )  list(X)
    else if (is.list(X)) X
    else NULL

    result = list()
    limit = min(coalesce(limit,length(X)),length(X))

    for( k in 1:limit ){

        DF <- df_original %>% rowid_to_column( "idx"  )
        indexes <- left_join( X[[k]] , DF, by=by )$idx

        indexes <-  sapply( indexes, function(rnum) {
          from <-  max( 1, (rnum-depth) );
          to   <-  min( (rnum+depth-1), nrow(df_original  ) );
          X=c( rep('', rnum-from ), 'X', rep('', to-rnum ) )
          return( list( X = X, idx = from:to ) )
          } )

        highlightXs = indexes['X',] %>% unlist
        indexes = indexes['idx',] %>% unlist
        DF <- cbind( X=c(highlightXs), DF[ c(indexes), ])

        result[[ length(result)+1 ]] <- DF
    }
    if (length(result)==1) return(result[[1]])
    else return(result)
}

The primary use scenario is
by <- c('session_id', 'datetime')

db$minuteCaloriesNarrow[Calories==0] %>%
  dilate_filter( db$minuteCaloriesNarrow, by )

But, it can be called from a piped sequence as:
db$minuteCaloriesNarrow[Calories==0] %>%
  split( row.names(.) ) %>%
  dilate_filter( db$minuteCaloriesNarrow, by )

And perform calculations in a pipe afterwards
db$minuteCaloriesNarrow[Calories==0] %>%
  split( .[['.datetime']]  ) %>%
  dilate_filter( db$minuteCaloriesNarrow, by )%>%
  map( ~.[['Calories']] %>% median ) %>%
  unlist

db$minuteCaloriesNarrow[Calories==0] %>%
  dilate_filter( db$minuteCaloriesNarrow, by ) %>%
  .$Calories %>%
  median

or
median_list <-
  db$minuteCaloriesNarrow[Calories==0] %>%
    split( row.names(.) ) %>%
    dilate_filter( db$minuteCaloriesNarrow, by )%>%
    map( ~.[['Calories']] %>% median ) %>%
    unlist

db$minuteCaloriesNarrow[Calories==0]$Calories <- median_list

db$minuteCaloriesNarrow[Calories==0]

The function gets either a DF or a list of DF (after using split).
Also requires the original DF, previous filtering, and the keys to perform left_join in order to get the row indexes.
Once indexes are encountered for each row on the input, it just adds more indexes to the list related to the neighbor rows or surroundings, by using depth and seq.
Additionally, it also adds a column with an X, marking the original row value that we are interested in.
This function is meant to avoid switching to Spreadsheet when trying to inspect the context of a certain row, but it can be used to perform calculations as well.
For last, a test with builtin dataset:
DF <- iris
keys = c('Species', 'Sepal.Length')
DF %>% filter(duplicated(.)) %>% dilate_filter( DF, keys, limit=10 )


text:
Q: How to resolve placeholder in properties file with values from another properties file in spring boot application My spring boot application has below properties files.
src/main/resources/config/DEV/env.properties
mail.server=dev.mail.domain

src/main/resources/config/QA/env.properties
mail.server=qa.mail.domain

src/main/resources/config/common/env.properties
mail.url=${mail.server}/endpoint

Is it possible to load "common/env.properties" so that it's placeholders will be resolved using the given environment specific properties file. For DEV environment, we want the placeholders in "common/env.properties" to be resolved using values from "DEV/env.properties".
There are answers about how to load multiple properties files and profile based loading but could not find an answer for this particular use case.
Thanks in advance.

A: 2 Options :

*

*Generate the common/application.properties using configuration-maven-plugin and filter files for each environment. It is outdated now.

*Use application-<env>.properties for each environment and pass the -Dspring.profiles.active=<env> as VM option in application start up. Spring will automatically take the property from correct file.

In option 2, you will be overwriting whatever is present in application.properties with application-.properties. So you dont have to add only the properties which you need to change per environment.
for eg:
Your application.properties can have
logging.level.root=WARN
logging.level.org.apache=WARN
logging.level.org.springframework=WARN

Your application-dev.properties can have
logging.level.org.springframework=DEBUG

which means, when you are starting application using dev profile, spring takes
logging.level.root=WARN
logging.level.org.apache=WARN
logging.level.org.springframework=DEBUG

edit :
Also, you can try something like below on your class. (Spring will overwrite value in config.properties with values from config-dev.properties). ignoreResourceNotFound will make sure, application will still start with default values even if the corresponding file is not found.
@Configuration
@PropertySource("classpath:config.properties")
@PropertySource(value = "classpath:config-${spring.profiles.active}.properties", ignoreResourceNotFound = true)

A: You can achieve this by declaring a property source on a class configuration and setting up an environment variable in the path :
@PropertySource({ "classpath:config/${env}/env.properties" })
@Configuration
public class config{}

And then you launch the spring boot app with the command line variable -env=dev
UPDATE
You can use @PropertySources annotation to load several properties.
 @PropertySources({
    @PropertySource("classpath:config/${env}/env.properties"),
    @PropertySource("classpath:config/common/env.properties")
  })
  public class config{}

A: You can add resources/application.yml file where you can have multiple profiles in one File.
MultiProfile Yaml
e.g.here are two different profiles 'dev' and 'qa' with different applicationNames 'DEV' and 'QA' and one defaultName 'Default'
spring:
  application:
    name: Default
  profiles:
    active: qa

---
spring:
  profiles: dev
  application:
    name: DEV
---
spring:
  profiles: qa
  application:
    name: QA


text:
Q: SSRS Expression Count values in one column where values in first column equal each other I have searched for an answer with no luck. I've tried Lookup and CountDistinct.
In the table below I need to count the number of distinct Records that have both an A and B in box 1. I'd like to do this in an expression as I want to use the same dataset to pull up other combinations of results. Please note I have multiple datasets in this report. There's a reason for this insanity. I greatly appreciate any help.
Record Box File
   01    1    A
   01    1    B
   01    2    B
   01    2    B
   02    1    A
   02    1    B
   02    2    B
   03    1    B
   03    1    B

A: Try to adjust your table a little bit to have the File column in the detailed row, then add a parent group by Box. In your detailed row, use the count expression on File.


text:
Q: Responsive table overflow on mobile Check out this image:

See how "Recreation", "Wednesday: 4:00-6:00pm" are spilling over into the next line under the column header? How do I keep the cell contents organized in the same column? It just looks very messy at the moment. I'm using jQuery mobile's default implementation of responsive tables.

      Activity Type
      Time
      Contact
      Address
      Website

I'm appending the cell contents dynamically.

A: Wrap text in span and apply the below CSS, only on small screens.
@media (min-width: 35em) {
   .ui-table-reflow.ui-responsive td span,
   .ui-table-reflow.ui-responsive th span {
      width: 50%;
      text-align: left;
      float: right;
   }
}

Demo


text:
Q: Incompatibility between babel and listings when using quotes - how to overcome this? With the following LaTeX file I get the error message

! Extra }, or forgotten \endgroup.
  <argument> {\lstinline {""}}
l.11 \cmd{{\lstinline{""}}}

Commenting out \usepackage[german]{babel} makes the file compile.
\documentclass{article}
\usepackage[german]{babel}
\usepackage{listings}

\newcommand{\cmd}[1]{#1}

\begin{document}

\cmd{{\lstinline{""}}}

\end{document}

My goal is to have an empty string "" plus some further strings within some text, and since I use \lstinline extensively otherwise, I would prefer to format those strings with \lstinline as well.  A potential workaround could be to format those strings without help of the listings package, but maybe there is a better solution.
For your reference: I also checked out Possible incompatibility between babel, listings and arsclassica and Textcase, Listings, and Tilde, but although it seemed to be a similar situation, this appears to be a different problem.


text:
Q: Watching for array additions/deletions in Vue When watching an array in Vue like this:
watch: {
  myarray(val) {
    // react to additions or deletions on myarray
  },
},

and adding or removing items on that array like this:
this.myarray.splice(this.myarray.findIndex((d) => d.id === myId), 1);
this.myarray.push({name: 'New Item'});

how do I watch for these additions or deletions on the array. Two ways I could do this:

*

*Use v-for to generate (renderless) components and use the created()/beforeDestroy() hooks of this component.

*Compare the old to the new version of the array and find differences (by iterating over the whole array)

But both methods would add a performance overhead to my application (There are up to a hundred thousand elements in this array).
Is there any way the watch callback can pass me a list of additions or deletions.
The (value, mutation) callback described here: https://optimizely.github.io/vuejs.org/api/instance-methods.html would be exactly what I need. Unfortunately that doesn't seem to work anymore.

A: The best method I came up with so far would be overwriting the push and splice methods of the array. I don't really like this solution though, as it doesn't use Vue's built-in reactivity which does basically the same I am doing here:
created() {
  this.myarray.push = (...args) => {
    //do something with args
    return Array.prototype.push.apply(this.myarray, args);
  };
  this.myarray.splice = (...args) => {
    //do something with args
    return Array.prototype.splice.apply(this.myarray, args);
  };
  //any more array methods you want to intercept
},

Alternatively, and if you don't need existing code using push() and splice() to be compatible with this, you could of course define new functions such as push2() and splice2() to avoid overwriting the native functions.
Or you could define such functions on the component itself to act as setter for the array.
Note that when using the above snippet you loose Vues own reactivity on that array. To keep both you would have to do:
created() {
  const originalPush = this.myarray.push;
  const originalSplice = this.myarray.splice;
  this.myarray.push = (...args) => {
    //do something with args
    return originalPush.apply(this.myarray, args);
  };
  this.myarray.splice = (...args) => {
    //do something with args
    return originalSplice.apply(this.myarray, args);
  };
  //any more array methods you want to intercept
},


text:
Q: Do I have to call dispose after each use though datatable is stored in cache? Simple case:
i put a DataTable in Cache
DataTable table = SomeClass.GetTable();
Cache["test"] = table;

then in later calls i use
DataTable table = (DataTable)Cache["test"];

now the question is: should i call table.dispose() on each call, though its stored in the Cache? Means the object is always the same? Or will Cache create a copy on each time?
thx :)

A: All you are doing is storing a pointer in cache... The actual "table" is still on the heap, where all .Net reference types are stored... You are not making a copy of it...
The variable in cache just acts to stop the garbage collector from erasing the object on the heap...
and no, you don't want to call dispose  until the actual object is no longer required.

A: i believe that you should only call Dispose once when you are completely done with the datatable; calling Dispose changes the state of the object.
note that 'cached' does not always mean 'copied'!

A: a DataTable is a managed resource and does not require that it's Dispose() method be called in order to be properly cleaned up by garabage collection.


text:
Q: Compass function in MATLAB I'm a beginner when it comes to MATLAB and I'm trying to plot a set of points using compass while holding on the plot. The problem is that when I, for example, plot the first point and then plot a second point that is "far away", the compass axes don't get updated. Is there a way to re-size the axes so that I can get the second point wihtin the frame?
Example :
compass(1,2);
hold on;
compass(40,50);%that point is out of the frame and I can't see the whole arrow

Thanks !

A: I'd recommend you simply store the coordinates in vectors first and then plot them all at once.
   a = [1,40];
   b = [2,50];
   compass(a,b)

A: Copied from @Hoki (so as to mark the subject as solved) :
In all the polar type plots (polar, compass, rose, ...). The polar grid is not the graduation of the axes itself, it is composed by a patch and a set of lines and texts objects, which are calculated and positioned the first time the function is called on a figure. They will not be dynamically adjusted. To make sure you'll have all your data fitting in the makeshift grid, call compass on the maximum element first.


text:
Q: detect rolling channels in a series of high and low points Suppose that I have a sequence of lows and highs (1st and 2nd column respectively). The sequence length can be an arbitrary number. The length of 100 here is just an example.
$ awk -e 'BEGIN { for(i=1;i<=100;++i) { l=rand(); b=rand(); print l, l+b } }'
0.924046 1.51795
0.306394 0.885335
0.740133 1.52706
0.43637 0.768565
0.77888 0.879766
0.785084 1.62024
0.761209 1.25729
0.426298 1.3721
0.821802 1.53107
0.157828 0.27758
...

For each window of rows with size w (for example, if w=4, the windows will be rows1-4, rows2-5, ...), I want to find two lines $a1+bi$ and $a2+bi$ (channel) enclosing all the points in the window so that $|a2-a1|$ is minimized.
Is there an efficient algorithm to find channels like this?
The implementation can be in python and R.

A: Here is a brutal force way that should run in NWlogW time, that does not factor in the rolling window. I thought about some ways the rolling part can be used to cut down some running time, but overall the complexity level remains the same, so I won't bother there
First, find the convex hull or the 2W points in O(WlogW) time. The result is represented by all points on the border of the hull, and ordered in a list (up to O(W) in size).
Second, for each edge (formed by 2 adjacent points, except for the 2 vertical edges which we don't need), you can find the 'b' and 'a1'. Then find the furthest point on the convex hull by assuming a parallel line of slope 'b' going thru a point a find its corresponding 'a2'. this can be done in bi-sectional search and needs time LogW. Now, since there are O(W) edges, you need WlogW total time to find the edge-point combination that give you the smallest |a1-a2|
Third, you have O(N) windows. So the total time is O(NWlogW). I guess this is not a very efficient way, but can give you an upper bound of doing this.


text:
Q: Debian 7, Apache2, PHP w/ FCID - what am I doing wrong? A lot of the documentation and search results came from those who have multiple users/sites and not sure if my situation applies to theirs or if it will open it up more than needed.
My situation: Single website and single user. Using Debian 7, Apache2 with mpm-worker, PHP5 with libapache2-mod-fcid.
After installation and reboot, not getting PHP scripts to run.
I enabled the following and it still doesn't work.

sudo a2enmod fcid
sudo service apache2 restart

What else do I need to change? Also, my installation doesn't seem to have a httpd.conf and only an apache2.conf and security.conf.
Thanks!


text:
Q: How to iterate properly using page token in Calendly? I want to get the information of all the pages that are generate.
This is my code:
import requests
response = requests.get(url, headers=headers)
final_response = response.json()
print(final_response)

I received a response like this:
{
  "collection": [
    {
      "uri": "https://api.calendly.com/event_types/AAAAAAAAAAAAAAAA",
    }
  ],
  "pagination": {
    "count": 1,
    "next_page":"https://api.calendly.com/event_types?
                 count=1&page_token=sNjq4TvMDfUHEl7zHRR0k0E1PCEJWvdi"
  }

With that page_token (https://api.calendly.com/event_types?count=1&page_token=sNjq4TvMDfUHEl7zHRR0k0E1PCEJWvdi) that is generated I want to iterate in all the pages and get all the information until "next_page"is "null"

A: you just need to use next_page url and do new request with this URL in loop until the next_page URL is None. You need to provide same auth headers for each request, but you don't have to provide search params, because they are already included in next_page URL. documentation


text:
Q: Appending numbers to url do not break the link I'm doing some url and meta cleanup and have found a strange problem(?) where, when adding a number to a url, the url still works.  For example:
The following uris both work and retrieve the same information:
/2012/06/21/graduation
/2012/06/21/graduation/29/
This numeral addition works with any url on the site.
I'd love to know a couple things:

*

*is this normal?

*if this is normal, how can I be more strict with url formation?

A: That's an old problem, and I have never looked deep enough explain it. But I have a plugin for that, written a long time ago. It still works, but keep the age of the code in mind when reading it. :) I didn't change much for this repost.
<?php
/*
Plugin Name: T5 Canonical Permalink
Plugin URI: http://toscho.de/2010/wordpress-plugin-canonical-permalink/
Description: Removes illegal numeric suffixes from the request URI.
Version: 0.3
Author: Thomas Scholz
Author URI: http://toscho.de
Created: 04.04.2010
*/

add_action('wp', 't5_canonical_request');
/**
 * WordPress allows URIs with any numeric suffix, e.g.:
 * /canonical-page-or-postname/12345/
 * This functions performs a simple check and redirects
 * to the canonical URI if neccessary.
 *
 * @return void
 */
function t5_canonical_request()
{
    global $page, $post;

    // post, page, attachment, preview
    if ( ! is_singular() or is_preview() )
    {
        return;
    }

    $permalink = get_permalink();

    // We don't have access to the number of sub pages here.
    // So we have to hack.
    $max_pages = substr_count(
        $post->post_content, '') + 1;

    if ( 1 < $page and $page <= $max_pages )
    {
        /*
         * Handle different permalink settings, eg:
         * /%year%/%postname%.html or
         * /%year%/%postname%/
         */
        $rev_perma_struct = strrev(get_option('permalink_structure'));

        if ( '/' != $rev_perma_struct[0] )
        {
            $permalink .= "/$page";
        }
        else
        {
            $permalink .= "$page/";
        }
    }

    $host_uri       = 'http'
                    . ( empty ( $_SERVER['HTTPS'] ) ? '' : 's' )
                    . '://' . $_SERVER['HTTP_HOST'];
    $canonical_path = str_replace($host_uri, '', $permalink);

    if ( ! empty ( $_GET ) )
    {
        global $wp;
        // Array
        $allowed = $wp->public_query_vars;

        $out_arr = array();

        foreach ( $_GET as $k => $v )
        {
            if ( in_array($k, $allowed ) )
            {
                $out_arr[] = $k . ( empty ( $v ) ? '' : "=$v" );
            }
        }

        if ( ! empty ( $out_arr ) )
        {
            $canonical_path .= '?' . implode('&', $out_arr);
        }
    }

    if ( $canonical_path == $_SERVER['REQUEST_URI'] )
    {
        return;
    }
    // Debug current result:
    #print '
' . var_export($canonical_path, TRUE) . '
';

    // Change it or return 'false' to stop the redirect.
    $canonical_path = apply_filters(
        't5_canonical_path',
        $canonical_path
    );

    if ( FALSE != $canonical_path )
    {
        header('Location: ' . $permalink, true, 301);
        die("$permalink");
    }

    return;
}


text:
Q: make df from matching columns I have 2 dataframes df1 and df2 having columns as df1['date','customer_id','category_name'] and df2['date','customer_id','category_name']. I want values from df1 which matches in df2 on columns 'customer_id' & 'category_name'.
So I tried this:
df_final = df1[(df1['customer_id']==df2['customer_id'])&(df1['category_name']==df2['category_name'])]

but it is showing 'ValueError: Can only compare identically-labeled Series objects' dataframes

A: Try using merge
df_final = pd.merge(df1, df2, on=["customer_id", "category_name"], how="left")


text:
Q: Random selection with a caveat / criteria I have a 6 x 6 grid. I have 36 samples split into three equal groups (A, B, and C).
I want a formula to arrange the samples in that grid randomly. However each row and each column must contain two of each group. Doing this manually once or twice is easy, but there are a massive number of combinations.
I am open in terms of software choices so long as it is freeware or Microsoft Office based.
Thank you!

A: I put together a tool for generating random row/column permutations with a couple of formulas and some VBA.  The sheet layout looks like this:

The reference grid is a trivial example of a valid matrix, as posted in Gary's Student's preliminary answer (possibly since deleted).  The row and column permutations incorporate all possible unique combinations of permutations for the 6x6 grid.  (This could easily be modified to include non-unique permutations, if desired.) The values in E12:E26 and L12:L26 are randomly seeded to either zero or one, to provide the basis for whether or not to perform a given permutation.  Columns D and K just convert these to boolean values for simplified handling within the VBA (see below).  The permuted grid is generated by the custom function doSwap, entered as an array formula.  Pressing F9 to trigger sheet recalculation causes the various RAND functions to re-generate their random values, changing the series of permutations to be performed.
The VBA code that enables this behavior is:
Function doSwap(srcRg As Range, rowSwaps As Range, colSwaps As Range) As Variant
    Dim workVt As Variant
    Dim iter As Long

    workVt = srcRg.Value

    ' Do row swaps
    For iter = 1 To rowSwaps.Rows.Count
        With rowSwaps
            If .Cells(iter, 3).Value Then
                workVt = swapRow(workVt, .Cells(iter, 1), .Cells(iter, 2))
            End If
        End With
    Next iter

    ' Do col swaps
    For iter = 1 To colSwaps.Rows.Count
        With colSwaps
            If .Cells(iter, 3).Value Then
                workVt = swapCol(workVt, .Cells(iter, 1), .Cells(iter, 2))
            End If
        End With
    Next iter

    ' Store and return
    doSwap = workVt

End Function

Function swapCol(ByVal inArr As Variant, idx1 As Long, idx2 As Long) As Variant
    Dim tempVal As Variant, workVt As Variant
    Dim iter As Long

    ' Check if Range or Array input
    If IsObject(inArr) Then
        If TypeOf inArr Is Range Then
            workVt = inArr.Value
        Else
            swapCol = "ERROR"
            Exit Function
        End If
    Else
        workVt = inArr
    End If

    ' Just crash if not correct size
    ' Do swap
    For iter = LBound(workVt, 1) To UBound(workVt, 1)
        tempVal = workVt(iter, idx1)
        workVt(iter, idx1) = workVt(iter, idx2)
        workVt(iter, idx2) = tempVal
    Next iter

    ' Return
    swapCol = workVt

End Function

Function swapRow(ByVal inArr As Variant, idx1 As Long, idx2 As Long) As Variant
   Dim tempVal As Variant, workVt As Variant
   Dim iter As Long

    ' Check if Range or Array input
    If IsObject(inArr) Then
        If TypeOf inArr Is Range Then
            workVt = inArr.Value
        Else
            swapRow = "ERROR"
            Exit Function
        End If
    Else
        workVt = inArr
    End If

    ' Just crash if not correct size
    ' Do swap
    For iter = LBound(workVt, 2) To UBound(workVt, 2)
        tempVal = workVt(idx1, iter)
        workVt(idx1, iter) = workVt(idx2, iter)
        workVt(idx2, iter) = tempVal
    Next iter

    ' Return
    swapRow = workVt

End Function

The above code is not well robustified, but serves the present purpose. Extension/generalization should be pretty straightforward, if needed.  In particular, it should handle as-is any size of 2-D reference grid, even one that is non-square.  The key thing is to ensure the arrays of permutation instructions are set up properly.
EDIT: After playing with it a bit, it's clear this solution doesn't provide access to the full space of possible permutations.  So, I tweaked it by adding a random "bit-shift" to swap the type labels among themselves. To simplify things, I switched from ABC labels to 123 labels, which allows implementation by a simple MOD operation, and also a quick-glance sanity check in the form of row and column sums:

A: There is a very simple way to accomplish this.  First pre-assign slots to each of the three types:

Then take the first sample, for example SAMPLE_A_1, and place it randomly in one of the A-slots.  Then continue to process each of the remaining 35 samples.If this approach is acceptable, I'll post a short program to populate the matrix.  If the approach is not acceptable, I will delete this post.


text:
Q: Nested attributes and interacting with form hash and setting the user_id to current_user.id I have rewritten this question as the other one seemed too verbose. I have the following model structure and am interested in having a set of files uploaded (2 at a time via a builder). I am not sure if the polymorphic relat
class Item < ActiveRecord::Base
  has_many :assets, :as => :assetable, :dependent => :destroy
  accepts_nested_attributes_for :assets, :allow_destroy => true, :reject_if => lambda { |a| a[:asset].blank? }
  attr_accessible :assets_attributes, :asset

  ...
end

class Asset < ActiveRecord::Base
   belongs_to :assetable, :polymorphic => true
   attr_accessible :name, :user_id, :description ...

   ...
end

I have copied out the entirety of the form:
<form accept-charset="UTF-8" action="/arc/items/70" class="edit_item" enctype="multipart/form-data" id="edit_item_70" method="post">
<input name="utf8" type="hidden" value="✓" /><input name="_method" type="hidden" value="put" /><input name="authenticity_token" type="hidden" value="NnaCxwmfy2zT8MnN7oNQnOx0xYXkgKUs+NbIh8+8cL4=" />

        <input id="item_assets_attributes_70_asset" name="item[assets_attributes][70][asset]" type="file" />
        <input id="item_assets_attributes_70_description" name="item[assets_attributes][70][description]" size="30" type="text" />

        <input id="item_assets_attributes_71_asset" name="item[assets_attributes][71][asset]" type="file" />
        <input id="item_assets_attributes_71_description" name="item[assets_attributes][71][description]" size="30" type="text" />

<input name="commit" type="submit" value="Update Menu item" />
</form>

and here is the controller for interacting with it:
class ItemsController < ApplicationController
...
def update
  item=params[:item]
  item[:assets_attributes].values do |v|
    v[:asset][:user_id]=3 # just hard-code it to see if workig
  end

  if @item.update_attributes(item)
    flash[:notice]="Menu Item has been updated #{undo_link}"
  else
    flash[:notice]="Menu Item has not been updated"
  end
end

In my asset class, the user_id NEVER gets set. How would I make this work? I obviously want to get the current_user.id.
thx
edit #1
Using Rails 3.1
edit 2
One thing that I've noticed is that if I set an instance variable in the loop and then debug it into the view, it wasn't set meaning that this loop isn't even running.
item[:assets_attributes].values do |v|
  v[:user_id]=3
  @a="here is a string"
end

I have also updated the Item model with the appropriate attr_accessible for the item class.

A: In this block you're not doing anything.
item[:assets_attributes].values do |v|
  v[:user_id]=3 # just hard-code it to see if working
end

values is just returning the values, so you need to have an iterator like each if you want to interact with those values. Try this
item[:assets_attributes].values.each do |v|
  v[:user_id]=3 # just hard-code it to see if working
end

A: It seems likely that you cannot mass assign user_id. Either:
You have attr_accessible defined, and it does not include user_id
You have attr_protected defined, and it does include user_id
You are using Rails 3.2, which does this automatically to prevent reassigning an object to a different user via mass assignment (which is a security hole).
If that is the case, then your best bet is to set the user directly via asset.user= instead (or to allow user_id to be mass assigned, I suppose).


text:
Q: module interconnection interface design I want to have some simple interfaces for the users to connect some pre-defined modules (I'm free to modify them if I have to).
Each module has a few named inputs and outputs.
One module may connect to a few modules.
A few modules can connect to a single module.
This is what I have in my mind so far:
Option 1:
Each module has "in" and "out" dictionary for input and output, and the connection is made through code like this:
a.out["out 1"].to(b.in["in 1"]) # connect a's "out 1" output to b's "in 1" input
a.out["out 2"].to(b.in["in 2"]) # connect a's "out 2" output to b's "in 2" input

But this looks quite tedious, so I came up with Option 2:
# connect a to b and c, then list which inputs connect to which outputs
a.to(b,{"out 1":"in 1",
        "out 2":"in 2"},
     c,{"out 4":"in 1",
        "out 3":"in 2"})

This seems to look better as it's clearer to me which modules are connected and also the mapping between their outputs and inputs are clearly listed.
I wonder if there is any room to improve the above, to clearly show:

*

*module level connections, e.g. module a connect to module b

*outputs and inputs connections

*simple and clear interface. By 'simple', I mean less typing; 'clear' means easy to understand. I understand that sometimes I can't have both in that case, 'clear' interface is preferable.

I'm not proficient in Python(2.7) so there might be some syntax or operator or data structure that I am not aware of but I may be able to take advantage for this purpose.

A: I have run into this exact issue, the issue of being able to clearly describe directed graphs linearly. None are particularly pleasant... Personally, I believe showing how the sources and sinks (node inputs and outputs) connect is more important than showing which nodes are connected, because the relationship is more specific.
Of the two designs you listed I would recommend the first, since it is clearer. It shows exactly how each input and output connects. However, I would slightly augment your implementation. I would make the node class capable of creating new handles for inputs and outputs that are actual attributes in the object. Then use those handles when describing the graph and capturing traffic, etc. Making the inputs and outputs actual objects instead of labels means construction-time checking and the ability to generate better error messages. For example:
b = Node()
b.input("in1", "in2")  # this creates a new input object that is located in 'b' with the attribute name of the given string
b.output("out1")  # this could be in the constructor
c = Node(in=["in1", "in2"], out=["out1"])  # like so

# describe the connections
a.out1.to(b.in1)
a.out2.to(b.in2)
a.out3.to(c.in2)
a.out4.to(c.in1)
# maybe syntax like 'a.out3 >> c.in2' would be prettier?

module_graph_output = c.out1.capture()
# do stuff with the graph output

Additionally, the module definitions can be passed these output and input object handlers for the user as they implement the module logic.
All this aside, how you are going to run the module graph is the bigger issue. If I'm not intruding, what is the application of this?


text:
Q: BigQuery: cannot save number in scientific notation We are experiencing problems in saving data on BigQuery between 22:00 and 5:00 UTC.
The problem started at midnight February 7th 2017 and is still happening today.
Everyday in this time frame we have a huge amount of failures inserting data.
The number of failures decreases dramatically until it disappears in the next hours.
The data format we insert is always the same throughout the day.
This is one of the "n" errors we found in the response of the insert request:
{"debugInfo":"generic::invalid_argument: Cannot convert value to integer (bad value):8.3163161541138022e+17","location":"id","message":"Cannot convert value to integer (bad value):8.3163161541138022e+17","reason":"invalid"}

It seems the problem is related to numbers with scientific notation. As mentioned above we perform save operations with this kind of numbers all the day but we encounter the problem only in a time frame of the day since February 7th 2017
This is a print out of the row (TableDataInsertAllRequest.Rows) related to the above error.
{insertId=831631615411380224, json={in_reply_to_status_id_str=null, in_reply_to_status_id=null, created_at_timestamp=2017-02-14 22:30:02, created_a
t=Tue Feb 14 22:30:02 +0000 2017, in_reply_to_user_id_str=null, source=Twitter for iPhone, retweeted_status={in_reply_to_status_id_str=null, in_reply_to_status_id=null, cr
eated_at=Tue Feb 14 15:56:07 +0000 2017, in_reply_to_user_id_str=null, source=bot, retweet_count=2.0, retweeted=false, geo=null, filter_level=low, in_reply_to_screen_name
=null, is_quote_status=false, id_str=831532483447488513, in_reply_to_user_id=null, favorite_count=25.0, id=8.3153248344748851E17, text=2017/02/15 00:48, place=null, lang=ja, favorited=fal
se, possibly_sensitive=false, coordinates=null, truncated=false, entities={urls=[{display_url=google.com/g0lSa9, indices=[31.0, 54.0], expanded_url=https://google.com/g0lSa9, url=https://twitter.com/W2Vpuwrq1F}], hashtags=[], user_mentions=[], symbol
s=[]}, contributors=null, user={utc_offset=null, friends_count=5.0, profile_image_url_https=https://pbs.twimg.com/profile_images/665843786015113217/126-R8pG_normal.jpg, listed_count=91.0, profile_background_image_url=http://abs.twimg.c
om/images/themes/theme1/bg.png, default_profile_image=false, favourites_count=0.0, description=abc, created_at=Sat Nov 14
10:18:54 +0000 2015, is_translator=false, profile_background_image_url_https=https://abs.twimg.com/images/themes/theme1/bg.png, protected=false, screen_name=keyaki_blog, id_str=4233385392, profile_link_color=1DA1F2, id=4.233385392E9, g
eo_enabled=false, profile_background_color=C0DEED, lang=ja, profile_sidebar_border_color=C0DEED, profile_text_color=333333, verified=false, profile_image_url=http://pbs.twimg.com/profile_images/665843786015113217/126-R8pG_normal.jpg, t
ime_zone=null, url=http://www.keyakizaka46.com/mob/news/diarShw.php?site=k46o&ima=2757&cd=member, contributors_enabled=false, profile_background_tile=false, profile_banner_url=https://pbs.twimg.com/profile_banners/4233385392/1447584504
, statuses_count=22077.0, follow_request_sent=null, followers_count=11669.0, profile_use_background_image=true, default_profile=true, following=null, name=bot, location=tokyo, profile_sidebar_fill_color=DDEEF6, notifications=null}}, retweet_count=0.0, retweeted=false, geo=null, filter_level=low, in_reply_to_screen_name=null, is_quote_status=false, id_str=831631615411380224, in_reply_to_user_id=null, favorite_count=0.0, id=8.3163161541138022E+17, text=RT @keyaki_blog: 2017/02/15 00:48 https://twitter.co/W2Vpuwrq1F, place=null, lang=ja, favorited=false, possibly_sensitive=false, coordinates=null, truncated=false, timestamp_ms=1487111402739, entities={urls=[{display_url=google.com/g0lSa9, indices=[48.0, 71.0], expanded_url=https://google.com/g0lSa9, url=https://twitter.co/W2Vpuwrq1F}], hashtags=[], user_mentions=[{indices=[3.0, 15.0], screen_name=keyaki_blog, id_str=4233385392, name=bot, id=4.233385392E9}], symbols=[]}, process_instance_id=user-twitter-listener-st-1, contributors=null, user={utc_offset=-28800.0, friends_count=328.0, profile_image_url_https=https://pbs.twimg.com/profile_images/601593430666412032/PQioR336_normal.jpg, listed_count=26.0, profile_background_image_url=http://abs.twimg.com/images/themes/theme1/bg.png, default_profile_image=false, favourites_count=49710.0, description=null, created_at=Fri May 22 01:28:04 +0000 2015, is_translator=false, profile_background_image_url_https=https://abs.twimg.com/images/themes/theme1/bg.png, protected=false, screen_name=tonton_gash1, id_str=3222825788, profile_link_color=1DA1F2, id=3.222825788E9, geo_enabled=true, profile_background_color=C0DEED, lang=ja, profile_sidebar_border_color=C0DEED, profile_text_color=333333, verified=false, profile_image_url=http://pbs.twimg.com/profile_images/601593430666412032/PQioR336_normal.jpg, time_zone=Pacific Time (US & Canada), url=null, contributors_enabled=false, profile_background_tile=false, statuses_count=113901.0, follow_request_sent=null, followers_count=404.0, profile_use_background_image=true, default_profile=true, following=null, name=bb@Onlooker, location=aaa, profile_sidebar_fill_color=DDEEF6, notifications=null}}}
14/02/2017 22:30:33 [ERROR] [95] [saveBulk] [Thread: Thread-1] ERROR BigQueryDataSaver: {insertId=831631616057425921, json={quoted_status={in_reply_to_status_id_str=null, in_reply_to_status_id=null, coordinates=null, created_at=Tue Feb 14 22:17:50 +0000 2017, truncated=false, in_reply_to_user_id_str=null, source=Twitter for iPhone, retweet_count=0.0, retweeted=false, geo=null, filter_level=low, in_reply_to_screen_name=null, is_quote_status=false, entities={urls=[], hashtags=[], user_mentions=[], symbols=[]}, id_str=831628543281025024, in_reply_to_user_id=null, favorite_count=0.0, id=8.3162854328102502E17, text=kaitlyn's baby pictures?, place=null, contributors=null, lang=en, user={utc_offset=-18000.0, friends_count=505.0, profile_image_url_https=https://pbs.twimg.com/profile_images/813191388967960577/Q6Wh4HyC_normal.jpg, listed_count=36.0, profile_background_image_url=http://pbs.twimg.com/profile_background_images/720373579259351041/mPcBv5UA.jpg, default_profile_image=false, favourites_count=48248.0, description=▽ liar, monster, snappy dresser ▽ → kaitlyn // 18 // she/her // antifa // studies history + sociology in scotland // #FreePalestine #AllBlackLivesMatter, created_at=Sun Apr 26 16:05:35 +0000 2009, is_translator=false, profile_background_image_url_https=https://pbs.twimg.com/profile_background_images/720373579259351041/mPcBv5UA.jpg, protected=false, screen_name=ghostcommie, id_str=35495052, profile_link_color=F5ABB5, id=3.5495052E7, geo_enabled=false, profile_background_color=89C9FA, lang=en, profile_sidebar_border_color=FFFFFF, profile_text_color=CE7834, verified=false, profile_image_url=http://pbs.twimg.com/profile_images/813191388967960577/Q6Wh4HyC_normal.jpg, time_zone=Quito, url=null, contributors_enabled=false, profile_background_tile=false, profile_banner_url=https://pbs.twimg.com/profile_banners/35495052/1471561647, statuses_count=59269.0, follow_request_sent=null, followers_count=836.0, profile_use_background_image=true, default_profile=false, following=null, name=a nearby galaxy, location=a few light years away, profile_sidebar_fill_color=78C0A8, notifications=null}, favorited=false}, in_reply_to_status_id_str=null, in_reply_to_status_id=null, created_at_timestamp=2017-02-14 22:30:02, created_at=Tue Feb 14 22:30:02 +0000 2017, in_reply_to_user_id_str=null, source=Twitter for iPhone, quoted_status_id=8.3162854328102502E+17, retweet_count=0.0, retweeted=false, geo=null, filter_level=low, in_reply_to_screen_name=null, is_quote_status=true, id_str=831631616057425921, in_reply_to_user_id=null, favorite_count=0.0, id=8.3163161605742592E+17, text=The people have spoken https://twitter.co/8yPASyGyww, place=null, lang=en, favorited=false, possibly_sensitive=false, coordinates=null, truncated=false, timestamp_ms=1487111402893, entities={urls=[{display_url=twitter.com/ghostcommie/st…, indices=[23.0, 46.0], expanded_url=https://twitter.com/ghostcommie/status/831628543281025024, url=https://twitter.co/8yPASyGyww}], hashtags=[], user_mentions=[], symbols=[]}, process_instance_id=user-twitter-listener-st-1, display_text_range=[0.0, 22.0], quoted_status_id_str=831628543281025024, contributors=null, user={utc_offset=-18000.0, friends_count=505.0, profile_image_url_https=https://pbs.twimg.com/profile_images/813191388967960577/Q6Wh4HyC_normal.jpg, listed_count=36.0, profile_background_image_url=http://pbs.twimg.com/profile_background_images/720373579259351041/mPcBv5UA.jpg, default_profile_image=false, favourites_count=48248.0, description=▽ liar, monster, snappy dresser ▽ → kaitlyn // 18 // she/her // antifa // studies history + sociology in scotland // #FreePalestine #AllBlackLivesMatter, created_at=Sun Apr 26 16:05:35 +0000 2009, is_translator=false, profile_background_image_url_https=https://pbs.twimg.com/profile_background_images/720373579259351041/mPcBv5UA.jpg, protected=false, screen_name=ghostcommie, id_str=35495052, profile_link_color=F5ABB5, id=3.5495052E7, geo_enabled=false, profile_background_color=89C9FA, lang=en, profile_sidebar_border_color=FFFFFF, profile_text_color=CE7834, verified=false, profile_image_url=http://pbs.twimg.com/profile_images/813191388967960577/Q6Wh4HyC_normal.jpg, time_zone=Quito, url=null, contributors_enabled=false, profile_background_tile=false, profile_banner_url=https://pbs.twimg.com/profile_banners/35495052/1471561647, statuses_count=59270.0, follow_request_sent=null, followers_count=836.0, profile_use_background_image=true, default_profile=false, following=null, name=a nearby galaxy, location=a few light years away, profile_sidebar_fill_color=78C0A8, notifications=null}}}

A: I have an important update: I have a problem in another project also on Google Cloud.
In this project the problem occurs 24H (not only between 22:00 and 5:00 UTC).
When we try the same software on a development machine on the same BigQuery table the problem does not occur.
So we tried the software on a GCE machine but in different zone: europe-west1-c instead of us-central1-a. On this area the problems does not occur!
Note: the previous message refer to another project. On this project the problem is still happening every day but only between 22:00 and 5:00 UTC. In this project we already have machines in europe-west1-c.
This is a very strange behaviour.


text:
Q: Maximized windows in Windows show odd dead space So we have experienced this a couple of times, on multiple PCs running Windows. We have only experienced this with one program, but it has occurred over multiple versions of the same program (i.e. 2017, 2018, etc.).
When we maximise the program window, the top of the window will go grey, and become "uninteractable" - that is, when you click on it, nothing happens, and right-clicking brings up the desktop pop up menu.

If we restore the window, the toolbar reappears, even if it gets stretched out to the screen borders (without maximizing it).
Is this a Windows thing?

A: The fact that the problem occurs only with this particular program, than more than likely the problem is the program itself.  I would suspect the developer of the application has made a mistake in designing  (not programming) the application, which is causing it to behave in this manner.  Other factors can be involved such as customization of your OS on your end, such as screen scaling.  However, ultimately that application is the only one with the issue.

A: It's probably a graphics/display issue - do you have a multiple monitor display?
I had the same problem today and fixed it by changing the screen resolution and then changing it back again.
See HERE: http://www.surfacetablethelp.com/2018/08/maximized-window-get-blank-empty-space-with-multi-monitors-in-windows-10.html


text:
Q: Convert Column to Polygon in Python to perform Point in Polygon I have written Code to establish Point in Polygon in Python, the program uses a shapefile that I read in as the Polygons.
I now have a dataframe I read in with a column containing the Polygon e.g [[28.050815,-26.242253],[28.050085,-26.25938],[28.011934,-26.25888],[28.020216,-26.230127],[28.049828,-26.230704],[28.050815,-26.242253]].
I want to transform this column into a polygon in order to perform Point in Polygon, but all the examples use geometry = [Point(xy) for xy in zip(dataPoints['Long'], dataPoints['Lat'])] but mine is already zip?
How would I go about achieving this?
Thanks

A: taking your example above you could do the following:
list_coords = [[28.050815,-26.242253],[28.050085,-26.25938],[28.011934,-26.25888],[28.020216,-26.230127],[28.049828,-26.230704],[28.050815,-26.242253]]

from shapely.geometry import Point, Polygon

# Create a list of point objects using list comprehension

point_list = [Point(x,y) for [x,y] in list_coords]

# Create a polygon object from the list of Point objects

polygon_feature = Polygon([[poly.x, poly.y] for poly in point_list])

And if you would like to apply it to a dataframe you could do the following:
import pandas as pd
import geopandas as gpd

df = pd.DataFrame({'coords': [list_coords]})

def get_polygon(list_coords):

    point_list = [Point(x,y) for [x,y] in list_coords]

    polygon_feature = Polygon([[poly.x, poly.y] for poly in point_list])

    return polygon_feature

df['geom'] = df['coords'].apply(get_polygon)

However, there might be geopandas built-in functions in order to avoid "reinventing the wheel", so let's see if anyone else has a suggestion :)


text:
Q: HTTP GET request cross-origin error for FRED API I am simply trying to get data from the FRED API using a get request. I keep getting "No Access-Control-Allow-Origin header is present on the requested resource. Origin null is there not allowed access'. I reviewed all of the API documentation and there is no reference to anything additional required for the get request. Is there a specific line-item I can add to my existing code to satisfy this 'Access-Control-Allow-Origin' header requirement? Could you give an example of what those line(s) would look like? I included my code with working API key. thank you
  <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>

function httpGet(theUrl)
{
    var xmlHttp = null;

    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", "http://api.stlouisfed.org/fred/releases/dates?api_key=1cee0e87e5e3362716028352d3d1c160", false );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}
</script>

</head>

<body>
<button onclick="httpGet()">http GET</button>

</body>
</html>

A: You function httpGet using cross-domain request if you domain is not stlouisfed.org. So if API response don't have Access-Control-Allow-Origin: * header all requests will fails.
As I understand FRED API is using only by desktop programs, not web apps.
But there is a iframe transport to circumvent this. I create html jsfiddle where you can press the button and see API result in iframe. But I have a problem with iframe onload event in this jsshell site - it always broken. You can add iframe.onload in your code to get the answer from API, then the form will change the iframe.

A:
I reviewed all of the API documentation and there is no reference to anything additional required for the get request.

Their documentation is not specific to JavaScript running in a browser.

Is there a specific line-item I can add to my existing code to satisfy this 'Access-Control-Allow-Origin' header requirement?

No. You need to make the request from your server.

Could you give an example of what those line(s) would look like? I included my code with working API key.

Your API key should be kept secret (which is any other reason to not do this directly with client side JavaScript).