text:
Q: How to load animation in background in cocos2d? I am currently developing one cocos2d game for iPad, in that game lot of animations is there. I have previously used zwoptex for creating spritesheet and adding animations in my project.
In my game 10 Levels is there, and after each level completed one animation will play, the animation is different for each level and animation image size is same as device screen size. so i am not create spritesheet file, instead of i am loading image directly. My problem is while animation it takes too much time for animation playing.
How to i fix it? please any one guide me. is it possible to load full screensize image(1024x768) in plist, because total 10 levels each level has 20 frames for animation, so 10X20 = 200 images need to load spritesheet.
I am using this code for animation
 CCAnimation *animation = [CCAnimation animation];
for(int i=1;i<=20;i++)
 {
  [animation addFrameWithFile:[NSString stringWithFormat:@"Level%dAni%d.png",level,i];
 }
 animation.delayPerUnit = 0.3f;
 animation.restoreOriginalFrame = YES;
 id action = [CCAnimate actionWithAnimation:animation];

My Question is it possible to load full screen animations with spritesheet? and animation loading time is differ and it takes too much time how to fix it?
Please help me..

A: By Using Cocos2D you can animate sprite sheet images easily.
Try following examples using Cocos2D
http://www.smashious.com/cocos2d-sprite-sheet-tutorial-animating-a-flying-bird/309/ http://www.raywenderlich.com/1271/how-to-use-animations-and-sprite-sheets-in-cocos2d
Try following examples without using Cocos2D
http://www.dalmob.org/2010/12/07/ios-sprite-animations-with-notifications/
http://developer.glitch.com/blog/2011/11/10/avatar-animations-in-ios/

A: Use NSThread and load your animation in this thread.
NSThread *thread = [[[NSThread alloc] initWithTarget:self selector:@selector(preloadFireWorkAnimation) object:nil] autorelease];
    [thread start];

-(void)preloadFireWorkAnimation
 {
      // load your animation here;
 }

A: Do the math and figure out the amount of memory you would need for 200 pics at 1024x768 pixels. Way too much memory for any iSomething device.
If you have a performance problem (ie are you running this on a device?), then there are two things you can do to improve image load speed:

*

*Convert your images to .pvr.gz (i recommend TexturePacker for this). They load significantly faster than .png.

*Use an RGBA4444 pixel format (again you can do this with TexturePacker), and set the texture format in cocos just prior to loading the images. Images will be smaller, take much less memory.

In your code, where you do the anim
    [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA4444];
    // load your images and do your anim
    ...
    // at the completion of the anim
    [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];


text:
Q: How to create an instance of an interface in GWT? How can i create an instance of an interface ?
example
@Connection(name="ClckCnt", version="1.0", description="Click Counter", maxsize=10000)
public interface MyInterface extends DataService{

    @Update("CREATE TABLE IF NOT EXISTS clickcount ("
      + "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
      + "clicked INTEGER)")
  void initTable(VoidCallback callback);

     @Update("INSERT INTO clickcount (clicked) VALUES ({when.getTime()})")
  void insertClick(Date when, RowIdListCallback callback);
}

public class WebApp implements EntryPoint{

    MyInterface myInterface = GWT.create(MyInterface.class);

    public void onModuleLoad(){

    }
}

This kind of example i have from the gwt-html5-database project. in this project is a sample application and they did it the same way but it doesnt work.
Somebody have an idea?
Greets.

A: See https://developers.google.com/web-toolkit/doc/latest/DevGuideCodingBasicsDeferred
You can either provide concrete implementations and chose the one to use depending on some properties (including, for example, user agent and/or locale), or use a generator. you can combine both: use a concrete implementation in some case, and a generator in another, depending on  properties.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to deploy an angular2 application as a webapp in azure Can someone help me deploy an angular2 application as a webapp in azure. I have a github enterprise setup. On my Jenkins server, I would like to do a no build. On successful completion of the build, I'd like to push it to a webapp.
Every deployment I attempted, failed on npm of one form or other. I don't want to create a VM and deploy a server.
I'd appreciate any help on this.

A: Deployment of all supported web applications to azure web app service ( PaaS and not IaaS VM as per your requirement) is possible by the following options

*

*from git CLI you can publish the code from your local repository to azure.

*linking an online repository like bitbucket, gitlabs to azure

*Powershell - publish code from your local repository to azure

*Azure CLI - publish code from your local repository to azure

*FTP option is available as well.

Check out this post to see how you can publish using git commandline https://learn.microsoft.com/en-us/azure/app-service-web/app-service-deploy-local-git


text:
Q: Show that the rings $R_1=F_5[x]/(x^2)$ and $R_2=F_5\times F_5$ are not isomorphic. Show that the rings $R_1=F_5[x]/(x^2)$ and $R_2=F_5\times F_5$ are not isomorphic.($F_5$ is the field with $5$ elements.)
My Work:
Since $(0,1)$ does not have an inverse, $F_5\times F_5$ is not a field. Since $x^2$ is reducible in $F_5[x]$, $F_5[x]/(x^2)$ is not a field. Also both $R_1,R_2$ have same number of elements. So, I was fail to prove that they are not isomorphic. Is there any property that do not satisfied by them together?

A: Hint: one ring has non-zero nilpotent elements, the other one hasn't.

A: (1). Let $A$ and $B$ be two rings (commutative with $1$) and let $\phi: A \rightarrow B$ be a homomorphism. If $\phi$ is an isomorphism then every non-zero nilpotent element of $A$ will map to a non-zero nilpotent element of $B.$
In this case, $A:= R_1$ contains a non-zero nilpotent element, $x + (x^2),$ but $B:= R_2$ has no non-zero nilpotent element.
(2). $R_1$ has only one prime ideal, the ideal generated by $x + (x^2)$ where as $R_2$ has two prime ideals, $ 0 \times F_5$ and $F_5 \times 0.$


text:
Q: RoR plugin/gem for html validation I am wondering if there is such a plugin or gem for Ruby on Rails that includes HTML validation (SGML or Tidy) in a testing cycle.
I am aware only about this plugin. Looking for alternatives...

A: I use be_valid_asset with rspec and cucumber. It uses the public W3C validator. It does not have the link checking that html_test has.
I use it in these two steps in cucumber's webrat_steps.rb:
Given /^(?:|I )am on (.+)$/ do |page_name|
  visit path_to(page_name)
  response.should be_valid_xhtml if ENV['VALIDATE_HTML']
end

When /^(?:|I )go to (.+)$/ do |page_name|
  visit path_to(page_name)
  response.should be_valid_xhtml if ENV['VALIDATE_HTML']
end

Then I can run rake VALIDATE_HTML=1 cucumber to validate all pages visited by my cucumber feature files.

A: Here's a Rack-based validator that can be used live: http://coderack.org/users/nerdEd/entries/95-rackvalidate

A: I am working on an all-in-one HTML/CSS validation gem for Ruby On Rails apps. It's name is Headhunter.
From the docs:

Headhunter is an HTML and CSS validation tool that injects itself into your Rails feature tests and automagically checks all your generated HTML and CSS for validity.
In addition, it also looks out for unused (and therefore superfluous) CSS selectors.

All you have to do is add gem 'headhunter' to your Gemfile in test environment:
group :test do
  gem 'headhunter'
end

The rest is all done automagically for you, and you'll get a statistic for your application's validness at the end of your tests, like this:
Validated 42 HTML pages.
41 pages are valid.
1 page is invalid.
Open .validation/results.html to view full results.

Validated 1 stylesheets.
1 stylesheet is invalid.
  application.css:
  - Invalid css: line 1: Property bla doesn't exist

Found 23 CSS selectors.
20 selectors are in use.
3 selectors are not in use: a img, #flash.failure, input[type='file']


text:
Q: Was my circuit victim of capacitor self-resonance? In order to generate a short pulse off a permanent constant current signal, I made this circuit.
It works well except that it created a very high frequency ripple which wreaked havoc all over the prototype board, not just the output, and brought the voltage of the entire board from 5V to 3V, sometimes less.
The frequency was so high that my 200Mhz oscilloscope couldn't see the wave but I could see that the line was very thick.
I solved the problem by adding a 15pF cap (C2) between the output and ground. Now the signal is perfect.
Before, when my circuit had problems, it was the same, just without this cap. There was already a 330K resistor to ground and I thought that would be enough to avoid this type of interference.
I think that the voltage drop was due to other ICs being pulsed extremely fast albeit at undefined levels.
Before finding out where the problem came from, the symptoms were not clear: The board worked as expected. Then the next day I changed something apparently not related and it started working unpredictably.
Is this phenomenon common? Should I be concerned about other flaws in my circuits which could be the cause of this? Or was it what is called "capacitor self-resonance"?

simulate this circuit – Schematic created using CircuitLab
The triangle on the left is a Schmidtt trigger. I can't confirm if the same effect would appear if the signal source came from another ic or a power supply directly.
The board is a composition of three 595 shift registers, schmidtt triggers, a 557 clock, 2 or 3 mosfets and a bunch of schottky diodes. It's powered by a linear regulator, itself powered by a 15V power supply. Changing the power supply to a completely different one didn't change anything. All the ICs have decoupling caps, which I think have also no effect as far as this board is concerned. Adding them didn't produce anything visible.

A: There isn't much difference between the two (they are right on top of each other), however there is probably much more going on with the design. I'm willing to bet you have one of the following problems:

1) Your ground is not continuous and has large amounts of parasitic inductance
2) Vcc has a large amount of parasitic inductance, or not enough local storage for the IC's with power filter caps.
The problem is the things you can't see. On the schematic we commonly draw Vcc and ground as one net. When the circuit is built we connect ground and Vcc with conductors, these conductors have resistance and inductance (and between them capacitance). Usually when you have these wierd problems, it's because you have too much inductance, and you've built and RLC filter with the resistor being the load the C being a power filter cap and the L being a wire to the IC.
Make sure you use large conductors and avoid daisy chaining Vcc and ground. Each IC's current should have a direct pathway back to the power supply, otherwise you'll have common mode problem.
Another thing that could be going on is the voltage regulator could be improperly compensated, check the datasheet and make sure you have a proper filter capacitor on the regulator.

A: Its not unheard of for high-speed discrete CMOS logic to self-oscillate if the source impedance is very high. Parasitic capacitance between the output and input terminal can form a relaxation oscillator.
While this may not be the source of your woes, it is something to be wary of, if the source impedance is very high (100's k Ohms and above). Your bypass cap reduces the effective source impedance at high-frequencies.


text:
Q: error with __security_init_cookie when using an imported function in a dll I'm trying to import an fonction from an dll using VS2010 with this code
 // test.cpp : définit le point d'entrée pour l'application console.
//

#include "stdafx.h"
#include<iostream>
#include<windows.h>
#include<map>
#include<string>

using namespace std;

namespace mido{
class ABC_YieldCurve;

}

typedef int (*buildDepoSwapCurve)(mido::ABC_YieldCurve *& depoSwapTermStructure, long asOfDate,
    std::map<std::string, double>& depoInstruments, std::map<std::string, double>& swapInstruments, std::string& error );

int _tmain(int argc, _TCHAR* argv[])
{
    buildDepoSwapCurve mybuildDepoSwapCurve;
    HINSTANCE hinstLib = LoadLibrary(TEXT("YieldCurve.dll"));
    if (hinstLib == NULL) {
                printf("ERROR: unable to load DLL\n");
                cin.get();
                return 1;
        }

     mybuildDepoSwapCurve = (buildDepoSwapCurve)GetProcAddress(hinstLib, "buildDepoSwapCurve");
        if (mybuildDepoSwapCurve == NULL) {
                printf("ERROR: unable to find DLL function\n");
                cin.get();
                FreeLibrary(hinstLib);
                return 1;
        }

    //Construction d'un depoInstruments
    std::map<std::string,double> mydepoInstruments;
    mydepoInstruments["1W"]=0.0382;
    mydepoInstruments["1M"]=0.0372;
    mydepoInstruments["3M"]=0.0363;
    mydepoInstruments["6M"]=0.0353;
    mydepoInstruments["9M"]=0.0348;
    //Construction d'un swap instrument
    std::map<std::string,double> mySwapInstruments;
    mySwapInstruments["1Y"]=0.0345;
    mySwapInstruments["2Y"]=0.037125;
    mySwapInstruments["3Y"]=0.0398;
    mySwapInstruments["5Y"]=0.0443;
    mySwapInstruments["10Y"]=0.05165;
    mySwapInstruments["15Y"]=0.055175;
    mySwapInstruments["25Y"]=0.05165;

    //l'objet myYieldCurve nul
    mido::ABC_YieldCurve * myYieldCurve;
    string t="";
    cout<< mybuildDepoSwapCurve(myYieldCurve,40000,mydepoInstruments,mySwapInstruments,t)<<endl;;

    cout<<"test";
    cin.get();

    FreeLibrary(hinstLib);
    return 0;
}

The result shows that the import of the dll and the function are succesful.
But I can not understand why there is the error (sorry it's in french)
Exception de première chance à 0x76bdb727 dans testWrapper.exe : Exception Microsoft C++ : QuantLib::Error à l'emplacement mémoire 0x0015f800..
Exception non gérée à 0x76bdb727 dans testWrapper.exe : Exception Microsoft C++ : QuantLib::Error à l'emplacement mémoire 0x0015f800..
However, my friend use VS2008 and this code works
The error when the code stops is:
    {
        /*
         * The /GS security cookie must be initialized before any exception
         * handling targetting the current image is registered.  No function
         * using exception handling can be called in the current image until
         * after __security_init_cookie has been called.
         */
        __security_init_cookie();

        return __tmainCRTStartup();
}

in the file crtexe.c
Thanks
I've removed the Remove the /GS (Buffer Security Check) but the problem now is in the code dbgheap.c
 extern "C" _CRTIMP void __cdecl _free_dbg(
        void * pUserData,
        int nBlockUse
        )
{
        /* lock the heap
         */
        _mlock(_HEAP_LOCK);

        __try {
            /* allocate the block
             */
            _free_dbg_nolock(pUserData, nBlockUse);
        }
        __finally {
            /* unlock the heap
             */
            _munlock(_HEAP_LOCK);
        }
}

A: Remove the /GS (Buffer Security Check) in your project settings :)


text:
Q: Creating Listview dynamically in Android I Have a two dimensional string array,
I want to create a 3 column list-view, that display data from the string array, it should have the same number of rows that the size of the string array.
This is my string array:
String[][] data = {
   {"001", "JOHN ","1001" },
   {"002", "SIBIN", "1002" },
   {"003", "TOM ",   "1003" },
   {"004", "FREEDY", "1004" }
   };

I want to display it in a Listview like
ID    NAME   VACANCY ID
001   JOHN    1001
002   SIBIN   1002
003   TOM     1003
004   FREEDY  1004

Also when I click a list-view item, it redirect to another page with the listview id
How is this possible?  I am new in the android development, I know only the basics, and I only know how to create listview.

A: for that you need a customize list view first you should add a listview in your main.xml(just an eg) file then create a class like this
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
      private final Context context;
      private final String[] values;
      DataHelper dh;

      public MySimpleArrayAdapter(Context context, int textViewResourceId, String[] values) {
        super(context, textViewResourceId, values);
        this.context = context;
        this.values = values;

        dh=new DataHelper(getApplicationContext());
      }

      @Override
      public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.list_name, parent, false);
       textView = (TextView) rowView.findViewById(R.id.textname);

        textView.setText(values[position]);
        // Change the icon for Windows and iPhone
        textView.setOnClickListener(new View.OnClickListener() {
               public void onClick(View v)
               {
                   Toast.makeText(this,""+values[position],10000).show();
               }
               });

        return rowView;
}

R.layout.list_name this will be the new xml file which will load the contents to the list view
and the the final step just in your on create method do this
con = (ListView) findViewById(R.id.main_listView);
 MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(MainActivity.this,  R.id.main_listView ,data);// data is String array valu to be added in list view
    //setting the adapter
    con.setAdapter(adapter);


text: Q: JS for muti Tabs search. Content shown on click below tabs can anyone advice a JS to achieve something like this? I am doing a search filter, where i have 4 filter groups like (Tab1), (Tab2), (Tab3), (Tab4). I want to show "Tab content" (search filters), after clicking on particular Tab button. For better understanding please see the image below. I found many JS demos for opening one tab and closing other, but I didn't find exactly what I need. I need tabs side by side, and content shown below them so if anyone can help with that, please get back to me. Many thanks


text:
Q: LDAP Integration with two different system Our Java based web application uses LDAP authorization and authentication mechanism .
And same for our version control system (SVN) which is using LDAP authentication.
In new requirement we've to integrate SVN with Web Application - like execute some basic SVN command through web application.
As I dont want use hard coded userID passowrd to connect SVN.
Can anyone suggest me a good way to connect SVN through Web Application as both system using LDAP ?


text:
Q: What happens to data when onPause is called on Activity I have a activity running on a app, when user clicks a search icon another activity (Google Maps) opens.
 So I am assuming the first activity onPause is called, and when Maps activity is completed the first Activity onResume is called.
So my question is, what happens to all the data entered by users and assigned to variables in the first activity before the Maps activity is called, is it lost?

A: Android stores user data for views when you start another activity.
onSaveInstanceState method will be executed and store the data.

Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).

you can check more info here.
If you want to keep your variables you can override onSaveInstanceState
static final String STATE_SCORE = "playerScore";
...

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);

    super.onSaveInstanceState(savedInstanceState);
}

and to get them back,
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    }
    ...
}

A: No, not all. Data entered by user will be still there, but you must save variables in
@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }
and get them back in
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
}

A: It depends on the situation when your backstack is not cleared. Please read that and there is some explanation.


text:
Q: How to design an angular2 project I have 2 html's
1) common-html.html
2) After-login.html
1) common-html.html--This is a layout page of my app because this contains my background image and little css.

                        <router-outlet></router-outlet>

2)This contains my navbar and side menu etc which should be appeared after login

        {{name}}

PROFILE

SOCIAL ADDRESSES

CUSTOM INFO

MY SOCIETY(ALL)

PERSONAL

PROFESSIONAL

                    <router-outlet></router-outlet>

I am not sure what to do in main module.ts and main.ts and in index.html.Can anyone suggest help.Thanks.

A: If you're "completely helpless", it might be a good thing to look at Angular CLI, which does 99.99% of the initial setup for you and also includes some very helpful generators to add components, pipes, services, etc. to your project.
Have a look: https://github.com/angular/angular-cli
However, if you're new to Angular (and that is why you are "helpless"), you should probably learn angular first.
Start with the Tour of Heroes and make your way from there.


text: Q: GKE Containerd node pool with nexus insecure registry Is there are way to authenticate and pull image from a insecure nexus registry to a containerd instance (GKE Containerd node pool) like for docker where we can create docker configjson secret. Coudn't find any doc related to this.


text:
Q: Floating menu bar using HTML/CSS? wondered if any one knew of a way of creating a floating menu bar that sticks to a point on a page until the browser window gets far enough down the page and unsticks it and then the menu bar begins to scroll along with it. The effect I want is the exact same as this http://www.jtricks.com/javascript/navigation/floating.html javascript menu. However, I really want to do this with CSS. I am aware I can make the div Absolutely positioned and it will move down the page, I tried making one DIV relative positioned (parent div) and then another div inside this which was absolute positioned, but I could not get this to work. Does any one know how to make this work with CSS  or does it need to be JS?
Thanks in advance.
Jon.

A: I believe using javascript is the only solution to get the effect you described. Here's a quick demo of a banner that starts in a absolute position and goes to fixed when the user scrolls.

$(window).scroll(function(){
    if ($(window).scrollTop() >= 200)
    {
        $("#floatbar").css({position:'fixed',left:'0',top:'0'});
    }
    else
    {
        $("#floatbar").css({position:'absolute',left:'0',top:'200px'});
    }
});

A: well if you do NOT need the animation, than just use
position: fixed;
in the css.
if you want it animated you need to use javascript.
for example in jquery:
$(window).scroll(function(){
   $('#menu').css({
       right: 0,
       top: 0
   })
})

A: Well you can't do it with absolute positioned div inside of a relative. Fixed position is basically an absolute positioned div, positioned relatively to the window. I'd say you definately need javascript here.

A: This should be rather easy with a fixed sidebar, and a floating content section. Try something like this...
#container {
    width: 960px;
    margin: 0 auto;
    overflow: hidden;
    position: relative;
}

#sidenav {
    width: 300px;
    position: fixed; /*--Fix the sidenav to stay in one spot--*/
    float: left; /*--Keeps sidenav into place when Fixed positioning fails--*/
}

#content {
    float: right; /*--Keeps content to the right side--*/
    width: 620px;
    padding: 0 20px 20px;
}

A: This is old post but CSS has changed a lot since then, we can do a floating menu with plain CSS. See sample code below. Credit to https://www.quackit.com/css/codes/css_floating_menu.cfm

  main {
    margin-bottom: 200%;
  }
  .floating-menu {
    font-family: sans-serif;
    background: yellowgreen;
    padding: 5px;;
    width: 130px;
    z-index: 100;
    position: fixed;
    right: 0px;/* You can change float left/right */
  }
  .floating-menu a,
  .floating-menu h3 {
    font-size: 0.9em;
    display: block;
    margin: 0 0.5em;
    color: white;
  }
<!DOCTYPE html>
<title>Example</title>

Scroll down and watch the menu remain fixed in the same position, as though it was floating.

Floating Menu

    CSS
    HTML
    Database

A: I believe it needs to be JS. I can imagine it can be rather simple with jQuery and I really cannot think of any way to achieve this only with CSS. I'll try to think about it, but I doubt I'll find a solution.


text:
Q: Access Util.logger from multiple classes I'm new to util.logging so this might seem a trivial question to some but anyway here goes..I'm using Java's Util.logger to log messages. I'm trying to declare a logger in a single class and accessing it from other classes for logging messages.
Logger class
package util;

import java.util.logging.*;

public class Logger {

public Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

 }

I'm trying to access this logger in other class as follows..
package mycode;

import util.Logger;

public class MYcode{

private void test(){
 LOGGER.fine("Sample message");
}
}

Compilation Error message..
error: cannot find symbol
[javac]LOGGER.fine("Sample message");

When I'm declaring logger in Mycode class then I'm not getting any error but when declaring it another class I'm getting an error. Any idea where I'm going wrong??

A: Just keep using in all classes needing the logger the same line:
public Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

This way you are creating many references to one instance of logger identified by the global name.

A: The problem is your 'LOGGER' is NOT static, so you are NOT able to access.
Logger class:
package util;

import java.util.logging.*;

public class Logger {

public static final Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

 }

Accessing logger in other class:
package mycode;

        import util.Logger;

        public class MYcode{

        public void test(){
         LOGGER.fine("Sample message");

        }
    }


text: Q: Can you color a cell based on another cell's contents in MS Word? I have a project I'm working on with reports in MS Word that have similarly structured tables, but some of the cells are different colors depending on the report. To fill them in, I'm using a merge. I know I can format a cell or text based on the cell contents, but what about adjacent cells? I would like for cells to be shaded a light blue if the cells next to them have a specific text. Obviously this is easy in Excel, but is it possible in Word?


text:
Q: Python script opens process but not sending mail I'm in the making of a script that checks if a program is running and then sending a email to confirm it. So far my script only opens the program but does not email me. I'd like to change into checking process and then email instead of opening the program.
import smtplib
import sys
import os
import csv
import subprocess
from subprocess import CalledProcessError, Popen, PIPE

# Set up mail info
FROM = "it@mail.com"
TO = ["mine@mail.com"] # must be a list
SUBJECTERR = "Batchserver runnning"
TEXTERR = "Batch server running"
SUBJECT = "Batch Server status "
TEXT = "Batch Server running relax"

#Gives response
cmd = '\\\\sesrv414\\Applications\\Software\\BIN\\system.EXE'
p = Popen(cmd, stdin=PIPE, bufsize=0)
if p.returncode != 1:
  raise CalledProcessError(p.returncode, cmd)
  server = smtplib.SMTP("email.serv.net",25) # Send the mail
  messageErr = "From:%s \nTo:%s \nSubject:%s \n\n%s\n" %(FROM, ", ".join(TO),
  SUBJECTERR,   TEXTERR)
  server.sendmail(FROM, TO, messageErr)
  server.quit()
  raise

 sys.stderr.close();
 sys.stderr = sys.__stderr__

A: Since you raise an exception before sending email.
You have to install psutil first to check process in windows OS.
If your process's name is not 'system.EXE', you will have to change value of variable name in the code.
Try this:
import smtplib
import sys
import os
import csv
import subprocess
from subprocess import CalledProcessError, Popen, PIPE
import psutil
import re

# Set up mail info
FROM = "it@mail.com"
TO = ["mine@mail.com"] # must be a list
SUBJECTERR = "Batchserver runnning"
TEXTERR = "Batch server running"
SUBJECT = "Batch Server status "
TEXT = "Batch Server running relax"

#Gives response

name = "system.EXE"

running = False
for process in psutil.process_iter():
    if re.search(name, repr(process)):
        running = True
        break
if not running:
    cmd = '\\\\sesrv414\\Applications\\Software\\BIN\\system.EXE'
    p = Popen(cmd, stdin=PIPE, bufsize=0)

server = smtplib.SMTP("email.serv.net",25) # Send the mail
messageErr = "From:%s \nTo:%s \nSubject:%s \n\n%s\n" %(FROM, ", ".join(TO),
SUBJECTERR,   TEXTERR)
server.sendmail(FROM, TO, messageErr)
server.quit()

sys.stderr.close();
sys.stderr = sys.__stderr__


text:
Q: Question regarding a section of an open set of the form $U \cup V$ Suppose I have some scheme $(X, O_X)$. Suppose I have two open subsets of X, $U$ and $V$.
I was wondering about the following:
1) Is $\Gamma (U \cup V, O_X) \cong \Gamma (U , O_X) \times_{\Gamma (U \cap V, O_X)} \Gamma (V , O_X)$? (here the product here denotes a fiber product)
1') Would it be $=$ or $\cong$ in 1)?
2) If the answer to 1) is yes, then this looks a lot like a section of a sheaf
when you glue two schemes together. I guess is it possible to interpret this as a section
of scheme (made by gluing together $U$ and $V$ along $U \cap V$ via the identity map?)
Thanks!


text:
Q: Git: Is there a way to git stash but be able to specify a branch name? I'm working along with some changes and I'm not sure about them. They may be the right way to proceed, but maybe I'm going down the wrong path. I want to save my work just in case I am doing the right thing but not continue with this line of development right now and return to where I was a half hour ago for example. Basically, do a stash but make the stash commit a real branch with a descriptive name.
something like
git stash save-stuff  // not a valid command

what I've been doing requires multiple commands
git commit -a -m 'not sure this is where I want to go'
git checkout -b save-stuff
git checkout original-branch // return to original branch
git reset --hard HEAD~1 // I don't always do this one.

This causes me displeasure.

A: Git history is always hierarchical, and that applies to git stash as well. git stash creates a new commit, relative to a specific commit, rather than a branch. As such, there is no need to save a Git stash with a specific name; in doing so, you would literally be creating a branch.
If you want to be able save a temporary piece of work that you are not confident is correct, the best thing to do would be to make use of a branch. Doing so will allow you, and anyone else working on the repository (should you push the branch to the origin), to be able to refer back to this point in time easily. You can make subsequent changes to this branch if your approach is found to be correct, and even squash the changes to make it seem like the questionable commit never existed.
Keep in mind that there is nothing stopping you from checking out an individual commit -- even on a branch that you are currently working on. This will allow you to revert back should you need to, and you can continue working from this old commit, even pushing to the same branch if desired.

A: Two steps :

*

*git stash has a subcommand git stash create, which basically creates the same commit as git stash but doesn't update the stash and does not touch your index or worktree

*git update-ref allows you to "update" a ref (for example : branch) without it being the current active branch

You can combine the two, either in a script :
# file git-snap:

#!/bin/bash

if git diff -s --exit-code HEAD; then
    echo " --- worktree is clean, nothing to save"
    exit 0
fi

# get name of active branch, to update a branch named wip/<branch> :
branch=$(git rev-parse --abbrev-ref HEAD)
ref="refs/heads/wip/$branch"

# call git stash create:
sha=$(git stash create)
# update a branch named 'wip/<branch>' :
git update-ref -m "save wip on $branch" "$ref" "$sha"

git log --oneline -1 "$ref"

(if you place the above git-snap script on your PATH, you can then simply invoke git snap)
or if you are into one liners :
git update-ref refs/heads/mystash $(git stash create)


text:
Q: fail to read locale using text/message and gotext, possibly importing other go file incorrectly? I wanted to learn how to do l10n in go and came across this one website.  Google said it was 5 days old which confused me as it looks like it was written in 2018.  For Reference the website is: https://phrase.com/blog/posts/internationalization-i18n-go/ and is focused on the content about 3/4 of the way through.  ( I was reading some comments and it seems others had issues but didnt understand how to solve them if possible.
I am currently using: go version go1.16.3 darwin/amd64
So, I found something which is great, using catalog to generate the l10n files I need, and then adding a new file which is referenced and then you can run it.  This example is using Greek.
Step one, make sure I had gotext in my cli.  This was done with: go get -u golang.org/x/text/cmd/gotext
Afterwards I created an empty go.mod file, and a main.go file  The main.go file contained the following information:
package main

//go:generate gotext -srclang=en update -out=catalog/catalog.go -lang=en,el

import (
    "golang.org/x/text/language"
    "golang.org/x/text/message"
    _ "golang.org/x/text/message/catalog"
)

func main() {
    p := message.NewPrinter(language.Greek)
    p.Println(language.Greek.String())
    p.Printf("Hello world!")
    p.Println()

    p.Printf("Hello", "world!")
    p.Println()

    person := "Alex"
    place := "Utah"

    p.Printf("Hello ", person, " in ", place, "!")
    p.Println()

    // Greet everyone.
    p.Printf("Hello world!")
    p.Println()

    city := "Munich"
    p.Printf("Hello %s!", city)
    p.Println()

    // Person visiting a place.
    p.Printf("%s is visiting %s!",
        person,
        place)
    p.Println()

    // Double arguments.
    miles := 1.2345
    p.Printf("%.2[1]f miles traveled (%[1]f)", miles)
}

and then did mkdir catalog and then go generate.  When you follow the how-to you will see that locale is created with the subfolders needed for localization. I created a second file in the el directory, called messages.gotext.json which i thought was weird because there is already a file in there called out.gotext.json so why the heck are there redundant files, beats me.  I figure there woudl really just be 1 file in there, the localization file which was translated.
Anyways, following the how-to, i created this second file, then ran the same code previously told: go generate && go run main.go.  Seems like it still prints in English, and I thought I was doing everything correct.
I thought I was doing this correctly but i see what the issue is.  What I am thinking is going on is that the Generated catalog file is not being properly referenced in my import.   generate is creating this catalog.go file, but i dont think that the file is being properly added to my main.go file?
Am i importing this Catalog file correctly?
It seems that the Author has no idea what he was doing and his answers to the comment questions verify that he doesnt know how his own code/how-to works.  So that is why I wanted to come to you all, to see if there is something to be done which can generate the catalog file I need and import it.


text:
Q: Does the alternating series $\sum_{n=1}^{\infty}(-1)^n$ converge? Does the series
$$\sum_{n=1}^\infty (-1)^n $$
converge? I was trying to use this as a convergent majorant for proving convergence of $$\sum_{n=1}^\infty (-1)^n \frac {\ln(n)} n $$ but I'm not sure if that would work. Any help is appreciated!

A: Think about what $\sum_{n=1}^{\infty}(-1)^{n}$ means
You get $-1 + 1 -1 + 1...$
Does that converge to a number? Clearly not, it goes back and forth between $-1$ and $0$
A convergent sum will get closer and closer to one particular value, and can in fact get arbitrarily close to that value, which clearly our sum does not.

A: Given $n\geq 1$, you have that $\frac{\ln n}{n}\geq 0$. Moreover, $n\mapsto \frac{\ln n}{n}$ is a decreasing function, which tends to $0$ as $n\to\infty$. Thus, you may apply the Alternating Series Test to conclude that the series $\sum_{n=1}^{\infty}(-1)^{n}\frac{\ln n}{n}$ converges.


text:
Q: How to export posts with featured image How do I export only posts that have a featured image?
I only want to export posts.

A: There's not an easy way to modify the export query that runs under /wp-admin/export.php.
It doesn't use the WP_Query or the get_posts() wrapper, instead it currently uses this query:
$post_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} $join WHERE $where" );

without explicit filters to it, though it's possible to filter few settings through the export_args filter.
In ticket #28146 it's suggested to rewrite it using get_posts() instead, but it's not currently active.
Workaround
Here's one type of a hack to only export posts with a featured image:

Here are the main parts for such a plugin:
Step # 1
First we add the HTML for our filter's settings:
/**
 * Custom Export Filters
 */
add_action( 'export_filters', function() {
?>

        <?php esc_html_e( 'With a featured image:', 'mydomain' ); ?>
        <input type="checkbox" name="wpse_with_featured_image" value="1">

<?php
} );

Step #2
Next we hook into export_wp to modify the export process:
/**
 * Modify the export query
 */
add_action( 'export_wp', function( Array $args )
{
    // User input
    $with_featured_image = filter_input( INPUT_GET, 'wpse_with_featured_image' );

    // Check if we should activate our custom filter
    if( wp_validate_boolean( $with_featured_image ) )
        add_filter( 'query', 'wpse_modify_export' );

    return $args;
} );

where the wpse_modify_export() callback is defined as:
/**
 * Inject sub-query to find posts with featured image
 */
function wpse_modify_export( $query )
{
    global $wpdb;

    // Target the next posts query
    if( false === strpos( $query, "SELECT ID FROM {$wpdb->posts}" ) )
        return $query;

    // Remove filter callback
    remove_filter( current_filter(), __FUNCTION__ );

    // Inject sub-query to find posts with featured image
    $sql = " {$wpdb->posts}.ID IN ( SELECT DISTINCT post_id
           FROM {$wpdb->postmeta} pm WHERE pm.meta_key = '_thumbnail_id' ) AND ";

    return str_replace( ' WHERE ', ' WHERE ' . $sql, $query );
}

Hope you can adjust this to your needs.


text:
Q: WordPress: deleted page still showing up and the slug is broken I have a WordPress page with a slug "blog" and I'm trying to delete it and create a new one with the same name, but even when I delete it, it still shows, i cleared the caches and i change the theme because I have a custom theme that i made to make sure it not a theme problem, but it still showing that page
What can I do?
Thanks!

A: Try these quick steps, I think that will 90% works.

*

*First backup your website, There are a lot of plugins that can do that perfectly with one click.

*Then reset your database, also there're a lot of plugins that can do that.

*check if the page still exists.

*If the problem is fixed then reinstall your theme, and use the backup file you made and you're all set!

Hope that helps!


text:
Q: Template member functions with trailing return type, giving errors even if unused I understand that template member functions are only generated if used. This is convenient if not all used types support such a function. However, this does not appear to work for functions with trailing return type specification. Below is a small experiment:
// helper function for case A workaround
template <typename A, typename T>
auto F(T&& x)
-> decltype(x.template f <A>())
    { return x.template f <A>(); }

// helper function for case B workaround
template <typename A, typename T>
auto G(T&& x)
-> decltype(x.g())
    { return x.g(); }

template <typename T>
struct S
{
    // case A: not ok in GCC + Clang
    template <typename A>
    auto f1()
    -> decltype(T().template f <A>())
        { return T().template f <A>(); }

    // case A workaround: ok in Clang + GCC
    template <typename A>
    auto f2()
    -> decltype(F <A>(T()))
        { return F <A>(T()); }

    // case B: ok in GCC, not ok in Clang
    template <typename A>
    auto g1()
    -> decltype(T().g())
        { return T().g(); }

    // case B workaround: ok in GCC + Clang
    template <typename A>
    auto g2()
    -> decltype(G <A>(T()))
        { return G <A>(T()); }
};

Please keep in mind that this sample is only meant to illustrate the issue, it is not useful in anything else.
S <T> can be instantiated for any type T that has appropriate member functions f, g.
However, if I try to instantiate S <int>, e.g. by S <int> s{};, I do get errors like type 'int' is not a structure or union. This happens for both cases f1, g1, which attempt to call template function f or non-template function g respectively on a value of type T (int in this case). It happens even though I am not trying to call f1 or g1 on object s. However, GCC is fine with the case of g1; Clang is not.
A workaround for case A (template member function f) is to use a helper function F, which is what f2 does, and works fine for both Clang and GCC. It appears to work because call T().template f <A>() is hidden from the declaration of f2, and the compiler is not looking into F <A>(T()) when type A is unknown.
The same workaround for case B (non-template member function g) is also working for both compilers.
I would appreciate some help in finding out what is going on. Which is the correct behaviour in each case? Which compiler is correct? Is there any other workaround in general?
I am using GCC 4.8.1 and Clang 3.3.

A: SFINAE only applies to the template arguments of the function, not the one inherited from the class.
A different solution is to include copy T to a second template argument but this is nothing more than a shorter version of your workaround:
#include <utility>
#include <type_traits>
struct Foo {
    template < typename T > T f() { return {}; }
};
template <typename T>
struct S {
    template <typename A, typename TT = T >
    auto f1()  -> decltype(std::declval<TT>().template f <A>()) {
        static_assert(std::is_same<T,TT>::value, "TT must be equal to T" );
        return TT().template f <A>();
    }
};

int main() {
    S<Foo> a;
    a.f1<int>(); // ok

    S<int> b;
    b.f1<int>(); // not ok
}


text:
Q: WP insert post PHP function dynamically generated Custom Fields Further to my previous question WP insert post PHP function and Custom Fields
We have a working insert post function that can also send over custom fields without yet knowing the ID. Please see the previous question for the answer. What we are trying to do now is have some of those custom fields dynamically load in. A session at the top of the page has loaded in all information from a post type called services. This is the code that then picks it up and inserts it into a new post.
    <?php
$my_post = array(
    'post_title' => $_SESSION['booking-form-title'],
    'post_date' => $_SESSION['cal_startdate'],
    'post_content' => 'This is my post.',
    'post_status' => 'publish',
    'post_type' => 'booking',
);
$the_post_id = wp_insert_post( $my_post );

__update_post_meta( $the_post_id, 'duration', $_SESSION['booking-form-actual-duration'] );
__update_post_meta( $the_post_id, 'picture', $_SESSION['booking-form-picture'] );
__update_post_meta( $the_post_id, 'totalprice', $_SESSION['booking-form-total-price'] );
__update_post_meta( $the_post_id, 'activityduration', $_SESSION['booking-form-total-duration'] );
__update_post_meta( $the_post_id, 'totaldives', $_SESSION['booking-form-total-dives'] );

query_posts('post_type=services'); while (have_posts()) : the_post();
__update_post_meta( $the_post_id, 'producttitle'.get_the_ID(), $_SESSION['products-form-title'.get_the_ID()]);
__update_post_meta( $the_post_id, 'productprice'.get_the_ID(), $_SESSION['products-form-price'.get_the_ID()]);
__update_post_meta( $the_post_id, 'productduration'.get_the_ID(), $_SESSION['products-form-duration'.get_the_ID()]);
__update_post_meta( $the_post_id, 'productdives'.get_the_ID(), $_SESSION['products-form-dives'.get_the_ID()]);
__update_post_meta( $the_post_id, 'productquantity'.get_the_ID(), $_SESSION['products-form-quantity'.get_the_ID()]);

 endwhile; ?>

Notice the query posts and use of get_the_ID() to differentiate. The same thing occurred with the session at the top of the page to load in the data.
The code that then receives it is as follows. Notice that the reason for the IF statement is to only display the data of items that had quantity. Other php codes on the page retrieve the other custom posts.
<?php query_posts('post_type=services'); while (have_posts()) : the_post();
        $SPtitle = get_post_meta($post->ID, 'producttitle'.get_the_ID(), true);
        $SPprice = get_post_meta($post->ID, 'productprice'.get_the_ID(), true);
        $SPduration = get_post_meta($post->ID, 'productduration'.get_the_ID(), true);
        $SPdives = get_post_meta($post->ID, 'productdives'.get_the_ID(), true);
        $SPquantity = get_post_meta($post->ID, 'productquantity'.get_the_ID(), true);
        if ( $SPquantity ) {
        echo '

',the_post_thumbnail(array(50, 50, true)),'

',$SPquantity,' ', $SPtitle,'

',the_excerpt(),'<input name="product_price_PRI_',get_the_ID(),'" id="product_price_PRI_',get_the_ID(),'" type="hidden" value="',$SPprice,'">
<input name="product_price_total_PRI_',get_the_ID(),'" id="product_price_total_PRI_',get_the_ID(),'" type="hidden" value="">
<input name="product_duration_PRI_',get_the_ID(),'" id="product_duration_PRI_',get_the_ID(),'" type="hidden" value="',$SPduration,'">
<input name="product_duration_total_PRI_',get_the_ID(),'" id="product_duration_total_PRI_',get_the_ID(),'" type="hidden" value="">
<input name="product_dives_PRI_',get_the_ID(),'" id="product_dives_PRI_',get_the_ID(),'" type="hidden" value="',$SPdives,'">
<input name="product_dives_total_PRI_',get_the_ID(),'" id="product_dives_total_PRI_',get_the_ID(),'" type="hidden" value="">

<input name="product_quantity_PRI_',get_the_ID(),'" id="product_quantity_PRI_',get_the_ID(),'" type="hidden" title="" value="',$SPquantity,'"/>

';
}
else {
echo '';
};?>
                <?php endwhile; ?>

Right so I hope that explains what I am trying to do. And may I point out that it is all functional with the exception of the query area services. Hence why I have provided you with that segment of code. Does anybody know why that bit isn't working.
Marvellous, Thanks.

A: <?php
              $thispostID = $post->ID
              ;?><?php

              query_posts('post_type=services'); while (have_posts()) : the_post();

Needs to get the post id of the master post before querying the services.
Change all references to $post->ID to $thispostID


text:
Q: How to insert NULL into Django's DateField? I have an optional datefield in my django model:
award_grant_date = models.DateField(null=True, blank=True)

When the user leaves the date field blank, NULL is inserted into the DateField, otherwise the date is inserted.
However, if the user does enter a date into the DateField, and the user has selected some other specific data in the form, then I want to insert NULL into the DateField.
So, in my form I have the following code:
    class AwardGrantDetailsForm(forms.Form):
    ...
    award_grant_date = forms.DateField(
    widget=forms.DateInput(attrs={'id':'id_award_grant_date'}),
    input_formats=settings.DATE_INPUT_FORMATS,
    label=_('Date'),
    required=False)
    ...
    elif cd_agdf['award_grant_type'] == 8888 or cd_agdf['award_grant_type'] == 9999:

        self.cleaned_data['award_grant_type_description'] = ''
        self.cleaned_data['award_grant_date'] = 'NULL' //this is the issue here!

The error I am getting is:
[u"'NULL' value has an invalid date format. It must be in YYYY-MM-DD format."]

I cannot  seem to get the syntax correct to enter the NULL in to the award_grant_date date field.
I am using bootstrap datepicker and django 1.4.
How do I write the code self.cleaned_data['award_grant_date'] = '' to insert the required NULL? I have set the models field to null=True, blank=True!

A: NULL value has an invalid date format. It must be in YYYY-MM-DD format
If you want to store Null value into model use model_field = None
Solution:
registration_date = request.POST.get('registration_date')

if not registration_date:
    registration_date = None

#StudentInfo is my model
student = StudentInfo(name=request.POST.get('name'), std=request.POST.get('std'), registration_date=registration_date)

#Now you can save your model data
student.save()

A: The Python representation of database null is None:
self.cleaned_data['award_grant_date'] = None


text:
Q: Copying Shape_Length and Shape_Area data (replace geometry tool) to other rows, or suitable alternatives using ArcMap? I am working on mapping extents for historical construction plans using ArcMap 10.6. I have sets of these blueprints that I must draw out dozens of similar polygons using the replace geometry tool, but on the larger and more complex polygons, I find myself making errors that slow my workflow down.
Is there is not a way for me to copy the polygon data, so that I only need to make one polygon that can be moved to other rows, what would be an alternative other than just continuing to draw out each sheet?


text:
Q: Laravel Eloquent using ->selectRaw() I'm trying to implement the code below. But, of course, my  $apartment_list is empty, and I only have the calculated distance and services & sponsors empty. So I know that the code is wrong; how can I fix it?
$apartment_list = Apartment::with(['services', 'sponsors'])
    ->selectRaw('( 6371 * acos( cos( radians(?) ) *
                    cos( radians( latitude ) )
                        * cos( radians( longitude ) - radians(?)
                    ) + sin( radians(?) ) *
                        sin( radians( latitude ) ) )
                    ) AS distance', [$lat_from, $lon_from, $lat_from])
    ->orderByRaw('distance')
    ->havingRaw("distance < ?", [$km_radius])
    ->get();


text:
Q: Compute mean pairwise covariance between elements in a list I have the following data frames:
# df1
id   cg_v
1       a
2       b
3     a b
4     b c
5   b c d
6       d

# df2
id  cg
1    a
2    b
3    a
3    b
4    b
4    c
5    b
5    c
5    d
6    d

I need to add a column to df1 that contains the mean covariance computed across each pair of elements in cg_v. If cg_v contains only one element, then I would like the new column to contain its variance.
I can get a covariance matrix by cov(crossprod(table(df2)))
#          a         b          c          d
a  0.9166667 0.0000000 -0.5833333 -0.6666667
b  0.0000000 2.0000000  1.0000000  0.0000000
c -0.5833333 1.0000000  0.9166667  0.3333333
d -0.6666667 0.0000000  0.3333333  0.6666667

What do I do from here?
The end result should be like this:
# df1
id   cg_v      cg_cov
1       a   0.9166667
2       b   2.0000000
3     a b   0.0000000
4     b c   1.0000000
5   b c d   0.4444444  # This is equal to (1.0000000 + 0.3333337 + 0.0000000)/3
6       d   0.6666667

Code to generate df1 and df2:
df1 <- structure(list(id = c(1L, 2L, 3L, 4L, 5L, 6L),
                      cg_v = c("a", "b", "a b", "b c", "b c d", "d")),
                 .Names = c("id", "cg_v"),
                 class = "data.frame", row.names = c(NA, -6L))

df2 <- structure(list(id = c(1L, 2L, 3L, 3L, 4L, 4L, 5L, 5L, 5L, 6L),
                      cg = c("a", "b", "a", "b", "b", "c", "b", "c", "d", "d")),
                 .Names = c("id", "cg"),
                 class = "data.frame", row.names = c(NA, -10L))

A: I think I found a solution for this problem using data.tables and reshape. What do you want to do with the three letters b c d? I assumed that you want to have the covariance of the first two letters:
        require(reshape)
        require(data.table)
        dt1 <- data.table(id = c(1L, 2L, 3L, 4L, 5L, 6L),
                          cg_v = c("a", "b", "a b", "b c", "b c d", "d"))
        dt2 <- data.table(id = c(1L, 2L, 3L, 3L, 4L, 4L, 5L, 5L, 5L, 6L),
                              cg = c("a", "b", "a", "b", "b", "c", "b", "c", "d", "d"))
        cov_dt <- data.table(melt(cov(crossprod(table(df2)))))
        dt1 <- cbind(dt1, t(sapply(strsplit(as.character(df1$cg_v), " "), function(x)x[1:2])))
        #replace the na with the first colomn
        dt1[is.na(V2), V2 := V1]

        # Merge them on two columns
        setkey(dt1, "V1", "V2")
        setkey(cov_dt, "X1", "X2")
        result <- cov_dt[dt1]
> result[,.(id, cg_v, value)]
   id  cg_v     value
1:  1     a 0.9166667
2:  3   a b 0.0000000
3:  2     b 2.0000000
4:  4   b c 1.0000000
5:  5 b c d 1.0000000
6:  6     d 0.6666667

Variant which also works if there are more than 2 letters (not the most efficient code):
require(reshape)
require(combinat)
df1 <- data.frame(id = c(1L, 2L, 3L, 4L, 5L, 6L),
                  cg_v = c("a", "b", "a b", "b c", "b c d", "d"))
df2 <- data.frame(id = c(1L, 2L, 3L, 3L, 4L, 4L, 5L, 5L, 5L, 6L),
                      cg = c("a", "b", "a", "b", "b", "c", "b", "c", "d", "d"))
cov_dt <- cov(crossprod(table(df2)))
mat <- sapply(strsplit(as.character(df1$cg_v), " "), function(x) if(length(x) == 1){c(x,x)} else(x))
# Should be all minimal 2
sapply(mat, length) > 1
mat <- sapply(mat, function(x) matrix(combn(x,2), nrow = 2))
df1$cg_cov <- sapply(mat, function(x) mean(apply(x,2, function(x) cov_dt[x[1],x[2]])))
> df1
  id  cg_v    cg_cov
1  1     a 0.9166667
2  2     b 2.0000000
3  3   a b 0.0000000
4  4   b c 1.0000000
5  5 b c d 0.4444444
6  6     d 0.6666667


text:
Q: Hibernate Criteria one to many association, mutiple objects public class Company{

    private Long id;
    private String companyName;
    private List<Employee> employees;

}

public class Employee{

    private Long empid;
    private String fstName;
    private String lstName;
    private String sal;
    private Company company;

}

using Hibernate criteria api, I want to construct the following SQL
select compantName from company c,employee e where  c.id = e.companyid and
    (e.firstName like '%john%' and e.lastname like '%doe% ) or
    (e.firstName like '%james%' and e.lastname like '%bond% ) or
    (e.firstName like '%mike%' and e.lastname like '%adams% )

Assume on UI user can search for firstname or last name or sal or company name or any one of
combinations
Also more important, user can search for multiple employees at a time
I came up with the following code. Please suggest what is the best approach to handle above
requirement
 DetachedCriteria criteria = DetachedCriteria
                .forClass(Company.class);

    criteria.createAlias("employees","employees");
    Disjunction or = Restrictions.disjunction();

      for(Employee emp : employees){
        or.add(Restrictions.and(Restrictions.ilike(
            "employees.fstName",emp.getFstName(), MatchMode.ANYWHERE),
        Restrictions.ilike(
            "employees.lstName",emp.getLstName(), MatchMode.ANYWHERE)));
        criteria.add(or);

       }

A: var criteria = DetachedCriteria.forClass(Company.class)
                   .CreateAlias("employees","emp",JoinType.LeftOuterJoin)

using criteria obtained above you can add Restrictions as you like
use Restrictions.ilike("emp.<propertyName>"... for adding restrictions on Employee
use Restrictions.ilike("this.<propertyName>"... for adding restrictions on Company.
You can use Restrictions.Or() between the restrictions for Company and Employee with
Restrictions.And() between restrictions for Employee.
The JoinType helps you select Company entities irrespective of the Employees
Check out this for better understanding of using ICriteria in Hibernate.
Pay special attention to the use of CreateAlias and CreateCreteria which help you to add Restrictions effectively.
Hope this serves as a guideline to build your Criteria.
Edit
adding this part to explain how to add the condition value.
Consider Search as a container object getting the info from the View to the Data access layer.
public class Search{
   private String Value;
   //getter and setter...
}

In your data access layer you can get the criteria from the top snippet of code and using
      search.getValue()!=null && !"".equals(search.getValue()){
             criteria.Add(Restrictions....);
      }


text:
Q: How to install Visual Studio for Mac from Terminal (Mac OS) I would like to install Visual Studio for Mac on ssh.
Therefore, I have to use Terminal for the installation.
I download the .dmg file and copy it from local computer to ssh.
Then, I follow this link, but it doesn't work.
I still can't use 'mcs' command to compile C# code.
Can anyone tell me how to install Visual Studio for Mac via Terminal?


text:
Q: Cut string after certain number of chracters in Unix Shell I have a string/file which contains some data that needs to be mailed using an API. But it doesn't allow message length to be greater than N.
So now I want to trim the contents of the file to N characters.
Suppose the contents of the file are as shown below:
2020-09-28 03:13:41,288 ERROR [.] [main]: java.lang.NullPointerException java.lang.NullPointerException
2020-09-28 03:13:41,298 ERROR [.] [main]: java.lang.NullPointerException java.lang.NullPointerException
at com.myPackage.anotherPackage.DoSomething.processSomeData(MagicallyPullData.java:98)
at com.myPackage.anotherPackage.DoSomething.processSomeData(MagicallyPullData.java:56)
at com.myPackage.anotherPackage.DoSomething.processSomeData(MagicallyPullData.java:112)

I want to get 50 characters for todays date say
[main]: java.lang.NullPointerException java.lang.NullPointerException

So today's date pattern should be matched, but date shouldn't be included, whole string should be shrunk to 50 characters after that.
I wrote the following
cat /home/myproject/logs/errors.log | grep "`date --date='today' '+%Y-%m-%d'`"

But this gives all the lines that have today's date.
This script is going to be a cron job that runs everyday.

A: Remove the date using cut -d' ' -f2-, then pipe it through head -c50 to get the first 50 bytes:
grep "`date --date='today' '+%Y-%m-%d'`" /home/myproject/logs/errors.log | cut -d' ' -f2- | head -c50

A: As an alternative to grep + cut, consider Awk.
awk -v ddmmyy="$(date +%Y-%m-%d)" '$1 == ddmmyy {
    print substr($0, 1, 50) }' /home/myproject/logs/errors.log

If you only want the first 50 characters from the first occurrence on today's date, simply add ; exit after the closing parenthesis, before the closing brace.
If you want only the text from character position 35 forward, change the second argument to substr from 1 to 35.


text:
Q: Handling infinite recursion XSL in Saxon I understand this question might be beyond Saxon and more related to the architecture of the application using it for transformations, but just wanted to give a try. Consider the following files-
XML
<?xml version="1.0" encoding="UTF-8"?>
<document>
    string
</document>

XSL
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xsl xs">

    <xsl:template match="/">
       <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="node()">
        <xsl:apply-templates select="."/>
    </xsl:template>

</xsl:stylesheet>

The XSL will go into an infinite recursion during the transformation aka stack overflow. My question is- Is there a way to stop or prevent this type of transformation from going into an infinite recursion? Any parameters that can be added to the command-line that can trigger a warning and gracefully stop?

A: Instead of relying on existing settings to address this sort of thing, you might just want to create your own.
Consider the following XSL run against the very simple XML you gave:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xsl xs">

    <xsl:variable name="recursion.limit" select="500" as="xs:integer"/>
    <xsl:variable name="new.line" select="'
'" as="xs:string"/>

    <xsl:template match="/">
        <xsl:value-of select="$new.line"/>
        <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="node()">
        <xsl:param name="recursion.count" select="1" as="xs:integer"/>

        <xsl:choose>
            <xsl:when test="$recursion.count <= $recursion.limit">
                <xsl:value-of select="'<' || name() || '>' || ':' || $recursion.count || $new.line" disable-output-escaping="yes"/>
                <xsl:apply-templates select=".">
                    <xsl:with-param name="recursion.count" select="$recursion.count + 1" as="xs:integer"/>
                </xsl:apply-templates>
            </xsl:when>
            <xsl:otherwise>
                <xsl:message>
                    <xsl:value-of select="'Recursion limit of ' || $recursion.limit|| ' hit.'"/>
                </xsl:message>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

</xsl:stylesheet>

This would certainly stop or prevent this type of transformation from going into an infinite recursion, but it's of course not automatic.  You have to set it up in code.  But if done, this can function as a home-brew max-depth setting.  All you would have to do at this point is parameterize the sheet to take such a value instead of baking it in as I did, and there's your setting.  And that takes care of your desire for parameters that can be added to the command line that can trigger some sort of warning and/or gracefully stop.  It's pure XSL, and as such, ought to be engine-independent, provided the XSL spec is being properly met by your engine of choice (which I really do hope is Saxon).

A: Did you try -opt:0 to disable optimizations ?


text:
Q: How to let user set time to run a task in google app engine My customer wants to set time (ex: Dec 13, 16:00 pm) to run a certain task.
I dont think cron job fits for it because customer dont know how to use google app engine SDK.
Is there any other way to do it?
Thanks

A: You can create a task and set the time when you want this task to be executed. From the documentation:

X-AppEngine-TaskETA, the target execution time of the task, specified
  in milliseconds since January 1st 1970.

A: You can use the task queue API: https://cloud.google.com/appengine/docs/python/taskqueue/ or even the defer API:  https://cloud.google.com/appengine/articles/deferred

A: If your customer is a user of your application, and there may be several users requesting tasks to be executed at different times, then you can save these requests to the datastore.  Create a cron job to run every hour (or however precise you need the timeframe) which checks the datastore to see if there are any tasks to run at that time - if so, run the proper script.
If this is just a one-time, or small number of tasks, you can do as Andrei suggested.


text:
Q: $\lim_{x\to p} f(x)=0 \iff \lim_{x\to p}| f(x)|=0$ $(\implies)$
Suppouse that $\lim_{x\to p}f(x)=0$. Then $\forall \epsilon > 0, \exists \delta > 0$ such that $0<|x-p|<\delta \implies |f(x)-0|<\epsilon$.
$||f(x)| - |0|| \leq |f(x)-0|<\epsilon$, so $||f(x)| - |0|| <\epsilon$, and since $|0|=0$ we have that $||f(x)| - 0| <\epsilon$.
$(\Longleftarrow)$
So, no we must suppouse that $\lim_{x\to p}|f(x)|=0$. Then $\forall \epsilon > 0, \exists \delta > 0$ such that $0<|x-p|<\delta \implies ||f(x)|-0|<\epsilon$. So the first direct is the case.
Can anyone help me to prove this second part? I can't see how

A: Given that $\lim_{x\to p} f(x)=0$. Note that $|f(x)|=||f(x)||$.
Every definition is "if and only if" so the following holds:
$$\lim_{x\to p} f(x)=0 \iff (\forall\epsilon\gt0)(\exists\delta\gt0)( \forall x\in (p-\delta,p+\delta)\setminus\{p\}\implies |f(x)|\lt\epsilon)\iff (\forall\epsilon\gt0)(\exists\delta\gt0)( \forall x\in (p-\delta,p+\delta)\setminus\{p\}\implies ||f(x)||\lt\epsilon)$$
Noting that $||f(x)||=||f(x)|-0|$, it follows that $\lim_{x\to p}|f(x)|=0$.
Your proof is also correct for the first part. To complete the proof in OP, just note that $|f(x)|=||f(x)||=||f(x)|-0|$ and then you are done.


text:
Q: Menu nav dropdown links don't work on home nav only Site I did not build but trying to help with, recently, (don't recall it being an issue before so maybe some update jacked it up?) no longer shows the hover on the drop downs of the links from the home page, thus also is not clickable. The top nav links are but the subpages/dropdowns do not.
However, if you click to another page, they do.
I did see in another question about adding the following CSS
nav ul.main-menu {
    z-index: 10;
}

of which I did try in the Theme Options Custom Code, didn't work, tried in the Header JS code for s&g, didn't work.
All plugins are up to date, WP is up to date, theme - some Roofer theme and WP Bakery = all up to date, php was updated a month or so ago (which stuff started breaking).   They have a TON of stuff (plugins) that they likely don't need or use (which I've mentioned) but you know how it is when folks build their own stuff and you need to fix it, well that is where I am at.  Please help.
Site is https://affordableroofingfl.com/  Thanks

A: This is caused by the dropdown menu element <ul class="dropdown-menu dropdownhover-bottom animated zoomIn" role="menu"> being above its child list items in the Z axis.
This makes these underlying link elements unclickable.
Relative positioning of these <li> children elements "activates" the already set value of their CSS property z-index and they become clickable again.
CSS rule to fix it:
.dropdown .dropdown-menu li {
    position: relative;
}


text:
Q: How to download older version of ginac through git I want to download older libraries from a git repository to desktop. How one does it?
For example I am trying to download ginac_1-6-5 from
http://www.ginac.de/ginac.git/

A: *

*Clone the repository.

The link you gave is to the web interface to the repository. The actual repo is at git://www.ginac.de/ginac.git.
$ git clone git://www.ginac.de/ginac.git
Cloning into 'ginac'...
remote: Counting objects: 20743, done.
remote: Compressing objects: 100% (7128/7128), done.
remote: Total 20743 (delta 17104), reused 16648 (delta 13581)
Receiving objects: 100% (20743/20743), 5.98 MiB | 1.72 MiB/s, done.
Resolving deltas: 100% (17104/17104), done.

Now you have a complete copy of the repository and can check out any older version you like.

*See if they tagged their releases.

Tags give a name to certain commits, usually associated with a release. Not all projects use them, but this one does.
$ git tag -l
ginac_1-6-3
ginac_1-6-4
ginac_1-6-5
ginac_1-6-6
relase_0-5-1
release_0-5-0
release_0-5-2
release_0-5-3
...

*Check out a release.

Since a clone is the complete history, you can check out any release you like.
git checkout ginac_1-6-5

*Follow the "To install from git" instructions.

Many projects don't check in all their generated files, so the install process from the repository can be different. For example, ./configure is a generated file. So you'll have to follow the special "To install from git" instructions in INSTALL.

A: Alternatively, check out the archive of past releases at https://www.ginac.de/archives/.


text:
Q: What are the difficulties/issues to consider when allowing ZIP file uploads? I allow PDF files to be uploaded to my site (PHP).
I would like to offer the ability to also allow .zip files which contain PDF files in directories so it is easier for users to simply zip a directory and upload one file instead of uploading multiple zip files individual.
For those of you who offer a .zip file upload feature to your (PHP) website, what are the technical, security, and other issues you have faced?

A: Assuming the .zip gets unpacked eventually you would have to make sure the directory they get unpacked in is unreachable by the the clients' browsers (with .htaccess or by placing it outside the web root directory), and even in that case I'd still monitor the contents of the unpacked .zip to make sure they didn't contain anything that might prove harmful (php or other files run by the server, html spoofs).
Another issue is i guess the upload_max_filesize set in php.ini, you can make sure it can be set big enough to suit your purposes before you start coding.
edit: also read sarnold's answer ;)

A: Be careful how you unpack the zip, you could find yourself consuming far more resources than you expected. Perhaps some setrlimit(2) resource limits before unpacking would be wise.
The unzip(1) utility has several nice safety features built in; the -^ command line option turns off control-character filtering, so make sure you don't touch this :) and the -: command line option allows stupid pathnames like ../../../../etc/passwd. Make sure you're on at least version 5.50, so that those stupid pathnames are forbidden by default. (And don't use that command line option. I mention the options just so you can more easily find the documentation for them. :)
If you use an API, make sure it has options to prevent both kinds of silly filenames.

A: AFAIK, php can handle zip files pretty efficiently. Difficulties/Issues that I can think of is, while accessing the file where We need to extract the zip first, and then retrieve the actual needed file. Due to that reason, extracting a zip, might consume additional amount of server time, depending on the size of the file itself.
Where As, during uploads, I do not suppose there is any difficulties or issues specially emphasized on zip types.


text:
Q: Use an element from a parsered Java DOM XML to add a new element Okay so I am working on a program that calculates something then takes that data and adds it to an existing XML file in the same directory. I have used DocumentBuilder to parse the file and now need (at least this is what I think I need to do, please correct me I am wrong) to get an element from the parsered file and appendChild another element to it.
Here is the code so far
The imported packages:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;

and the function that actually parsers and edit the XML file:
public void saveIt(){
        DocumentBuilder bd = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = bd.parse("excersize.xml");
        Element root = doc.getElementsByTagName("root");
        Element today = doc.createElement(today);
        root.appendChild(today);
    }

When I try to compile this code here are the errors I get (fyi, this is a custom-made cmd):
Good Luck Sir: javac excersize.java
excersize.java:240: error: incompatible types
                Element root = doc.getElementsByTagName("root");
                                                       ^
  required: Element
  found:    NodeList
excersize.java:241: error: method createElement in interface Document cannot be
applied to given types;
                Element today = doc.createElement(today);
                                   ^
  required: String
  found: Element
  reason: actual argument Element cannot be converted to String by method invoca
tion conversion
2 errors

A: Method doc.getElementsByTagName("root") returns NodeList so change it,
Element root = doc.getDocumentElement();


text:
Q: How to detect text enters in the CTR+F input box How we can find text enters in the CTR+F input box with the core javascript?
In this screenshot, I have searched Of course text.
How we can find Of course text?

A: In general, you cannot invoke browser controls from inside the webpage - security, sandboxing, and all that.
A trick could be listening to Ctrl + F , prevent it and then capture all the keys user enters then do what you want to do .
window.addEventListener("keydown",function (e) {
    if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
        callBackCtrlF();
        e.preventDefault();
    }
})

then you could use :
function callBackCtrlF() {
     // do your stuff
}


text:
Q: PHP not running on Apache ARM I have installed ubuntu on a Beaglebone black.
  apache2 -v
  Server version: Apache/2.4.18 (Ubuntu)
  Server built:   2016-04-15T18:00:57

  php -v
  PHP 7.0.4-7ubuntu2 (cli) ( NTS )
  Copyright (c) 1997-2016 The PHP Group
  Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
  with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies

I see this is CLI version so I guess is not used for HTTP?
Following blog posts it says to install php5 but when I try this I get "no install candidate" but as I get a php version I guess this doesn't matter?
I have added the PPA via sudo add-apt-repository ppa:ondrej/php and tried to install PHP5
sudo apt-get install php5 libapache2-mod-php5
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package libapache2-mod-php5 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

Package php5 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'php5' has no installation candidate
E: Package 'libapache2-mod-php5' has no installation candidate

I have created a file called info.php and added the line  but when I run it it prints <?php phpinfo() ?> on the screen (have tried short tags as well). The file resides in /var/www/html.

A: Although sudo apt-get install php5 failed sudo apt-get install php5.6 worked and now php is working.


text:
Q: convert date to a specific format and pass to a file in unix I have requirement in unix. I have a file which has the end time of a workflow like the below:
End Time:[Thu oct 05:12:12:12 2017]

I have to convert this to  mm-dd-yyy hh24:mi:ss and write to another file.
Please let us know how can i do that?
Thanks,
Amit

A: Something like
grep input_filename -e "End Time:" | sed -E 's/End Time:\[\w{3}\s(\w{3})\s([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\s([0-9]{4}).*$/\1-\2-\6 \3:\4:\5/' | sed 's/jan/01/ig; s/feb/02/ig; s/mar/03/ig; s/apr/04/ig; s/may/05/ig; s/jun/06/ig; s/jul/07/ig; s/aug/08/ig; s/sep/09/ig; s/oct/10/ig; s/nov/11/ig; s/dec/12/ig' > output_filename

This is broken into three commands. First is grep to extract the line with the time you need. Second is sed to rearrange the date into the output format, but note that the month is still a string. The third command is another sed call and this replaces the month name with a number.
Caveats:

*

*the above regex are rather strict and will fail on simple deviations

*no need to split the regex stuff into two sed invocations, this could be handled in one

*or for that matter, the whole process could be more gracefully handled with python, perl, etc


text:
Q: Logs Don't get Written to ULS in SharePoint 2013 Foundation I've found that SharePoint Foundation 2013 has some problems with Logging to ULS. Whenever I try to case an exception on the website using GUI or I want to write a message to ULS from a webpart nothing gets logged to ULS.
How to reproduce without any custom code:

*

*Go to any list

*go to any list item

*replace the ID in the url to one that does not exist

*you'll get an error:

I've managed to reproduce this problem on all Foundation servers I could get my hads not. This includes:

*

*SharePoint 2013 Foundation SP1 (rereleased)

*SharePoint 2013 Foundation March 2015 CU: 15.0.4701.1000

*SharePoint 2013 Foundation April 2015 CU: 15.0.4711.1000

Additional info

*

*I can write Logs to ULS from Console apps or Powershell with no problems

*there are many useless logs from w3wp.exe and OWSTIMER.exe in ULS, but those are not exceptions, just some infromational spam

*Windows logs or ULS do not contain any hints as to what is going on. I've looked very carefully.

*clearing SharePoint cache does not help

*running SharePoint wizard does not help

*app pool account is a member Performance Monitor Users

*we have one farm with 2 WFE where only one of the servers gets logs written properly

*the problem has nothing to to with logging categories because this problem occures even when I causing it manually via standard OOB GUI (mentioned above).

There is a similar(but not duplicate) question with my bounty. You can answer there as well to get it.

A: Here is an answer to this mystery. After almost 9 months of utter misery we finally found that the source of the problem was in global.asax. More specifically, we replace SpHttpApplication with our custom class that inherits from SpHttpApplication.
Standard SharePoint's global.asax looks like this:
<%@ Application Language="C#" Inherits="Microsoft.SharePoint.ApplicationRuntime.SPHttpApplication" %>

We have modified it (with an Web application feature) to look like so:
<%@ Assembly Name="Microsoft.SharePoint" %>
<%@ Assembly Name="CustomDll"%>
<%@ Application Language="C#" Inherits="CustomDll.CustomSpHttpApplication" %>

So, basically, whenever we replace standard SpHttpApplication with a custom implementation on SharePoint 2013 Foundation we get no logs written via w3wp. Weirdly enough, it does not affect SharePoint 2013 Standard/Enterprise.
I was unable to dig deeper into the exact reason for this behavior since there are no errors anywhere present on the server while logging. It must be somewhere deep in COM-objects where some dark magic happens that prevents the logs from being written.
Update:
I've found out that more specifically, problem occurs when using one of those methods:
SPUtility.GetCurrentGenericSetupPath(xmlKernelConfigurationPath)

SPUtility.GetVersionedGenericSetupPath(xmlKernelConfigurationPath, 15)

Looks like these methods do not cause any exceptions, but as a consequence, logs do not get written. I know, it sounds incredible, but this is true. I'm still trying to dig deeper.


text:
Q: how to apply laplacian Basically I want to understand the solution,I am confused here how to apply laplacian $\Delta={\partial^2\over\partial x^2}+{\partial^2\over\partial y^2}$ on the object $M=|f|^2+|g|^2$ where $M$ is a constant and $f,g$ are holomorphic function, I assumed $f(z)=u(x,y)+iv(x,y),g(z)=p(x,y)+iq(x,y)$ so $M=u^2(x,y)+v^2(x,y)+p^2(x,y)+q^2(x,y)$

A: Hint: $\dfrac{\partial^2 u}{\partial x^2} + \dfrac{\partial^2 u}{\partial y^2} = 0$, and similarly for $v$, $p$, $q$.


text:
Q: My webview app does not loggin into facebook? I have a web site that is being use in a webView app.
But the login with Facebook in the WebView app is not working.. it send me to facebook login page but then do not returns to the App, and sometimes the screen remains all white..
the login in chrome works OK!
this is my facebook login script:
 window.fbAsyncInit = function() {
    FB.init({
      appId      : 'XXXX47035339XXX',
      xfbml      : true,
      status     : true, // check login status
      cookie     : true,
      version    : 'v2.0'
    });
  };

  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));

function basicAPIRequest() {
    FB.api('/me',
        {fields: "id,age_range,picture,email,first_name,last_name,gender"},
        function(response) {

          $.ajax({
        url: "loginSave.php",
        type: "post",
        data: {id:response.id,
          email:response.email,
          name1:response.first_name,
          name2:response.last_name,
          gender:response.gender} ,
        success: function (response) {

           window.location.href = 'index.php';

        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }
    });
        }
    );
  }
jQuery(document).ready(function(){

  jQuery("#load").click(function(e){
    $("#load").css("display","none")
       $("#spinWheel").css("display","block")
    if(typeof(FB) == "undefined") {
        alert("Facebook SDK not yet loaded please wait.")
      }
    FB.getLoginStatus(function(response) {
      if (response.status === 'connected') {

        basicAPIRequest();

      }
      else {
        FB.login();
      }
    });
  });

});

A: There are two problems in the code:

*

*You should use FB.getLoginStatus right after FB.init, to check if the user is authorized on page load

*You should use FB.login on user interaction, NOT in the asynchronous callback of FB.getLoginStatus. Some browsers may block the login popup.

More information: http://www.devils-heaven.com/facebook-javascript-sdk-login/


text:
Q: How to get shell script to work on gcloud CLI in PowerShell? I've installed the gcloud CLI according to https://cloud.google.com/sdk/docs/install.
When using cloud shell on browser, I could simply paste a script and it would work. But it won't do the same when using cloud CLI on Powershell.
Script:
# List Projects accessible to these credentials
PROJECTS=$( `
  gcloud projects list `
  --format="value(projectId)")

# Iterate over each Project
for PROJECT in ${PROJECTS}
do
  echo "Project: ${PROJECT}"
  # Check Compute Engine service
  ENABLED="$( `
    gcloud services list `
    --project=${PROJECT} `
    --filter=config.name=compute.googleapis.com `
    --format='value(state)')"
  # Is it enabled?
  if [ "${ENABLED}" = "ENABLED" ]
  then
    # Enumerate Disks that have `users` and output `name`
    gcloud compute disks list `
    --project=${PROJECT} `
    --filter="-users:*" `
    --format="csv(name,sizeGb,zone,status,type,lastAttachTimestamp,lastDetachTimestamp)"
  fi
done

Result on browser cloud shell: successfully iterated through projects and listed disks in that project.
Result on Powershell:
PS C:\WINDOWS\System32> C:\Users\minh.tran\Documents\Get Disk.ps1
At C:\Users\minh.tran\Documents\Get Disk.ps1:7 char:4
+ for PROJECT in ${PROJECTS}
+    ~
Missing opening '(' after keyword 'for'.
At C:\Users\minh.tran\Documents\Get Disk.ps1:8 char:3
+ do
+   ~
Missing statement body in do loop.
At C:\Users\minh.tran\Documents\Get Disk.ps1:17 char:5
+   if [ "${ENABLED}" = "ENABLED" ]
+     ~
Missing '(' after 'if' in if statement.
At C:\Users\minh.tran\Documents\Get Disk.ps1:17 char:7
+   if [ "${ENABLED}" = "ENABLED" ]
+       ~
Missing type name after '['.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingOpenParenthesisAfterKeyword

PS C:\WINDOWS\System32>

A: The comment from @John Hanley is the correct answer. I tried to use a Linux shell script as a PowerShell script on a Windows machine.
The simplest solution for my case is to convert the shell script to a PowerShell script and run the converted script from PowerShell.
Converted script can be found here: GCP | disks.list method returning error when ran as part of a script . Despite working, it is still throwing some errors.


text:
Q: ¿Cómo concateno una lista de strings dentro de un ciclo for? Antes que nada les quiero aclarar que soy primerizo en esto de la programación. He estado escribiendo un código para jugar al ahorcado y quedó listo.
Ahora mi problema es el siguiente; no sé cómo concatenar los elementos de una lista para utilizarlos en un ciclo for (no sé si sea la manera más conveniente de hacer mi merecido) para añadir un plus a mi juego: elegir si queremos jugar de la manera tradicional o adivinando la palabra completa, en esta segunda opción es cuando comienza mi problema.
        import random
        archivo=open('listapal.txt',encoding='utf-8-sig')
        leer=archivo.read()
        palabras=leer.split()
        palabra_secreta=random.choice(palabras)
        nombre=input('¡Bienvenido al juego del Ahorcado!, ¿Cómo te llamas?')
        tipo_juego=int(input('Ingresa (1) para jugar tradicional y (2) para tratar de adivinar la palabra completa'))
        print('Hola %s, comienza a adivinar :)' %nombre.title())

        letras_ingresadas=''
        oportunidades=6
        oportunidades_2=2
        while oportunidades and oportunidades_2 >0:
            errores_cometidos=0
            if tipo_juego==1:
                for letra in palabra_secreta:
                    if letra in letras_ingresadas:
                        print(letra)
                    else:
                        print('*')
                        errores_cometidos=errores_cometidos+1
                if errores_cometidos==0:
                    print(' era la palabra.\n¡Felicidades, %s, ganaste!'%nombre.title())
                    break
                letras_a_ingresar=input('Introduce una letra: ')
                letras_ingresadas=letras_a_ingresar+letras_ingresadas
                if letras_a_ingresar not in palabra_secreta:
                    oportunidades=oportunidades-1
                    print('Te equivocaste.\nTe quedan %s oportunidades!'%oportunidades)

            else:
                for letra in palabra_secreta:
                    print('*')
                palabra_ingresada=input('Ingrese la palabra completa: ')
                if palabra_ingresada is palabra_secreta:
                    print(palabra_secreta)
                else:
                    errores_cometidos=errores_cometidos+1
                if errores_cometidos==0:
                    print(' era la palabra.\n¡Felicidades, %s, ganaste!'%nombre.title())
                    break
                if palabra_ingresada is not palabra_secreta:
                    oportunidades_2=oportunidades_2-1
                    print('Te equivocaste.\nTe quedan %s oportunidades!'%oportunidades_2)

        else:
            print('¡Perdiste!\nGracias por participar, %s.'%nombre.title())

Hasta antes del else dentro del while todo está perfecto.
A partir del else y al ejecutar el programa, si se decide ir por la opción 1 o 2 todo anda bien. Al elegir la 2 todo anda aparentemente bien, pero al ingresar la palabra correcta sigue contando errores y no muestra que se ha adivinado correctamente.
He intentado cosas como:
for letra in palabra_secreta:
  if ''.join(letra) is palabra_secreta:
    print(palabra_secreta)
  else:
    print('*')

y sigue dando el mismo resultado. ¿Existe alguna manera de concatenar los elementos de la palabra secreta para condicionarlos con la misma?. O, ¿cuál sería la mejor manera de lograr mi cometido?. Gracias por sus respuestas...

A: El problema es que usas is para comprobar si dos cadenas son iguales (mismo contendido) cuando debes usar el operador de igualdad:
 if palabra_ingresada == palabra_secreta

Explicación larga:

*

*is comprueba si dos identificadores apuntan al mismo objeto en memoria. Comprueba la identidad.

*Por contra == comprueba si ambos identificadores (apunten o no al mismo objeto) tienen el mismo valor. Comprueba la igualdad.
Puede parecer confuso, pero es fácil de entender, un ejemplo con un "objeto real", imagina que vas con un amigo por la calle y ve un coche pasar y te dice:

¡Mira un coche como el tuyo!

Esto lo entendemos como que ha visto un coche con los mismos atributos que tuyo, el mismo color, marca, etc . Pues el amigo a usado el operador == al comparar ambos coches, el coche puede o no ser el tuyo.
Ahora bien si te dice:

¡Mira tu coche!

Entonces no está diciendo que ha visto un coche como el tuyo, sino que ha visto tu coche. A usado el operador is para comparar ambos coches y le ha dado True (se deduce que por lógica == también dará True), lo cual si te puede ocasionar cierta intranquilidad...
En Python hay una pequeña excepción, por ejemplo nos podemos encontrar con esto:
>>> a = 5
>>> b = 5
>>> a is b
True

>>> a = 1111
>>> b = 1111
>>> a is b
False

>>> a = "a"
>>> b = "a"
>>> a is b
True

¿Qué está pasando aquí? Según lo dicho antes, a y b son dos objetos distintos y por tanto siempre debería dar False al comparar con is... Cierto, esto se debe a un efecto secundario de una medida tomada por el intérprete en aras de la optimización. Por ejemplo, almacena de forma preventiva enteros pequeños (menores a 255) en forma de singleton. Otra cosa que se suele hacer es usar tablas hash internamente para optimizar la comparación de literales de cadena, estas optimizaciones hacen que eventualmente is apunte al mismo objeto, pero no significa que se esté usando correctamente cuando queremos saber si dos identificadores apuntan a objetos con el mismo valor a no ser que sea una especificación del lenguaje y no optimizaciones internas, dependientes de la implementación.
Por lo tanto, por regla general usar is para saber si dos identificadores apuntan al mismo objeto y == si tienen el mismo valor:
>>> a = 5
>>> b = a  # No se copia el objeto, solo se hace que b apunte al mismo objeto que a
>>> a is b
True

>>> b += 5 #Como int es inmutable esto crea un nuevo objeto
>>> a += 5
>>> a is b
False

>>> a == b
True

Hay una excepción a la que ya hemos hecho referencia, para cualquier objeto singleton se debe usar is, ver PEP-8. Un caso muy común es ver si un objeto es None o no. En este caso la forma recomendada es siempre:
foo is None
foo is not None

no
foo == None
foo != None

None es también un singleton (dicho de forma poco ortodoxa, el intérprete se asegura de que existe un solo objeto None en memoria y todos los identificadores apuntan a él) y la comparación es mucho más rápida vía is.


text:
Q: LWC Toast Event JEST Test Issue I have a JEST test that tests for the presence of a toast event when an exception occurs from an imperative apex call:
    test('test exception path', () => {

    getStatusList.mockResolvedValue(GET_STATUS_LIST_EXCEPTION);

    console.trace = jest.fn();
    //console.log = jest.fn();

    const element = createElement('c-broker-load-status', {is: BrokerLoadStatus});
    element.recordId = '123456789012345678';
    document.body.appendChild(element);

    const handler = jest.fn();
    element.addEventListener('lightning__showtoast', handler);

    return flushPromises().then(() => {

        const headerArray = element.shadowRoot.querySelectorAll('th');
        expect(headerArray.length).toBe(0);
        const detailArray = element.shadowRoot.querySelectorAll('td');
        expect(detailArray.length).toBe(0);

        expect(handler).toHaveBeenCalled();
        console.log('Hello:' + Object.keys(handler.mock.calls[0][0]));
        expect(handler.mock.calls[0][0].detail.title).toBe('test');
        expect(handler.mock.calls[0][0].detail.message).toBe('test');
        expect(handler.mock.calls[0][0].detail.variant).toBe('test');
    });

});

This works fine up to the expect(handler_.toHaveBeenCalled(); which is true.  OK so far.
However as you can see from the console below the handler.mock.calls[0][0] object just has one property, isTrusted....
npm ERR! A complete log of this run can be found in:

  at Function.LightningUtil [as logError] (force-app/main/default/lwc/lightningUtil/lightningUtil.js:59:9)

console.log
  Hello:isTrusted

  at force-app/main/default/lwc/brokerLoadStatus/__tests__/brokerLoadStatus.test.js:100:13

c-broker-load-status › test exception path

TypeError: Cannot read property 'title' of null

   99 |             expect(handler).toHaveBeenCalled();
  100 |             console.log('Hello:' + Object.keys(handler.mock.calls[0][0]));
> 101 |             expect(handler.mock.calls[0][0].detail.title).toBe('test');
      |             ^
  102 |             expect(handler.mock.calls[0][0].detail.message).toBe('test');
  103 |             expect(handler.mock.calls[0][0].detail.variant).toBe('test');
  104 |         });

  at force-app/main/default/lwc/brokerLoadStatus/__tests__/brokerLoadStatus.test.js:101:13

I am following the repo examples from Salesforce pretty closely.  Why is calls[0][0] not showing me the toast event contents?
Thanks for your help!

A: The default stubs that come from @salesforce/sfdx-lwc-jest don't include a detail field. Source here.
The stubs from the sample repo lwc-recipes override the default stub and include a detail field the tests inspect. You can see the source here:
export const ShowToastEventName = 'lightning__showtoast';

export class ShowToastEvent extends CustomEvent {
    constructor(toast) {
        super(ShowToastEventName, {
            composed: true,
            cancelable: true,
            bubbles: true,
            detail: toast
        });
    }
}

Then the Jest config is updated to point to the new stub using the moduleNameMapper config entry.


text:
Q: Decrypting RSA data encrypted in python with cryptodome in C# using bouncycastle gives error block incorrect I am using the following function to encrypt RSA data in PHP:
    function RSAEncrypt($text){
    $priv_key=file_get_contents("privateKey.key");
    //$passphrase is required if your key is encoded (suggested)
    $priv_key_res = openssl_get_privatekey($priv_key);

    if(!openssl_private_encrypt($text,$crypttext,$priv_key_res)){
        echo "Error: " . openssl_error_string ();
    }
    return $crypttext;

}

I am decoding this in C# with the following function:
public static string RSADecrypt(string b64cipher, string pemcert) {
    byte[] bytesCypherText = Convert.FromBase64String(b64cipher);

    Org.BouncyCastle.X509.X509Certificate cert = (Org.BouncyCastle.X509.X509Certificate)new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(pemcert)).ReadObject();
    var decryptEngine = new Pkcs1Encoding(new RsaEngine());
    //var decryptEngine = new OaepEncoding(new RsaEngine());

    decryptEngine.Init(false, cert.GetPublicKey());

    string decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesCypherText, 0, bytesCypherText.Length));
    return decrypted;
}

I want to replace the PHP function with python, and tried the following:
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_OAEP, AES, PKCS1_v1_5
import base64
from Cryptodome import Random
from Cryptodome.Random import get_random_bytes
import hashlib
def encrypt_private_key(a_message):
    with open("privateKey.key", 'r') as f:
        private_key = RSA.importKey(f.read())
    #encryptor = PKCS1_OAEP.new(private_key)
    encryptor= PKCS1_v1_5.new(private_key)
    encrypted_msg = encryptor.encrypt(a_message.encode())
    encoded_encrypted_msg = base64.b64encode(encrypted_msg)
    return encoded_encrypted_msg

However, when decoding I get the following error:
InvalidCipherTextException: block incorrect

at byte[] Org.BouncyCastle.Crypto.Encodings.Pkcs1Encoding.DecodeBlock
 (byte[] input, int inOff, int inLen) at string RSADecrypt (string
 b64cipher, string pemcert)

If I try to use PKCS1_OAEP (in python and c#, see commented code), I am getting a data wrong exception.
Not sure what am I missing

A: After some research, it seems python lirary does not allow to make private key encryption as it is not a standard operation, however in my case I still wanted to do it, and used the code here:
https://www.php2python.com/wiki/function.openssl-private-encrypt/
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_private_key
def openssl_private_encrypt(data):
    """Encrypt data with RSA private key.
    This is a rewrite of the function from PHP, using cryptography
    FFI bindings to the OpenSSL library. Private key encryption is
    non-standard operation and Python packages either don't offer
    it at all, or it's incompatible with the PHP version.
    The backend argument MUST be the OpenSSL cryptography backend.
    """
    # usage
    key = load_pem_private_key(open("key.pem").read().encode(
        'ascii'), None, backend=default_backend())
    backend = default_backend()
    length = backend._lib.EVP_PKEY_size(key._evp_pkey)
    buffer = backend._ffi.new('unsigned char[]', length)
    result = backend._lib.RSA_private_encrypt(
        len(data), data, buffer,
        backend._lib.EVP_PKEY_get1_RSA(key._evp_pkey),
        backend._lib.RSA_PKCS1_PADDING)
    backend.openssl_assert(result == length)
    res = backend._ffi.buffer(buffer)[:]
    print(res)
    return base64.b64encode(backend._ffi.buffer(buffer)[:]).decode()


text:
Q: Notification observer selector not called I have this observer
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(GetUserID(_:)), name: Notification.Name("UserID"), object: nil)
    }

and this selector function
    @objc func GetUserID(_ notification: Notification){
        let User = notification.object as? String
        self.UserID = User
    }

And I keep getting nil in UserID even though I am certain that when I get the notification it is not nil which makes me believe that the selector is not being called

A: You can get observer value by below method
 let selectedIndex:[String: Int] = ["selectedIndex": 1]
                         //selectedindex = 0
                         // post a notification
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "SelectedSegment"), object: nil, userInfo: selectedIndex)

    NotificationCenter.default.addObserver(self, selector: #selector(self.changeSegmentControlIndex(notification:)), name: Notification.Name("SelectedSegment"), object: nil)

     @objc func changeSegmentControlIndex(notification: Notification) {

        if let selectedIndex = notification.userInfo?["selectedIndex"] as? Int {
         // do something with your image
            print(selectedIndex)

         }
    }