text:
Q: App Engine - LoggerFactory Restricted Class Error When Using Firebase in Java I'm creating a backend for my Android application using Google App Engine. I'm doing something very simple, which is just initialising my Firebase Admin SDK following instructions here - https://firebase.google.com/docs/admin/setup.
When I do this and run, I get the following error:

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory is a restricted class. Please see the Google  App Engine developer's guide for more details.
      at com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:52)
      at com.google.firebase.internal.FirebaseThreadManagers.(FirebaseThreadManagers.java:37)
      at com.google.firebase.FirebaseOptions$Builder.(FirebaseOptions.java:147)
      at com.example.app.myapplication.backend.MyServlet.doGet(MyServlet.java:34)

Here's my Servlet, which works fine without the Firebase additions. Error occurs at FirebaseOptions:
    public class MyServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        resp.setContentType("text/plain");
        resp.getWriter().println("Please use the form to POST to this url");

        FileInputStream serviceAccount =
                new FileInputStream("WEB-INF/MyAppServiceKey.json");

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
                .setDatabaseUrl("https://MyApp.firebaseio.com")
                .build();

        FirebaseApp.initializeApp(options);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String name = req.getParameter("name");
        resp.setContentType("text/plain");
        if (name == null) {
            resp.getWriter().println("Please enter a name");
        }
        resp.getWriter().println("Hello " + name);
    }
}

Here's my build.gradle for the backend:
    buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.google.appengine:gradle-appengine-plugin:1.9.42'
    }
}

repositories {
    jcenter();
}

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'appengine'

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7

dependencies {
    appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.42'
    compile 'javax.servlet:servlet-api:2.5'
    compile 'com.google.firebase:firebase-admin:5.5.0'

}

appengine {
    downloadSdk = true
    appcfg {
        oauth2 = true
    }
}


text:
Q: Tab bar visible for all activities in android My app contains 15 activities but i add only 3 activities for my tab bar.Tab Bar is visible in those activities not all. How to set tab bar visibility for all 15 screens or activities.

A: Solved. Created one Group Activity called TAB GROUP. It helps to display the Tab bar for whole
app.

A: Use HorizontalScrollView in layout xml
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/scroller"
        android:padding="0dp" />

    <HorizontalScrollView
        android:id="@+id/scroller"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:fillViewport="true"
        android:scrollbars="none" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="bottom" />
    </HorizontalScrollView>
</RelativeLayout>

A: public class Tab1Fragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    if (container == null) {
        return null;
    }
    LinearLayout theLayout = (LinearLayout) inflater.inflate(
        R.layout.tab_frag1_layout, container, false);
    // Register for the Button.OnClick event
    Button b = (Button) theLayout.findViewById(R.id.btn_startActivity);
    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(Tab1Fragment.this.getActivity(),
                "open new activity with tab bar", Toast.LENGTH_LONG).show();
            //Here I want to start new activity with tab bar
        }
    });
    return theLayout;
    // return (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout,
    // container, false);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best Structure for ASP.NET MVC Solution I tried to structure my last sizeable MVC project following a best practice approach, but didn't quite understand what I was doing.
It has a Data, Business and Web (MVC) project, but the controllers contain most of the code, the Data layer uses NHibernate and has a few repositories responsible for too many things, and the Business layer is a dumping ground for anything that doesn't belong in the other two projects.  It works, but I feel it could have been setup better - the main things I'm unhappy with are the fat controllers and the repositories.
I'm starting a new project that might grow to be a decent size, so I'm spending a bit more time trying to get my design right up front.  Having read a bit more, I'm trying to have a repository per aggregate-root, and then have a service in the Business layer for each controller in the presentation layer.
My initial hopes were that the bulk of the code would go in the services and this coupled with the smaller repositories would keep my controllers and data layer thin.  So far though, this isn't happening.
Everything I've read suggests that the View Models should not be returned from the Business layer, and should be populated in the presentation layer, so at the moment my service layer is mainly passing models from my data layer through to the presentation layer which then does what it needs to prepare the view models.  So I still have fat controllers, plus a thin business and data layer.
My presentation layer also knows about both my business and data layer, but I thought part of the point of this separation was to reduce coupling?
Have I got this all wrong?  Should I stop trying to blindly follow what I read on the internet and simply prepare view models in the business layer so I can move the bulk of my code in there?  Should I just go back to classic ASP? :)

A: the main guide that I use when I am setting up a project structure is to ensure that I can add some operationcontract attributes to the business logic layer, and then host it as a wcf service.
If i can do this, that means the business logic layer has isolated my data layer, and is interacting with its client only by passing simple structures and entities.  the datalayer is completely hidden.
So my usual structure looks like:
Solution
    Business.Contracts (interfaces for bll layer in here)
    Business.Logic     (concrete implementations of contracts in here)
    Business.Entities  (Pocos that bll uses)
    Data.Contracts     (interfaces for dal)
    Data.Sql           (Concrete Sql implementation of contracts)
    Common.Enums       (Enums needed by all projects)
    FrontEnd           (Main mvc app)

So in this structure, my mvc project only ever deals with the business namespace and the common namespace.
When interacting with the entities however, I tend to use my own models in the mvc project to allow me to add annotations and front end specific functionality, then i provide implicit conversions for these models to be able to be used interchangeably with the business entities.
HTH


text:
Q: php parsing with dom i'm having a problem parsing a url. i would like to do it with dom but ihave no idea where to start. i want to only parse the src from the following code. any ideas would be great thank you.
<script type="text/javascript" src="http://website.com/?code-ajax&cd=1145040425"></script>

A: $doc = new DOMDocument();
$doc->loadXML($xml);
$src = $doc->documentElement->getAttribute('src');

XPath example using remote file
$doc = new DOMDocument();
$doc->loadHTMLFile($url);
$xpath = new DOMXpath($doc);

// Retrieve collections of script nodes
$allScripts  = $xpath->query('//script');
$headScripts = $xpath->query('/html/head/script');
$bodyScripts = $xpath->query('/html/body/script');

// Get all scripts who's src attribute starts with "http://website.com"
$websiteScripts = $xpath->query('//script[starts-with(@src, "http://website.com")]');
if ($websiteScripts->length) {
    // contains one or more matches
    $src = $websiteScripts->item(0)->getAttribute('src');
}

A: My favorite solution is simplehtmldom php library, it is alot simpler to use than PHP's native solution; I say this from experience. It's similar to jQuery in it's syntax and usage.
You may use it like this
include('lib/simple_html_dom.php');
$html = str_get_html('<script type="text/javascript" src="http://website.com/?code-ajax&cd=1145040425"></script>');
$scriptsrc = $html->find('script',0)->src;

A: Using the SimpleHTMLDom Library:
<?php
    // include the SimpleHTMLDom library
    include('lib/simple_html_dom.php');

    // our input string
    $input = '<script type="text/javascript" src="http://website.com/?code-ajax&cd=1145040425"></script>';

    // create our Object. If reading from a file, use: file_get_html('/path/to/file');
    $doc = str_get_html($input);

    // find the first <script> tag, and echo its 'src' attribute.
    // -- note: calling this with find('script') returns an array
    echo $doc->find('script',0)->src;
?>


text:
Q: How to catch current css translate() position in javascript I would like to animate element on the screen by arrows. It should change the direction immediately while translation. So if element go to right and I press down arrow in half of the animation it should go straight down and stop to go right. But how can I catch current x position of the element. offsetLeft does not work. It is still the same origin position. Is it possible to catch current position of animated element? Thanks.

A: I think you need to call element.getBoundingClientRect()

let circle = document.querySelector(".animate");
let style = window.getComputedStyle(circle);

setInterval(() => {
  let rect = circle.getBoundingClientRect();
  console.log(rect.left)
}, 1000)
div {
  height: 100px;
  width: 100px;
  border-radius: 100px;
  background: blue;
}

.animate {
  animation: animate;
  animation-duration: 3s;
  animation-direction: alternate;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
}

@keyframes animate {
  from {
    transform: translate(0)
  }
  to {
    transform: translate(calc(100vw - 120px))
  }
}
<div class="animate"> </div>

Not sure why code snippet renders the entire element in console.log, but in an actual script it would return only the value.


text:
Q: Detox, multiple elements were matched for button in transition I am using detox e2e for creating test cases for my react-native application. Long story short, I have a button inside of my component's render function and that button transitions from left to right. I have given a unique test id to that button. Inside my test case i'm expecting that button to appear using its test id. But when I run "detox test", the test fails and error says that the multiple elements were matched against that test id.
Code for my test file is :
describe('Login flow', () => {
    // test case for wallet generation

    it('should generate new wallet', async () => {
        await expect(element(by.id('WelcomeScreen'))).toBeVisible()
        await expect(element(by.id('WelcomeScreenCreateWalletButton'))).toBeVisible()
    })
})

and code for my button inside render function is:
<Transition appear="horizontal">
          <View style={styles.buttonContainer}>
            <Button
              text={I18n.t('create-wallet')}
              onPress={this.createWallet}
              style={[styles.button, styles.topButton]}
              testID="WelcomeScreenCreateWalletButton"
            />

            <Button
              text={I18n.t('restore-wallet')}
              transparent
              onPress={this.restoreWallet}
              style={styles.button}
              shared={'button'}
              testID="WelcomeScreenRestoreWalletButton"
            />
          </View>
        </Transition>

Inside my test case I'm expecting button with testid "WelcomeScreenCreateWalletButton" to be visible. If I remove transition tags from the render function of my component, then the test runs successfully and passes. So apparently there's some problem with the transition of the button. I've read that detox's idle state synchronization handles the animation problems. I don't know what I am missing :/.

A: So, apparently this particular issue was introduced by react-native-fluid-navigation which make transitions by duplicating items. I was using it for the transition of buttons from left to right. The simple solution was to use the second item and perform actions on it. The code that works is as follow:
describe('Login flow', () => {
// test case for wallet generation

    it('should generate new wallet', async () => {
        await expect(element(by.id('WelcomeScreen'))).toBeVisible()
        await expect(element(by.id('WelcomeScreenCreateWalletButton')).atIndex(1)).toBeVisible()
    })
})

Adding just atIndex(1) solved the problem.


text:
Q: Cannot set headers after they are sent to the client in nodejs i have a login form . in this form i using the passport for find user . when i send the request it show me error.
this is my code :
passport.local :
 passport.use('local.login' , new localStrategy({
    usernameField : 'phoneNumber',
    passwordField : 'password',
    passReqToCallback : true
} , (req , phoneNumber, password , done) => {
    UserModel.findOne({'phoneNumber' : phoneNumber} , (err , user)=>{
        if(err) return done(err)
        if(! user || ! user.ValidationPassword(password)) return done(null , false , req.flash('errors' , 'کاربری با این مشخصاتا در سیستم ثبت نشده است'));
        console.log(err,user)
        done(null , user);
    })
}))

LoginController :
async LoginProcess(req, res, next) {

    var result = await this.formValidation(req, res);
    if (result) {
        this.Login(req, res, next)
    }
    return res.redirect('/auth/login');
}

Login(req, res, next) {
    passport.authenticate('local.login', (err, user) => {
        console.log(user, err)
        if (!user) return res.redirect('login')
        req.login(user, err => {
            if (err) console.log(err)
            if (req.body.remember) {
                user.setRememberToken(res)
            }
            return res.redirect('/');
        })
    })(req, res, next)
}

when i send the request it show me this Error :
events.js:292
      throw er; // Unhandled 'error' event
      ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:518:11)
    at ServerResponse.header (/home/mrcoder/Projects/Nodejs/Store/node_modules/express/lib/response.js:771:10)
    at ServerResponse.location (/home/mrcoder/Projects/Nodejs/Store/node_modules/express/lib/response.js:888:15)
    at ServerResponse.redirect (/home/mrcoder/Projects/Nodejs/Store/node_modules/express/lib/response.js:926:18)
    at /home/mrcoder/Projects/Nodejs/Store/app/http/controller/Login.js:25:35
    at allFailed (/home/mrcoder/Projects/Nodejs/Store/node_modules/passport/lib/middleware/authenticate.js:107:18)
    at attempt (/home/mrcoder/Projects/Nodejs/Store/node_modules/passport/lib/middleware/authenticate.js:180:28)
    at Strategy.strategy.fail (/home/mrcoder/Projects/Nodejs/Store/node_modules/passport/lib/middleware/authenticate.js:302:9)
    at verified (/home/mrcoder/Projects/Nodejs/Store/node_modules/passport-local/lib/strategy.js:82:30)
    at /home/mrcoder/Projects/Nodejs/Store/app/passport/registerPassportValidation.js:44:66
    at /home/mrcoder/Projects/Nodejs/Store/node_modules/mongoose/lib/model.js:4883:16
    at /home/mrcoder/Projects/Nodejs/Store/node_modules/mongoose/lib/model.js:4883:16
    at /home/mrcoder/Projects/Nodejs/Store/node_modules/mongoose/lib/helpers/promiseOrCallback.js:24:16
    at /home/mrcoder/Projects/Nodejs/Store/node_modules/mongoose/lib/model.js:4906:21
    at /home/mrcoder/Projects/Nodejs/Store/node_modules/mongoose/lib/query.js:4390:11
    at /home/mrcoder/Projects/Nodejs/Store/node_modules/kareem/index.js:135:16
Emitted 'error' event on Function instance at:
    at /home/mrcoder/Projects/Nodejs/Store/node_modules/mongoose/lib/model.js:4885:13
    at /home/mrcoder/Projects/Nodejs/Store/node_modules/mongoose/lib/helpers/promiseOrCallback.js:24:16
    [... lines matching original stack trace ...]
    at /home/mrcoder/Projects/Nodejs/Store/node_modules/kareem/index.js:135:16
    at processTicksAndRejections (internal/process/task_queues.js:79:11) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...

whats the problem ? how can i solve this problem ???


text:
Q: Xamarin forms Android OAuth2 redirect no working So, I've been working on this a couple days and I'm missing something.  I'm trying to create a Xamarin forms app that connects to a cloud accounting package using OAuth2 authentication.  I've been working through the examples from here. But I just can't get the redirect working.  Most likely something simple, but I'm not seeing or understanding
I'm created my authenticator as per the example, setting the redirect url to https://com.myproject.myapp/oauth2redirect.
var authenticator = new OAuth2Authenticator(
            <ClientId>,
            null,
            "openid profile email accounting.transactions accounting.settings offline_access",
            new <AuthoriseationEndpoint>,
            new Uri("https://com.myproject.myapp/oauth2redirect"),
            new <TokenEndpoint>,
            null,
            true);

Then, I'm created a new activity in my Android project with the intentFilter
    [Activity(Label = "CustomUrlSchemeInterceptorActivity", NoHistory = true)]
    [IntentFilter(new[] { Android.Content.Intent.ActionView },
        Categories = new[] { Android.Content.Intent.CategoryDefault, Android.Content.Intent.CategoryBrowsable },
        DataSchemes = new[] { "com.myproject.myapp" },
        DataPath = "/oauth2redirect")]
    public class CustomUrlSchemeInterceptorActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            var uri = new Uri(Intent.Data.ToString());

            // Load redirectUrl page
            AuthenticationState.Authenticator.OnPageLoading(uri);

            Finish();

            // Create your application here
        }
    }

When I run my app, the login screen pops up as expected.  My app is registered okay with the cloud application fine but the redirect doesn't work.  I just get a browser error saying the site can't be reached. Server IP address could not be found DNS_PROBE_FINISHED_NXDOMAIN

A: try to change
var authenticator = new OAuth2Authenticator(
        <ClientId>,
        null,
        "openid profile email accounting.transactions accounting.settings offline_access",
        new <AuthoriseationEndpoint>,
        new Uri("https://com.myproject.myapp/oauth2redirect"),
        new <TokenEndpoint>,
        null,
        true);

to
var authenticator = new OAuth2Authenticator(
        <ClientId>,
        null,
        "openid profile email accounting.transactions accounting.settings offline_access",
        new <AuthoriseationEndpoint>,
        new Uri("com.myproject.myapp:/oauth2redirect"),
        new <TokenEndpoint>,
        null,
        true);

You could not add https:// to your custom redirect url after you define a Schemes. Note that only a single / can appear after the scheme component.
you could refer to Redirect URL


text:
Q: First Data Payment Gateway Issue I'm trying to intigrate First data Payment Getway in my site
Config file for FirstData Payment Gateway
define("FDAPI_URL","https://ws.merchanttest.firstdataglobalgateway.com/fdggwsapi/services/order.wsdl");
define("FD_USERPWD","WSXXXXXXXX._.1:XXXXXXXX");
define("FD_SSLCERT", "/home/flagcases/domains/usaflagcases.com/public_html/certificate/WSXXXXXXXX._.1.pem");
define("FD_SSLKEY","/home/flagcases/domains/usaflagcases.com/public_html/certificate/WSXXXXXXXX._.1.key");
define("FD_SSLKEYPASSWD", "ckp_XXXXXXXX");
$ch = curl_init(FDAPI_URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, FD_USERPWD);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSLCERT, FD_SSLCERT);
curl_setopt($ch, CURLOPT_SSLKEY, FD_SSLKEY);
curl_setopt($ch, CURLOPT_SSLKEYPASSWD, FD_SSLKEYPASSWD);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if ($result === false)
{
    echo curl_error($ch);
}

Alway I got Curl Error
unable to use client certificate (no key found or wrong pass phrase?) Curl Error

A: Please try to add WSXXXXXXXX..1.p12 might be help you... Where you added WSXXXXXXXX..1.pem and WSXXXXXXXX._.1.key


text:
Q: How to shorten multiple && condition Currently I can run my program but my code consists of a lot of repetition which looks something like:
while(option != 'E' && option != 'D' && option != 'P' && option != 'Q' &&
      option != 'e' && option != 'd' && option != 'p' && option != 'q') {
  // Some code here
}

or:
while(cType != 'S' && cType != 'L' && cType != 'O' && cType != 'Q' &&
      cType != 's' && cType != 'l' && cType != 'o' && cType != 'q') {
  // Some code here
}

What's the fastest way to shorten above code?

(Is there any way beside using additional function?)

A: const char invalidChars[] = "edpq";
while (strchr(invalidChars, tolower(option)) != 0) {
    ...
}

A: You could initialize a string containing the characters you want to match, then use find, which returns npos if no match was found:
string match = "SLOQsloq";
while (match.find(cType) == string::npos)
  ...

A: You could get rid of half of the conditions with std::tolower
while(std::tolower(option) != 'e' && std::tolower(option) != 'd' && std::tolower(option) != 'p' && std::tolower(option) != 'q')

You could also use a std::string and it's find member function like:
std::string options = "edpq";
//...
while (options.find(std::tolower(option)) == std::string::npos)

A: You could simplify the logic and make things more readable by using an std::set and checking if the set contains (or doesn't contain) the variable we're comparing to:
std::set<char> someChars { 'a', 'b', 'c' };
if(someChars.find(myChar) != someChars.end()) {
    // myChar is either 'a', 'b', or 'c'
}

The condition in most other languages would be written more cleanly as something like someChars.contains(myChar) (but C++'s set interface is very minimal).
However, for a small number of comparisons, your method is probably faster.

A: A candidate quick test with no branching.
1) Make case-less.
2) Form product of 4 differences.
3) 1 compare against 0.
Assumes only letters.
Works up to 4 (sizeof int/sizeof char) letters.
Upper/Lower case differ by the same bit.  (This works with ASCII and EBCDIC)
#define CaseMaskBits ((unsigned char)~('A'^'a'))
#define Product4(ch, s) ((ch-s[0]) * (ch-s[1]) * (ch-s[2]) * (ch-s[3]))
#define TestEq4(ch, t, s)  (t=ch&CaseMaskBits, !Product4(t, s))

int main(void) {
  int ch;
  printf("%X\n", CaseMaskBits);
  for (ch = 0; ch < 256; ch++){
    int t;  // temp var for TestEQ4
    while (TestEq4(ch, t, "ELPQ")) {
      printf("%d %c\n", ch, ch);
      break;
    }
  }
  return 0;
}

280           while (TestEq4(ch, t, "ELPQ")) {
00402560:   mov %ebx,%eax
00402562:   and $0xdf,%eax
00402567:   lea -0x4c(%eax),%edx
0040256a:   lea -0x45(%eax),%ecx
0040256d:   imul %edx,%ecx
00402570:   lea -0x50(%eax),%edx
00402573:   sub $0x51,%eax
00402576:   imul %ecx,%edx
00402579:   imul %edx,%eax
0040257c:   test %eax,%eax
0040257e:   jne 0x402555 <main+37>
281             printf("%d %c\n", ch, ch);

A: If option/cType have <= 8 bits of significance, for speed, use a table lookup. @Dieter Lücking
unsigned char Table[UCHAR_MAX + 1] = {
  fill per needs };
#define Table_OptionMask 1
#define Table_cTypeMask 2
#define Table_nextMask 4

while (!(Table[(unsigned char)option] & Table_OptionMask)) ...
while (!(Table[(unsigned char)cType] & Table_cTypeMask)) ...

For simpler code maintenance, populate the table on code startup by calling Table_Setup().
static void Table_SetInsensitive(unsigned char *Table, unsigned mask, cnst char *src) {
  while (*src) {
    Table[toupper((unsigned char) *src)] |= mask;
    Table[tolower((unsigned char) *src)] |= mask;
    src++;
  }
}

void Table_Setup(void) {
  memset(Table, 0, sizeof Table);
  Table_SetInsensitive(Table, Table_OptionMask, "EDPQ");
  Table_SetInsensitive(Table, Table_cTypeMask, "SLOQ");
  Table_SetInsensitive(Table, Table_cTypeMask, tbd);
}


text:
Q: MUI5 createTheme - color gradations do not exist in typescript definition of Theme I need to customize my theme colors in MUI5, in typescript.  I am using the createTheme function to do so.  createTheme accepts a palette entry in its argument object, which TS says should be of type PaletteOptions:

What TS says a palette argument can be:
If you dig into the tsdefs on what PaletteOptions is, its an object whose keys are the 'qualifier' words for various states, and whose values are PaletteColorOptions
// From MUI's own ts defs:

export interface PaletteOptions {
  primary?: PaletteColorOptions;
  secondary?: PaletteColorOptions;
  error?: PaletteColorOptions;
  warning?: PaletteColorOptions;
  info?: PaletteColorOptions;
  success?: PaletteColorOptions;
  mode?: PaletteMode;
  tonalOffset?: PaletteTonalOffset;
  contrastThreshold?: number;
  common?: Partial<CommonColors>;
  grey?: ColorPartial;
  text?: Partial<TypeText>;
  divider?: string;
  action?: Partial<TypeAction>;
  background?: Partial<TypeBackground>;
  getContrastText?: (background: string) => string;
}

A PaletteColorOptions should be able to be either a SimplePaletteColorOptions or a ColorPartial:
// Again from MUI's own ts defs:

export type PaletteColorOptions = SimplePaletteColorOptions | ColorPartial;

// Where:
export interface SimplePaletteColorOptions {
  light?: string;
  main: string;
  dark?: string;
  contrastText?: string;
}

// And
export type ColorPartial = Partial<Color>;

export interface Color {
  50: string;
  100: string;
  200: string;
  300: string;
  400: string;
  500: string;
  600: string;
  700: string;
  800: string;
  900: string;
  A100: string;
  A200: string;
  A400: string;
  A700: string;
}

My inference from this is that its perfectly valid to define the success or info or similar objects using the fine gradations of 50, 100, 200, 300, etc.  This is what I need to do.  When doing so, I get no errors.  The colorPalette I fed to createTheme above has these gradations, and TS doesn't bother me:

What TS says a palette's properties can be once created
However, I notice that createTheme returns a MUI Theme object:
// From MUI ts defs:

export default function createTheme(options?: ThemeOptions, ...args: object[]): Theme;

Digging into Theme, the palette entry is not a PaletteOptions like it was in the argument, but rather a Palette object, whose entries are PaletteColor:
// MUI TS defs

export interface Palette {
  common: CommonColors;
  mode: PaletteMode;
  contrastThreshold: number;
  tonalOffset: PaletteTonalOffset;
  primary: PaletteColor;
  secondary: PaletteColor;
  error: PaletteColor;
  warning: PaletteColor;
  info: PaletteColor;
  success: PaletteColor;
  grey: Color;
  text: TypeText;
  divider: TypeDivider;
  action: TypeAction;
  background: TypeBackground;
  getContrastText: (background: string) => string;
  augmentColor: (options: PaletteAugmentColorOptions) => PaletteColor;
}

export interface PaletteColor {
  light: string;
  main: string;
  dark: string;
  contrastText: string;
}

So when trying to access any fine gradations (50, 100, 200, etc) on any of the objects, TS throws an error.  It thinks that the objects can only be light, main, dark, or contrastText

Why the discrepancy?
What am I doing wrong in my setup such that TS thinks that the entries in a the palette object cannot have these fine gradations, when the argument for palette says that clearly they can?  Using // @ts-expect-error works and the code runs properly, but I don't want to use that every time I access one of these color partial gradations.

A: The discrepancy is due to the intentional difference between what is being created (a collection of PaletteColor objects within the Palette) and the two main ways by which you can provide information for creating those PaletteColor objects.
The two alternatives in PaletteColorOptions are so that you can do either of the following:
Option 1 - Use imported color object
import * as React from "react";
import { createTheme } from "@mui/material/styles";
import { purple } from "@mui/material/colors";

const theme1 = createTheme({
  palette: {
    primary: purple
  }
});

Option 2 - Explicitly specify "main" (and optionally "light" and "dark" shades)
import * as React from "react";
import { createTheme } from "@mui/material/styles";

const theme2 = createTheme({
  palette: {
    primary: { main: "#9c27b0" }
  }
});

When you use Option 1, MUI adds in the main, light, and dark shades by selecting the [500], [300], and [700] shades respectively (https://github.com/mui/material-ui/blob/v5.11.10/packages/mui-material/src/styles/createPalette.js#L221). The numbered shades remain in the resulting theme object, but that is just because MUI doesn't remove anything that you pass in, it just adds to it the pieces that it requires/guarantees to be in the resulting theme.
With option 2, the resulting theme does not contain any of the numbered shades, it will only contain the main, light, and dark shades (in my example MUI derives the light and dark shades from the provided main shade). The TypeScript definition for the resulting theme reflects the common output for the two alternatives.
Here's a sandbox demonstrating those two createTheme approaches: https://codesandbox.io/s/createtheme-example-z4nei6?file=/demo.tsx.
If you want to use shades other than main, light, and dark, then you can augment the PaletteColor type:
declare module "@mui/material/styles" {
  interface PaletteColor {
    A700?: string;
  }
}

Related answer:

*

*How to add custom colors name on Material UI with TypeScript?


text:
Q: Trying to run SparkSQL over Spark Streaming I am trying to run SQL queries over streaming data in spark. This looks pretty straight forward but when I try it, I get the error table not found : tablename>. It unable to find the table I've registered.
Using Spark SQL with batch data works fine so I'm thinking it has to do with how I'm calling streamingcontext.start(). Any ideas what is the issue? Here is the code:
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.StreamingContext._
import org.apache.spark.sql.SQLContext

object Streaming {

def main(args: Array[String]) {

    val sparkConf = new SparkConf().setMaster("local").setAppName("HdfsWordCount")
    val sc = new SparkContext(sparkConf)
    // Create the context
    val ssc = new StreamingContext(sc, Seconds(2))

    val sqc = new SQLContext(sc);
    import sqc.createSchemaRDD

    // Create the FileInputDStream on the directory and use the
    // stream to count words in new files created
    val lines = ssc.textFileStream("C:/Users/pravesh.jain/Desktop/people.txt")
    lines.foreachRDD(rdd=>rdd.map(_.split(",")).map(p => Persons(p(0), p(1).trim.toInt)).registerAsTable("data"))
    // lines.foreachRDD(rdd=>rdd.foreach(println))
    val teenagers = sqc.sql("SELECT name FROM data WHERE age >= 13 AND age <= 19")
    ssc.start()
    ssc.awaitTermination()
  }
}

Any suggestions welcome. Thanks.

A: Well I got to know the problem. You have to query the data within the foreachRDD function, otherwise the table is not recognized. Something like this works:
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.StreamingContext._
import org.apache.spark.sql.SQLContext
import org.apache.spark.streaming.Duration

object Mlist {

  def main(args: Array[String]) {

    val sparkConf = new SparkConf().setMaster("local").setAppName("HdfsWordCount")
    val sc = new SparkContext(sparkConf)
    // Create the context
    val ssc = new StreamingContext(sc, Seconds(2))

    val lines = ssc.textFileStream("C:/Users/pravesh.jain/Desktop/people.txt")
    lines.foreachRDD(rdd=>rdd.foreach(println))

    val sqc = new SQLContext(sc);
    import sqc.createSchemaRDD

    // Create the FileInputDStream on the directory and use the
    // stream to count words in new files created

    lines.foreachRDD(rdd=>{
      rdd.map(_.split(",")).map(p => Persons(p(0), p(1).trim.toInt)).registerAsTable("data")
      val teenagers = sqc.sql("SELECT name FROM data WHERE age >= 13 AND age <= 19")
      teenagers.foreach(println)
    })

    ssc.start()
    ssc.awaitTermination()
  }
}


text:
Q: can't figure out, have many differentfiles for this import java.util.Scanner;
//import javax.swing.JOptionPane;

public class batavg
{

    private int hits = 0;
    private int tab = 0;
    private double ba;

    Scanner stdIn = new Scanner(System.in);

    public void battingaverage(double ba)
    {
        this.ba = ba;
    }

    public void avg()
    {
        this.avg = (double) (hits)/(tab);

        System.out.println("Number of hits are " + hits + " .");

    }
}

import java.util.Scanner;
//import javax.swing.JOptionPane;

public class batdriver
{

    public static void main(String[] args)
    {
        Scanner stdIn = new Scanner(System.in);
        int hits;
        batavg batter

        System.out.println("Enter number of hits: ");
        int hits = stdIn.nextInt();
        batavg batter = new batavg();
        batter.battingaverage(hits);

    }
}

A: In java, all your public classes are kept in separate files with file names same as class name. FOr instance  class batavg will be written in file name batavg.java
so there will be2 separate files. For main function separate class is not necessarily required, you can write the main function in batavg class as well.


text:
Q: JavaScript / jQuery escape special chars I need to escape a String with special characters and i dont know how to do that.
The  String var value is set by an Input field, so the user can write any special character as he wants, even the ones that i dont know and i could break the syntax...so instead of escape char by char, i want to know what's the better method to accomplish this.
This is my example code:
string = '-|{}?" Hello \$#^*&@)(~';

newHTML= ''+string+'';

$('#my-div').append(newHTML);

But i get a syntax error.I want to escape all special characters... as you can see this code detector also is not working when i use ' in the string

A: Or easy jQuery trick:
string = $("

").text(string).html();

text() encodes the string inside the temporary div and html() fetches the encoded string :)

A: You used escape character(backslash) \ in string. You must use escape character before the escape character in order to escape it.
So you must define this character in your string like : \\
You see, every special character in c based programming/scripting languages, must be used with escape character. Like newline or return.  \n  \r


text:
Q: Preg_Split is not keeping the delimeter I'm trying to parse the attributes out of a shortcode tag that I have.  The string that I'm starting with looks like this.
href="https://example.com" class="bootstrap class names"

I'm using this expression, which gets me ALMOST there.
$attribute_dna = '/"\s/';
$attributes = preg_split($attribute_dna, $attributes_string, null, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);

the output I get is this...
string(27) "href="https://example.com"  <--Problem is right here (missing a quote)
string(17) "class="bootstrap class names""

You can see above if i had the ending quote on the href just like the second one it would be perfect.  But it's not capturing the delimeter.
I'd appreciate any and all help I can get.  Thanks in advance.

A: Isn't this much more beautiful?
<?php

$html = <<<DATA

    Some link here

DATA;

# set up the DOM
$dom = new DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);

# set up the xpath
$xpath = new DOMXPath($dom);

foreach ($xpath->query("//a") as $link) {
    foreach ($link->attributes as $attr) {
        $name = $attr->nodeName;
        $value = $attr->nodeValue;
        echo "Attribute '$name': '$value'\n";
    }
}
?>

Which yields
Attribute 'href': 'https://example.com'
Attribute 'class': 'bootstrap class names'


text:
Q: In Delphi: How can I find the recursion depth without using a parameter? When I create recursive methods, I often include a Depth-parameter, especially when I need some sort of bailout mechanism. The code will usually be something like this
procedure Recurse(<Params>; aDepth : integer = 0);
begin
  if aDepth > SomeLimit then
  begin
    //Tidy up, return best result found>
    exit;
  end;

  <stuff>

  if <Condition> then
    Recurse(<Params>; aDepth+1)
  else
  begin
    //Tidy up, return result of endnode>
  end;
end;

And I call it without the Depth-parameter
Recurse(<Params>);

Is there another way to easily find the depth?

A: If you had a way to walk the stack and see how many times your function's entry point was in there, I suppose you could do it that way. But then you'd notice that your aDepth parameter was right there too, and you'd realize that aDepth is just easier and much less trouble than snooping the stack.
IMO, the simple solution is best here, it's portable and future-proof, unlike whatever stack snooping solution you could invent.
So yes, there are other ways, but your original solution is best, IMO.

A: Declare a typed constant inside your procedure. Make sure you set the compile option to allow changes in constants.
procedure Recurse;
const
  aDepth : integer = 0;
begin
  aDepth := aDepth + 1;

  try
    if aDepth > SomeLimit then
    begin
      //Tidy up, return best result found>
      exit;
    end;

    <stuff>

    if <Condition> then
      Recurse
    else
    begin
      //Tidy up, return result of endnode>
    end;
  finally
    aDepth := aDepth - 1;
  end;
end;

A: Have a global variable that would count recursion? Otherwise no - recursion is just calling some method with some parameters.

A: In C++ I am able to do this
class recursion_guard
{
public:
    recursion_guard() { depth_count++; }
    ~recursion_guard() { depth_count--; }
    static int depth_count;
};
int recursion_guard::depth_count = 0;
void recurse(recursion_guard a = recursion_guard())
{
    if(recursion_guard::depth_count > 100)
        return;
    recurse();
}

but since objects in Object Pascal are always allocated on the heap, I wonder if it is possible to use instead String with default argument and access somehow its reference count
const
    MyRecursionGuardConstString: string = "whatever";
procedure Recurse(RecursionGuard: string = MyRecursionGuardConstString)
begin
    if GetRefCount(MyRecursionGuardConstString) > 100 then //o_o
        exit;
    end;
    Recurse;
end;

A: type
  TMyRecursion = class
  private
    nDepth: integer;
  public
    constructor Create;
    procedure Recursion(...)
  end;

In constructor you must initialize nDepth, of course.


text:
Q: Ubuntu how to give read permission only for owner i need to give read permission to only the owner of the directory and sub directory.no other user can read the files in the directory.how to do this in command line

A: chmod -R 700 directory_name recursively sets all the permissions for yourself, leaving none for the others.

A: You can use the find command for this:
find -type d -exec chmod 0500 {} \;

Note that read permissions only will not work for a directory to list it's contents. Additionally the executable permission must be given. Therefore 0500

A: Try this :
chmod -R 700 yourDir


text:
Q: How to restore a missing Recovery HD partition I bought a second hand Macbook Pro which came with OSX Lion installed, when I wanted to clean it I found out that it had no Recovery HD partition. I confirmed this through the Disk Utility (enabled debug menu, showing every partition).
I am able to boot using Apple's Internet Recovery feature, but since Lion wasn't bought on my Apple ID, its only giving me the option to buy OSX Mountain Lion. Can I use that to completely reinstall my Macbook and create a proper Recovery HD partition, and then can I simply use Timemachine afterwards to recover my data?
Any hints or tips for this process would be highly appreciated.

A: Yes, you can. Be sure to have a full Time Machine archive on an external device before you begin, and check your MBP meets the minimum system requirements before you buy.  The Mountain Lion installer will create Recovery HD, if it doesn't already exist.
In case you choose to do a clean install, which is quicker, import your account afterwards from the Time Machine archive using Migration Assistant: you can pick and choose exactly what you want to import from the archive, and the Apple utility will sanitise imported user preferences so they are Mountain Lion compatible.
Alternatively, if you are comfortable using Terminal,  Lloeki's answer to How can I create or recreate a Lion recovery partition has much to recommend it.

A: SuperDuper's developer recommends reinstalling OS X from the App Store:

Actually, you can easily recreate the recover partition by simply reinstalling Lion from the App Store. (This has the additional benefit of updating the recover partition with the most recent data, too.)

See http://www.shirt-pocket.com/forums/showthread.php?t=6647.
Reinstalling OS X over the current installation is like upgrading OS X. It keeps user files and settings in place, but it replaces some system files with the versions included with the installer. It shouldn't cause you any extra work, apart from things like having to reinstall Java or restore the contents of /etc/apache2/.
Alternatively, if you are running an old major version of OS X like the OP, you can just upgrade OS X from the App Store.

A: I had a whole set of articles about it on my blog.
http://www.dmitry-dulepov.com/2011/09/how-to-create-mac-os-x-lion-recovery.html
http://www.dmitry-dulepov.com/2011/09/mac-recovery-partion-revisited.html
http://www.dmitry-dulepov.com/2012/09/creating-os-x-recovery-partion-part-3.html
For now I would recommend the last article as a way to go. The first two will work but they require a lot of attention and doing math.

A: You can use Carbon Copy Cloner to create the space for the Recovery Partition if you are booted from another hard drive.
The problem is that you will need a copy of to 10.7 Recovery Partition to copy into the space that Carbon Copy Cloner creates.

A: I would recommend using a tool for this. The one I prefer is:

*

*https://github.com/MagerValp/Create-Recovery-Partition-Installer
You can look at the tools and it's been used by many Mac Admins so it gets updated when things break over time quite rapidly. Apple recommends reinstalling the OS, but that's an indirect way if you don't mind running a special tool for this limited task.


text:
Q: Magento: not shipped item collection I would like to get all items that has not been shipped for a given order.
Suppose  that I have a  partial shipped order I would like to retrieve all items that are pending to be shipped.
Something like:
$collection = Mage::getModel('...')->getCollection()
                     ->Add...()

A: To get all items of the order, use the item collection:
    $order = Mage::getModel('sales/order')->load($orderId);
    $orderItems = $order->getItemsCollection();

And then use the shipment model to get all the items of the order:
   $shippedItems = Mage::getModel('sales/order_shipment')
    ->setOrder($order)->getItemsCollection();

Edit2: Turns out that setting the order on the shipment does not work to get the items collection, since there can be several shipments for an order. Use the code snippet provided below, instead.
Edit: I forgot that there could be several shipments, so here is the full working code to get all Ids of the order items and all Ids of the shipped ones:
$orderId = 15;
$order = Mage::getModel('sales/order')->load($orderId);
$orderItems = $order->getItemsCollection();
$allOrderItemIds = $orderItems->getAllIds();
$shipments = $order->getShipmentsCollection();
$shippedItemIds = array();
foreach ($shipments as $shipment) {
        $shippedItems = $shipment->getItemsCollection();
        foreach ($shippedItems as $item) {
                $shippedItemIds[] = $item->getOrderItemId();
        }
}
var_dump($allOrderItemIds);
var_dump($shippedItemIds);

A: $orderId = 382;

$order = Mage::getModel('sales/order')->load($orderId);
// OR if you load the order with increment id ...
// $order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
$orderItems = $order->getItemsCollection();

foreach ($orderItems as $item) {

    $qtyToBeShipped = $item->getQtyOrdered() - $item->getQtyShipped();

    if ($qtyToBeShipped)
        echo $item->getId() . ' - ' . $qtyToBeShipped . '</br>';
}


text:
Q: using Where in views Laravel 5.1 I'm relative new in laravel, in my first app I have a method in the controller that pass a list of links to the view, but in the view I only need some of those links so in the view I have this:
$links->where('menu_id', 2)

This works in my developer environment but don't work in production server.
Someone knows why? or knows another way to filter the results in the view?

A: Try like this
@foreach($links as link)
    @if($link['menu_id'] == 2)
           // your logic
    @endif
@endforeach


text:
Q: In Cloud Firestore, how do you add URl in the field section in Document? In Cloud Firestore, I want to add a collection like for ex. A,B,C and ..... within document I want to add two things(fields) basically

*

*a image, and

*a URL

Since I am new to Firebase ...Can anyone help me with this problem

A: As suggested by Vinamra Jaiswal, you need to store the URL as a string in the Firestore, you can refer to "How to store multiple url in firestore using flutter" for an example.
As for the image you can refer to "firestore database add image to record", where you can see that it is wiser to store the images in the Cloud Storage and then download the URLs and store them in Firestore.
You can also refer to the "Upload image to Cloud Storage, save URI in Firestore" video to get more insight on how to do this.


text:
Q: Requesting OAuth request token from Twitter API with RestSharp returns 404 I'm trying to retrieve a Twitter OAuth request token using RestSharp, but no matter what I try the API seems to respond with a 404. Here's my method code:
public void GetRequestToken()
{
    var client = new RestClient("https://api.twitter.com/1");

    var authenticator = OAuth1Authenticator.ForRequestToken(_consumerKey, _consumerSecret);
    authenticator.ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader;

    client.Authenticator = authenticator;

    var request = new RestRequest("/oauth/request_token", Method.POST);
    request.AddHeader("oauth_callback", "http%3A%2F%2Fmarkashleybell.com");
    var response = client.Execute(request);

    var qs = HttpUtility.ParseQueryString(response.Content);

    _token = qs["oauth_token"];
    _tokenSecret = qs["oauth_token_secret"];
}

_consumerKey and _consumerSecret are retrieved from Web.config settings, and I've double-checked that they are correct. _token and _tokenSecret are private member variables of the class containing this method.
The API url being requested is correct. The request seems to be passing all the correct headers according to Twitter's documentation.
I've tried to use the APIGee console to make the same API call and see what I'm doing wrong, but even that returns 404.
What am I doing wrong here?

A: DOH. It turns out the Twitter API URLs for OAuth operations are in fact slightly different to those for all other Twitter API calls and omit the API version segment, so this was a genuine 404.
There was also a tidier way to supply the oauth_callback parameter built into the RestSharp authenticator constructor—for reference, the code below works perfectly:
public void GetRequestToken()
{
    var client = new RestClient("https://api.twitter.com"); // Note NO /1

    client.Authenticator = OAuth1Authenticator.ForRequestToken(
        _consumerKey,
        _consumerSecret,
        "http://markashleybell.com" // Value for the oauth_callback parameter
    );

    var request = new RestRequest("/oauth/request_token", Method.POST);
    var response = client.Execute(request);

    var qs = HttpUtility.ParseQueryString(response.Content);

    _token = qs["oauth_token"];
    _tokenSecret = qs["oauth_token_secret"];
}


text:
Q: "If var:" statement behaves unexpectedly in Python script While the 'if var:' statement works correctly in Python IDE, it is not behaving the same when run from a Python script. Any idea why is that?
Code to reproduce the problem:
%%writefile if_var.py
import argparse

def if_var_fn(Flag):
    if Flag:
        print(f'Flag is True: {Flag}')
    else:
        print(f'Flag is False or None: {Flag}')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Process Flag argument.')
    parser.add_argument('Flag_', help='Enter Flag value')
    args = parser.parse_args()
    print(f'Value of args.Flag_: {args.Flag_}')
    print('Running if var ...')

    if_var_fn(args.Flag_)

The problem is that the passed argument always takes only one value: True
(base) /.../: python if_var.py 1
Value of args.Flag_: 1
Running if var ...
Flag is True: 1
(base) /.../: python if_var.py 0
Value of args.Flag_: 0
Running if var ...
Flag is True: 0

A: One solution I found was to cast the argument to integer from argument type declaration and use choices to restrict the argument values to [0,1].


text:
Q: Is it possible to set a variable value based on screen size in angular using bootstrap? I have a global variable in an angular component like so,
visibleDays = 7

I want to be able to control this value based on screen size. For smaller devices, I want this to be
3 instead of 7. Is it possible to do this for "sm", "xs" devices?

A: you can track windows size and base of innwewidth update the value of visibleDays
app.component
  visibleDays = 7;

  @HostListener("window:resize", []) updateDays() {
    // lg (for laptops and desktops - screens equal to or greater than 1200px wide)
    // md (for small laptops - screens equal to or greater than 992px wide)
    // sm (for tablets - screens equal to or greater than 768px wide)
    // xs (for phones - screens less than 768px wide)

    if (window.innerWidth >= 1200) {
      this.visibleDays = 7; // lg
    } else if (window.innerWidth >= 992) {
      this.visibleDays = 6;//md
    } else if (window.innerWidth  >= 768) {
      this.visibleDays = 5;//sm
    } else if (window.innerWidth < 768) {
      this.visibleDays = 3;//xs
    }

  }

stackblitz demo


text:
Q: Merging two rows having different value I have a Sample table:
Region    | OpenServices | DFC
Karaci    | 14           | 4
Lahore    | 13           | 3
Islamabad | 10           | 4

This is Second Table
Region    | OpenServices | DFC
Karaci    | 14           | 4
Lahore    | 10           | 3
Islamabad | 10           | 4

I want my Final table to look like
Region    | OpenServices | DFC
Karaci    | 14           | 4
Lahore    | 13 , 10      | 3
Islamabad | 10           | 4

A: I'll assume LUW and a recent one. There you can use the LISTAGG aggregate function:
with Sample(region, openservices, dfc) as (
    values ('Karaci','14','4')
         , ('Lahore','13','3')
         , ('Islamabad','10','4')
), Second (region, openservices, dfc) as (
    values ('Karaci','14','4')
         , ('Lahore','10','3')
         , ('Islamabad','10','4')
)
select region, substr(listagg(openservices,','),1,10), dfc
from (
    select region, openservices, dfc
    from sample
    union
    select region, openservices, dfc
    from second
)
group by region, dfc

The union will eliminate duplicate rows and the we can use listagg to concatenate openservices for the group region, dfc. Here I assumed that dfc is functionally dependent of region (according to you sample data). Since the return type of LISTAGG is a rather long string, I trimmed it down using substr.
Result:
REGION    2          DFC
--------- ---------- ---
Islamabad 10         4
Karaci    14         4
Lahore    10,13      3


text:
Q: WordPress Blog Slug Issue Recently I have made a website and since then I am trying to post my new posts on my blog page but it's not showing there.
I have updated settings also where I have made my blog page as a post page.
Whenever I am trying to go to my blog page from my website it is showing index/blog/
And parent directory underneath that.
If anyone can help me in this I would be more than happy.

A: Check if the Permalink is set to Post Name. If not try to set Post Name as Permalink from Settings > Permalink. (https://i.imgur.com/jJZ9wJo.png)


text:
Q: What does the "0" mean in MongoDB's BinData(0, "e8MEnzZoFyMmD7WSHdNrFJyEk8M=")? The MongoDB shell prints binary data as a Base64-encoded string wrapped in what looks like a function call:
"_id" : BinData(0,"e8MEnzZoFyMmD7WSHdNrFJyEk8M=")

What does the "0" mean?

A: Macrolinux is right but you have to be careful with his example as it will work but by accident.
The first argument to BinData() is the BSON binary subtype which, as has been mentioned is one of the following:
generic:  \x00 (0)
function: \x01 (1)
old:      \x02 (2)
uuid_old: \x03 (3)
uuid:     \x04 (4)
md5:      \x05 (5)
user:     \x80 (128)

These are just helpers so that the deserializer can interpret the binary data differently depending on what those bytes represent except for the subtype 2 which is like the generic subtype but stores an int32 representing the length of the byte array as the first 4 bytes of data.
Now to see why the example is wrong you'll note that calling BinData(2, "1234") doesn't store the binary representing the string "1234" for two reasons:

*

*The BinData function interprets that string as a base64 encoded string.

*Type 2 would require that the first 4 bytes be an int32 containing the length of the byte array.

See bsonspec.org for more information.

A: http://docs.mongodb.org/manual/reference/mongodb-extended-json/#binary
The BSON BinData datatype is represented via class BinData in the shell. Run help misc for more information.
> new BinData(2, "1234")
BinData(2,"1234")

from the shell
help misc
b = new BinData(subtype,base64str)  create a BSON BinData value

The 0 in your case is the BSON subtype
http://bsonspec.org/#/specification
binary  ::=   int32 subtype (byte*)   Binary - The int32 is the number of bytes in the (byte*).
subtype ::=   "\x00"  Generic binary subtype
  |   "\x01"  Function
  |   "\x02"  Binary (Old)
  |   "\x03"  UUID (Old)
  |   "\x04"  UUID
  |   "\x05"  MD5
  |   "\x80"  User defined

Similar question on this thread
http://groups.google.com/group/mongodb-dev/browse_thread/thread/1965aa234aa3ef1e

A: I believe they they correspond to the BSON subtypes:

subtype   ::= "\x00"  Binary / Generic
      |   "\x01"  Function
      |   "\x02"  Binary (Old)
      |   "\x03"  UUID
      |   "\x05"  MD5
      |   "\x80"  User defined

Looking at that, it appears that 0 is almost always a valid choice.


text:
Q: Meta-analysis in R without control group? Purely improvement of symptoms I'm currently trying to perform a meta-analysis in R via the metafor package using data that does not have a control group. In this case, I am looking to see whether or not a type of surgical intervention improves symptoms in these unique type of patients. Essentially, the only data I have from these studies is whether symptoms of their certain pain has improved.
Would this be a meta-analysis of proportions? Or would I do a standard REML in metafor: For example, one paper gives the data that 20/25 patients had symptoms that improved. Thus, would I have 4 data points, "creating" my own control group?:

*

*Surgery_improvement: 20 patients

*Surgery_no_improvement: 5 patients

*No_surgery_improvement: 0 patients (obviously, as this doesn't even exist)

*No_surgery_no_improvement: 25 patients

And then perform a standard meta-analysis?

A: You suggestion that this is a meta-analysis of proportions is correct. If each study gives you the number treated and the number of those who improved then you an analyse those. You second suggestion is flawed because the last group (4) should read no surgery no improvement 0 as that is all you know.
You will probably want to choose one of the options for transforming proportions before doing the meta-analysis especially if they are close to zero or one.
Note that you meta-analysis will be open to the criticism that this is just observational but if that is what the studies available to you have then that would be an unfair criticism.


text:
Q: Remove meta tag refresh My site has a refresh tag like this:
<meta http-equiv='refresh' content='400'>

I have some vídeos embedded and when they're playing I want to remove the refresh.
In a specific function that detects when video is playing I did this using JQuery:
$("meta[http-equiv='refresh']").remove();

But the page still refreshes after 400 secs.
Is there a way to solve this?

A: Removing the meta tag isn't an option, based on the link Robert Rozas added --> Using Javascript to override or disable meta refresh tag
Since I don't have your code I can't help completely, but below is a way to auto refresh the page on load & then stop refreshing it on an event.
Clicking on the Test Button will stop the refresh.. just hook this into your event and it should solve your problem -->
 <script>
$(document).ready(function () {
     $("#test").click(function (e) {
        // This event will clear the timeout
            clearTimeout(timeout);
     });

 var timeout = setTimeout(function()
{
    // The refresh is occurring here
    location.reload();
}, 4000);

});
 </script>
 <button id="test">Test</button>

The following will remove the meta tag (quotes removed)
 $('meta[http-equiv=refresh]').remove();

A: Have you tried using the <noscript> tag? Also, if the .remove function does remove the <meta> from the DOM, then you should make sure that it's not something else refreshing your page!


text:
Q: Unit-testing a class that calls a static method I am trying to unit-test a class 'A' which calls a static method of a class 'B'. Class 'B' essentially has a google guava cache which retrieves a value(Object) from the cache given a key, or loads the object into the cache (in case of a cache-miss) using a service adapter. The service-adapter class in turn has other autowired dependencies to retrieve the object.
These are the classes for illustration purposes:
Class A
public class A {
    public Object getCachedObject(String key) {
        return B.getObjectFromCache(key);
    }
}

Class B
public class B {

    private ServiceAdapter serviceAdapter;

    public void setServiceAdapter(ServiceAdapter serAdapt) {
        serviceAdapter = serAdapt;
    }

    private static final LoadingCache<String, Object> CACHE = CacheBuilder.newBuilder()
                .maximumSize(100)
                .expireAfterWrite(30, TimeUnit.MINUTES)
                .build(new MyCacheLoader());

    public static Object getObjectFromCache(final String key) throws ExecutionException {
        return CACHE.get(warehouseId);
    }

    private static class MyCacheLoader extends CacheLoader<String, Object>  {

        @Override
        public Object load(final String key) throws Exception {
            return serviceAdapter.getFromService(key)
        }
    }
}

Service-Adapter Class
public class ServiceAdapter {
        @Autowired
        private MainService mainService

        public Object getFromService(String key) {
            return mainService.getTheObject(key);
        }
    }

I am able to do the integration test successfully and fetch (or load) the value from (or into) the cache. However, I am unable to write the unit-test for class A. This is what I have tried:
Unit-Test for Class A
@RunWith(EasyMocker.class)
public class ATest {
    private final static String key = "abc";
    @TestSubject
    private A classUnderTest = new A();

    @Test
    public void getCachedObject_Success() throws Exception {
        B.setServiceAdapter(new ServiceAdapter());
        Object expectedResponse = createExpectedResponse(); //some private method
        expect(B.getObjectFromCache(key)).andReturn(expectedResponse).once();
        Object actualResponse = classUnderTest.getCachedObject(key);
        assertEquals(expectedResponse, actualResponse);
    }
}

When I run the unit-test, it fails with a NullPointerException at ServiceAdapter class where the call: mainService.getTheObject(key) is made.
How do I mock the dependency of ServiceAdapter while unit-testing class A. Shouldn't I be just concerned about the immediate dependency that class A has, viz. B.
I am sure I am doing something fundamentally wrong. How should I write the unit-test for class A?

A: You now know why static method are deemed bad practice for unit testing,
as they make mocking almost impossible, esp. if they are stateful.
It is hence more practical to refactor B static methods into a set of non-static public ones.
Class A should get an instance of class B injected, either via constructor or setter injection. In Your ATest you then instantiate class A with a mock of class B and have it return whatever you like depending on your test case and base your assertions on that.
By doing so you really test the unit, which in the end should be the public interface of class A. (This is also why I like for a class to have only one public method in an ideal world.)

Regarding to your specific example: The mock of B should also not care about its own dependencies. You currently write in your test:
 B.setServiceAdapter(new ServiceAdapter());

You are in ATest. Not in BTest. ATest should only have a mock of B, so passing an instance of the ServiceAdapter should not be required.
You only should care how A's public methods behaves, and that may change given certain responses of B's public methods.
What I also find odd is that the method you want to test basically only a wrapper to B. Maybe this makes sense in your case yet this also hints to me that you maybe want to already inject an Object in A instead of an instance of B.
If you want to not get lost in mocking hell it really helps to have as less public methods per class which in turn have as less dependencies as possible. I strive for at three dependencies per class, and allow up to five on special occasions. (Each dependency may have huge impact on the mocking overhead.)
If you have too many dependencies, certainly some parts can be moved to other/new services.

A: Re-writing code to make it more testable has already been explained in another answer. At times it is difficult to avoid these cases.
If you really wanted to mock a static call, you could use PowerMock. You will need to use @PrepareForTest({CACHE.class}) annotation for your class followed by code below in the unit test.
      Object testObject = null; // Change this
      PowerMock.mockStatic(CACHE.class);
      expect(CACHE.get(anyString())).andReturn(testObject);
      PowerMock.replay(CACHE.class);

A: In order to get around this you could wrap an interfaced repository type class around class B.  Once you have an interface you can then stub it for testing purposes.
By doing this you insulate A from the inner workings of B and focus only on the resulting actions of B (I guess this is just another way of saying to program to an interface rather than a concrete class)


text:
Q: HTML5: element  What valid HTML5-tag do you suggest, to combine one or more elements into a group?
Example:

Test1

      <group id="2">
Test 2
</group>

Test2

Test3

Test Text 1 <group id="3">Lorem ipsum dolor</group>

Javascript (with DOM-Utility):
console.log($('group#2'));

A: It depends on the context. Here is the spec for all grouping elements of block level (or I like this visualization). You want something that fits semantically. For example, if you have an article, you'll want to use the
 tag. If you are defining a section of the page, use a
. If you are grouping headers, use <hgroup>. If you are doing x, use x tag.
The list goes on and on and on. Find the appropriate element for the context. But do note, older browsers won't know how to handle the elements, so you'll need to be aware of that in how you style and how you use JavaScript to query the elements.

A: In this situation you should just use a class name:

Test 2


text:
Q: Word count not working using with PyPDF2 error : Stream has ended unexpectedly I am trying to get the word count by simply reading pdf. Below is the chunk code which is working fine on some of the pdf documents and not with some.
Error seems to be PdfStreamError: Stream has ended unexpectedly and not sure how to fix this one as we are not writing any output file.
Code:
> import Crypto from Crypto.Cipher import AES import PyPDF2
>
> a = ["business","book"]
> filename = (r'C:\Users\my_pc\Downloads\bp-annual-report-and-form-20f-2021.pdf')
>
> pdfFileObj = open(filename,'rb') pdfReader =
> PyPDF2.PdfFileReader(pdfFileObj) num_pages = pdfReader.getNumPages()
> num_pages
>
>
> count = 0 text = ""
>
> while count < num_pages:
>     pageObj = pdfReader.getPage(count)
>     count +=1
>     text += pageObj.extractText() text
>
>
> for x in a:
>     print(x,text.count(x))

Error code :
> ignore '/Perms' verify failed
> --------------------------------------------------------------------------- PdfStreamError                            Traceback (most recent call
> last) ~\AppData\Local\Temp/ipykernel_31804/1917676716.py in <module>
>       1 pdfFileObj = open(filename,'rb')
>       2 pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
> ----> 3 num_pages = pdfReader.getNumPages()
>       4 num_pages
>       5
>
> ~\Anaconda3\lib\site-packages\PyPDF2\_reader.py in getNumPages(self)
>     408         """
>     409         deprecate_with_replacement("reader.getNumPages", "len(reader.pages)")
> --> 410         return self._get_num_pages()
>     411
>     412     @property
>
> ~\Anaconda3\lib\site-packages\PyPDF2\_reader.py in
> _get_num_pages(self)
>     395         # the original method (flattened page count) is used.
>     396         if self.is_encrypted:
> --> 397             return self.trailer[TK.ROOT]["/Pages"]["/Count"]  # type: ignore
>     398         else:
>     399             if self.flattened_pages is None:
>
> ~\Anaconda3\lib\site-packages\PyPDF2\generic\_data_structures.py in
> __getitem__(self, key)
>     148
>     149     def __getitem__(self, key: Any) -> PdfObject:
> --> 150         return dict.__getitem__(self, key).get_object()
>     151
>     152     @property
>
> ~\Anaconda3\lib\site-packages\PyPDF2\generic\_base.py in
> get_object(self)
>     161
>     162     def get_object(self) -> Optional[PdfObject]:
> --> 163         obj = self.pdf.get_object(self)
>     164         if obj is None:
>     165             return None
>
> ~\Anaconda3\lib\site-packages\PyPDF2\_reader.py in get_object(self,
> indirect_reference)    1119             and indirect_reference.idnum
> in self.xref_objStm    1120         ):
> -> 1121             retval = self._get_object_from_stream(indirect_reference)  # type: ignore
> 1122         elif (    1123             indirect_reference.generation
> in self.xref
>
> ~\Anaconda3\lib\site-packages\PyPDF2\_reader.py in
> _get_object_from_stream(self, indirect_reference)    1070             read_non_whitespace(stream_data)    1071
> stream_data.seek(-1, 1)
> -> 1072             objnum = NumberObject.read_from_stream(stream_data)    1073
> read_non_whitespace(stream_data)    1074
> stream_data.seek(-1, 1)
>
> ~\Anaconda3\lib\site-packages\PyPDF2\generic\_base.py in
> read_from_stream(stream)
>     294     @staticmethod
>     295     def read_from_stream(stream: StreamType) -> Union["NumberObject", FloatObject]:
> --> 296         num = read_until_regex(stream, NumberObject.NumberPattern)
>     297         if num.find(b".") != -1:
>     298             return FloatObject(num)
>
> ~\Anaconda3\lib\site-packages\PyPDF2\_utils.py in
> read_until_regex(stream, regex, ignore_eof)
>     156             if ignore_eof:
>     157                 return name
> --> 158             raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
>     159         m = regex.search(tok)
>     160         if m is not None:
>
> PdfStreamError: Stream has ended unexpectedly


text:
Q: can a button lose its onclick listener if its repeatedly hidden and shown I have two buttons say "Button A" and "Button B" initially both of which are visible. Clicking  Button B sends a ajax request which brings data and then sets display:none on 'button A' . Again on clicking Button B it brings data but this time sets display:block on 'button A' .
After repeatedly doing the above for  some 10-15 times , button A stops responding and its  onClick function is not even called .
It happens only in chrome , not in IE.
Setting visibility :visible and visiblity:hidden solves the issues but using display property is the requirement.
Is there any solution for the above issue .

A: You can do it either like this:

<button id="toggler">Apply Overlay</button>

<button id="closeit">Close Overlay</button>

http://codepen.io/damianocel/pen/VevpwM
See, the second button is not shown at all times.
Or, if you can use Jquery, you can bind the eventHandler to elements which do not exists yet like this:
$(document).on("click","your button",function(){ your function block});

This will do, I do not know how to do this in vanilla JS, if somebody could explain this, I would appreciate this very much.
Regards


text:
Q: yii2 GridView filtering conflict with other form in the same page I'm new to the Yii framework, and the situation confused me. I have a main form in a view that it has some validations. In addition, I have a gridview inside a modal in this view that it is hidden until the end user click a button in order to choose a field. The problem appeared just when the boss told me to have some search field in the modal (I decided to use filter in gridview for this purpose). After traces I've found that the reason was form validation of the first form when the filter method of gridview is trying to send GET request to the server to receive grid rows that related just with the filter parameters, But it's not working maybe the failure is about my understanding of MVC pattern.
Anyway this is some part of my codes:
View:
/* this section placed inside a modal div beside the main form*/
    echo GridView::widget([
                          'dataProvider' => $dataProvider,
                          'filterModel' => $searchModel,
                          'filterUrl' => Yii::$app->urlManager->createUrl('catm/grid'),
                          'rowOptions' => function ($model, $key, $index, $grid){
                            return ['onclick' => 'setText(\''. $model['name'] . '\');$(\'#myModal\').modal(\'hide\')',
                                    'style' => 'cursor: pointer',
                                ];
                          }
                           ]);

Controller:
 public function actionCreate()
    {
        $modelCatm = new Catm();
        $modelApplication = new \app\models\Application();
        $modelBranch = new \app\models\Branch();
        $modelConfig = new \app\models\Config();
        $modelMedia = new \app\models\Media();
        $modelMessage = new \app\models\Message();
        $modelServiceConfig = new \app\models\ServiceConfig();

        $searchMdl = new BranchSearch();
        $dataPrv = $searchMdl->search(Yii::$app->request->queryParams);

        $webroot = Yii::$app->basePath;

        if ($modelCatm->load(Yii::$app->request->post())){

        //}
//print_r($_GET);
                $transaction=Yii::$app->db->beginTransaction();

                try {

                       //Branch:
                    $modelBranch->attributes = $_POST['Branch'];
                    //echo $modelBranch->attributes['name'];
                    if ($modelBranch->findBySql('select * from branch where name =\'' . $modelBranch->attributes['name'] . '\'')->count()==0) {
                    //echo 'not exists!';
                        if(!$modelBranch->save(false)) {echo 'error in model branch'; return 0;};
                    }

                    //Cashless ATM:
                    $modelCatm->attributes = $_POST['Catm'];
                    if(!$modelCatm->save(false)) {echo 'error in model catm'; return 0;};

                    //Application:
                    /*  file upload handling and saving the path to database*/
                    $modelApplication->attributes = $_POST['Application'];
                    $modelApplication->catm_id = $modelCatm->id;
                    $modelApplication->file = UploadedFile::getInstanceByName('Application[file]');
                    //echo $modelApplication->file->baseName;
                    $modelApplication->validate();
                    $modelApplication->file->saveAs('uploads/application/' . $modelApplication->file->baseName . '.' . $modelApplication->file->extension);
                    $modelApplication->filepath = $webroot . '/uploads/application/' . $modelApplication->file->name;
                    if(!$modelApplication->save(false)) {echo 'error in model application'; return 0;};

                    //Media:
                    /*  file upload handling and saving the path to database*/
                    $modelMedia->attributes = $_POST['Media'];
                    $modelMedia->catm_id = $modelCatm->id;
                    $modelMedia->file = UploadedFile::getInstanceByName('Media[file]');
                    //echo $modelMedia->file->baseName;
                    $modelMedia->validate();
                    $modelMedia->file->saveAs('uploads/media/' . $modelMedia->file->baseName . '.' . $modelMedia->file->extension);
                    $modelMedia->filepath = $webroot . '/uploads/media/' . $modelMedia->file->name;
                    if(!$modelMedia->save(false)) {echo 'error in model media'; return 0;};

                    //Messages:
                    $modelMessage->attributes = $_POST['Message'];
                    $modelMessage->catm_id = $modelCatm->id;
                    if(!$modelMessage->save()) {echo 'error in model message'; return 0;};

                    $transaction->commit();

                } catch (Exception $ex) {
                    $transaction->rollback();
                }

        return $this->render('view',[
            'modelCatm' => $modelCatm,
            'modelBranch' => $modelBranch,
            'modelApplication' => $modelApplication,
            'modelConfig' => $modelConfig,
            'modelMedia' => $modelMedia,
            'modelMessage' => $modelMessage,
            'modelServiceConfig' => $modelServiceConfig,
        ]);

        } else {
            return $this->render('create', [
                'modelCatm' => $modelCatm,
                'modelBranch' => $modelBranch,
                'modelApplication' => $modelApplication,
                'modelConfig' => $modelConfig,
                'modelMedia' => $modelMedia,
                'modelMessage' => $modelMessage,
                'modelServiceConfig' => $modelServiceConfig,
                'searchModel' => $searchMdl,
                'dataProvider' => $dataPrv,

            ]);
        }
    }

I will update the question with more information of my code after your helpful comments if it is required.

A: It has nothing to do with your understanding of MVC mate, Yii does a lot of things for you automatically but sometimes in cases like this you just need to get to do some things by hand.
Probably you need to change the form action in your controller to check if this is a form submission or a gridview navigation / filter and handle it differently. You need to check if some get params exist and bypass the form validation in that case.


text:
Q: Can I write comments in UML Class diagram? What symbol should I use ?

A: Use --.
...if you are looking to comment the UML source, rather than render a comment in a diagram. As mentioned by WileCau above the reference for this is here: http://www.omg.org/spec/OCL/2.2 and is called an Object Constraint Language comment."
-- This section is about [etc.]
[My Thing] -> (Result)

This doesn't work in all UML renderers though - When I tried in PlantUML for example, it considered this a syntax error.

A: If you looking to add a comment in the UML source, depending on the renderer you can use -- or ' for a single line comment.
For PlantUML comments:
@startuml
' This is a comment on a single line
Bob->Alice : hello
/' You quote alors use slash-and-quote
to split your comments on several
lines '/
@enduml

A: Below is an extract from the Unified Modeling Language specification. The complete specification is available at http://www.omg.org/spec/UML/2.3.

9.5.1 Comment
A comment is a textual annotation that
  can be attached to a set of elements.
Description
A comment gives the ability to attach
  various remarks to elements. A comment
  carries no semantic force, but may
  contain information that is useful to
  a modeler. A comment may be owned by
  any element.
Notation
A Comment is shown as a rectangle with
  the upper right corner bent (this is
  also known as a "note symbol"). The
  rectangle contains the body of the
  Comment. The connection to each
  annotated element is shown by a
  separate dashed line.
Presentation Options
The dashed line connecting the note to
  the annotated element(s) may be
  suppressed if it is clear from the
  context, or not important in this
  diagram.


text:
Q: PHP ошибка Parse error: syntax error, unexpected end of file На одностраничном сайте(сайт для продаж) при попытке нажать кнопку "Оформить заказ" выскакивает ошибка Parse error: syntax error, unexpected end of file in .../send.php on line 84
Сам код send.php:
<?php
$phone = $_POST['phone'];
if(empty($phone)) {
?>

<meta http-equiv="content-type"
content="text/html;charset=UTF-8" />
<title>Спасибо!</title>

Вы не ввели
необходимые данные!

Вернитесь на сайт и заполните контакнутю
форму.

<a style="display: inline-block;height:
53px;height: 5.3rem;margin: 0px 0
0px;padding: 0 24px; font-size: 1.8rem;
letter-
spacing: 0.02em; line-height: 53px; line-
height: 5.3rem; text-align: center; text-
decoration: none; color: black; transition:
background-color 0.2s ease-out 0s; border-
radius: 7px; text-shadow: 1px 1px 0px
rgba(255, 255, 255, 0.5); -webkit-box-
shadow: inset 0px -3px 0px 0px rgba(50, 50,
50, 0.2); -moz-box-shadow: inset 0px -3px
0px 0px rgba(50, 50, 50, 0.2); box-shadow:
inset 0px -3px 0px 0px rgba(50, 50, 50,
0.2); background: rgb(196, 255, 161);
width:500px;margin:0 auto;display:block;
border: 1px solid #ccc;" href="./"
class='hover'>
Вернуться на сайт

<?
}else {

$email2="example@gmail.com"; // ------------
----------------------------- почта, куда
отправляем письмо
$headers  =  'MIME-Version: 1.0' . "\r\n";
$headers .=  'Content-type: text/html;
charset=UTF-8' . "\r\n";
$headers .=  'To: <'.$email2.'>, '."\r\n";
$headers .=  'From: <site.ru>' . "\r\n"; //
---------------------- адрес отправителя,
это заголовок письма, менять не обязательно
$subject2    = "Название товара"; // -------
---------------------------------- заголовок
$message2    = "

Имя: ".$_POST['name']."

Телефон: ".$_POST['phone']."

IP-адрес посетителя:
".@$_SERVER['REMOTE_ADDR']."

Время заказа: ".date('Y-m-d H:i:s').";
";
$mail=mail($email2, $subject2, $message2,
$headers);
if($mail==true){
?>

<meta http-equiv="content-type"
content="text/html;charset=UTF-8" />
<title>Спасибо!</title>

Благодарим за
Заявку!

Ваша заявка принята и поставлена в
обработку.

Вы указали следующие данные для обратной связи:

Имя:
<?php
 echo $_POST['name'];
 ?>

 Телефон:
 <?php
 echo $_POST['phone'];
 ?>

<a style="display: inline-block;height: 53px;height:     5.3rem;margin: 0px 0 0px;padding: 0 24px; font-size: 1.8rem;     letter-spacing: 0.02em; line-height: 53px; line-height:     5.3rem; text-align: center; text-decoration: none; color:     black; transition: background-color 0.2s ease-out 0s; border-    radius: 7px; text-shadow: 1px 1px 0px rgba(255, 255, 255, 0.5); -webkit-box-shadow: inset 0px -3px 0px 0px rgba(50, 50, 50, 0.2); -moz-box-shadow: inset 0px -3px 0px 0px rgba(50, 50, 50, 0.2); box-shadow: inset 0px -3px 0px 0px rgba(50, 50, 50, 0.2); background: rgb(196, 255, 161); width:500px;margin:0 auto;display:block; border: 1px solid #ccc;" href="./" class='hover'>
Вернуться на сайт

<?
}else{
echo "no";
}
}
?>

Спасибо

A: Обратите внимание на ваши комментарии, вот к примеру:
$email2="example@gmail.com"; // ------------
----------------------------- почта, куда
отправляем письмо

здесь видно что вы закомментировали только // ------------ это, нижние же строки остались без комментария, из-за этого и ошибка. Пройдитесь по всему коду и закомментируйте всё что требуется

A: У меня такая же проблема возникла в похожем файле, скрипт успешно работал в PHP 5, а при переходе на PHP 7 стала появляться эта ошибка.
У меня были подозрения на такие участки кода:

?> HTML код <?php

.
Да, и когда я их заменил на

echo 'HTML код';

ошибка исчезла.


text:
Q: Interpretation of Weibull Accelerated Failure Time Model Output In this case study I have to assume a baseline Weibull distribution, and I'm fitting an Accelerated Failure Time model, which will be interpreted by me later on regarding both hazard ratio and survival time.
The data looks like this.
head(data1.1)

TimeSurv IndSurv Treat Age
1     6 days       1     D  27
2    33 days       1     D  43
3   361 days       1     I  36
4   488 days       1     I  54
5   350 days       1     D  49
6   721 days       1     I  49
7  1848 days       0     D  32
8   205 days       1     D  47
9   831 days       1     I  24
10  260 days       1     I  38

I'm fitting a model using the function Weibullreg() in R. The survival function is built reading TimeSurv as the time measures and IndSurv as the indicator of censoring. The covariates considered are Treat and Age.
My issue deals with understanding the output properly:
wei1 = WeibullReg(Surv(TimeSurv, IndSurv) ~ Treat + Age, data=data1.1)
wei1

$formula
Surv(TimeSurv, IndSurv) ~ Treat + Age

$coef
            Estimate           SE
lambda  0.0009219183 0.0006803664
gamma   0.9843411517 0.0931305471
TreatI -0.5042111027 0.2303038312
Age     0.0180225253 0.0089632209

$HR
              HR       LB       UB
TreatI 0.6039819 0.384582 0.948547
Age    1.0181859 1.000455 1.036231

$ETR
             ETR        LB        UB
TreatI 1.6690124 1.0574337 2.6343045
Age    0.9818574 0.9644488 0.9995801

$summary

Call:
survival::survreg(formula = formula, data = data, dist = "weibull")
               Value Std. Error     z      p
(Intercept)  7.10024    0.41283 17.20 <2e-16
TreatI       0.51223    0.23285  2.20  0.028
Age         -0.01831    0.00913 -2.01  0.045
Log(scale)   0.01578    0.09461  0.17  0.868

Scale= 1.02

Weibull distribution
Loglik(model)= -599.1   Loglik(intercept only)= -604.1
    Chisq= 9.92 on 2 degrees of freedom, p= 0.007
Number of Newton-Raphson Iterations: 5
n= 120

I don't really get how Scale = 1.02 and log(scale) = 0.015, and if the p-value of this log(scale) is a big non-signfificant one, from how the documentation of the function shows some conversions it makes, am I to assume that the values of the alphas are also not to be trusted (considering they were reached using the scale value)?

A: Many (including me) get confused by the different ways to define the parameters of a Weibull distribution, particularly since the standard R Weibull-related functions in the stats package and the survreg() parametric fitting function in the survival package use different parameterizations.
The manual page for the R Weibull-related functions in stats says:

The Weibull distribution with shape parameter $a$ and scale parameter $b$ has density given by
$$\frac{a}{b}\left(\frac{x}{b}\right)^{a-1}e^{-(x/b)^{a}}$$
for $x$ > 0.

That's called the "standard parameterization" on the Wikipedia page (where they use $k$ for shape and $\lambda$ for scale).
The survreg() function uses a different parameterization, with differences explained on its manual page:

There are multiple ways to parameterize a Weibull distribution. The survreg function embeds it in a general location-scale family, which is a different parameterization than the rweibull function, and often leads to confusion.
survreg's scale  =    1/(rweibull shape)
survreg's intercept = log(rweibull scale).

The WeibullReg() function effectively takes the result from survreg() and expresses the results in terms of the "standard parameterization."
There is a potential confusion, however, as the $summary of the object produced by WeibullReg is "the summary table from the original survreg model." (Emphasis added.) So what you have displayed in the question includes results for both parameterizations.
That dual representation of the results helps explain what's going on.
Starting from the bottom, the survreg value of scale is the reciprocal of the "standard parameterization" value of shape. The "standard" shape parameter is called gamma in the WeibullReg $formula output near the top of your output. The value for gamma is  0.98434, with a reciprocal of 1.0159, rounding to the value of 1.02 shown as Scale in the last line of your output. The natural logarithm of 1.0159 is 0.01578, shown as Log(scale) in the next-to-last line. Those last lines of your output, remember, are based on the survreg definition of scale.
The p-value for that Log(scale) is indeed very high. But that just means that the value of Log(scale) is not significantly different from 0, or that the scale itself (as defined in survreg) is not different from 1. That has nothing to do with the hazard ratios and so forth for the covariates. It just means that the baseline survival curve of your Weibull model can't be statistically distinguished from a simple exponential survival curve, which would have exactly a value of 1 for survreg scale or "standard" shape and a constant baseline hazard over time. So there is nothing to distrust about your results on that basis.


text:
Q: Failing to connect to server via SSH - "Server refused to allocate pty" I have a STRATO V-PowerServer running with Ubuntu 10.10 for my stuff but lately have problems connection to the server via ssh.
Basically all I have is ssh-access to the server and if necessary I can boot into a recovery-mode where all my stuff is in /repair so that I can do any fixes on the system.
The problem is, that when I try to connect to the server via ssh I get this error:
Using username "florian".
florian@mydomain.de's password:
Server refused to allocate pty
Linux hwn36335 2.6.18-028stab070.5 #1 SMP Fri Sep 17 15:37:23 MSD 2010 i686 GNU/Linux
     Ubuntu 10.10

                 Welcome to Ubuntu!
                                    * Documentation:  https://help.ubuntu.com/
                                                                              /home/florian/.zlogin:1: command not found: display_info

So the shell doesn't open and I can't enter any commands. I've already tried to google for "Server refused to allocate pty" but couldn't find anything that helped, though the problem has happened to other people before. Additionally, I sometimes even get a different error: "pty allocation request failed on channel 0" instead of the other error. For this problem all I could find was this:
http://blog.dinotools.de/2010/10/03/fehler-pty-allocation-request-failed-on-channel-0
But unfortunately it didn't help...
Does anybody have an idea why this error is caused and what I could try to fix it?
Would be great if you could give me tips. I know some basic things and know how to work with my server but if it goes this deep into problem-solving I am at my limits... ;-) Thanks!
Addition 1:
/var/log/auth.log
Jan 24 16:20:01 h1696522 CRON[3417]: PAM unable to dlopen(/lib/security/pam_smbpass.so): /lib/security/pam_smbpass.so: cannot open shared object file: No such file or directory
Jan 24 16:20:01 h1696522 CRON[3417]: PAM adding faulty module: /lib/security/pam_smbpass.so
Jan 24 16:20:01 h1696522 CRON[3417]: pam_unix(cron:session): session opened for user www-data by (uid=0)
Jan 24 16:20:03 h1696522 CRON[3417]: pam_unix(cron:session): session closed for user www-data

/var/log/daemon.log
Jan 24 16:00:02 h1696522 update.pl[14292]: /var/drweb/bases/dwr50003.vdb - dwr50003.vdb with such CRC32 already exists, downloading has been skipped
Jan 24 16:00:02 h1696522 update.pl[14292]: /var/drweb/bases/dwr50004.vdb - dwr50004.vdb with such CRC32 already exists, downloading has been skipped
Jan 24 16:00:02 h1696522 update.pl[14292]: /var/drweb/bases/dwr50005.vdb - dwr50005.vdb with such CRC32 already exists, downloading has been skipped
Jan 24 16:00:02 h1696522 update.pl[14292]: /var/drweb/bases/dwr50006.vdb - dwr50006.vdb with such CRC32 already exists, downloading has been skipped
Jan 24 16:00:02 h1696522 update.pl[14292]: /var/drweb/bases/dwr50007.vdb - dwr50007.vdb with such CRC32 already exists, downloading has been skipped
Jan 24 16:00:02 h1696522 update.pl[14292]: /var/drweb/bases/dwr50008.vdb - dwr50008.vdb with such CRC32 already exists, downloading has been skipped
Jan 24 16:00:02 h1696522 update.pl[14292]: /var/drweb/bases/dwr50009.vdb - dwr50009.vdb with such CRC32 already exists, downloading has been skipped
Jan 24 16:00:02 h1696522 update.pl[14292]: /var/drweb/bases/dwrtoday.vdb - dwrtoday.vdb with such CRC32 already exists, downloading has been skipped
Jan 24 16:00:02 h1696522 update.pl[14292]: /var/drweb/updates/timestamp -    timestamp with such CRC32 already exists, downloading has been skipped
Jan 24 16:00:02 h1696522 update.pl[14292]: /var/drweb/bases/update.drl -   update.drl with such CRC32 already exists, downloading has been skipped
Jan 24 16:00:02 h1696522 update.pl[14292]: deleting old files ...
Jan 24 16:00:02 h1696522 update.pl[14292]: moving downloaded files from temporary to working directory ...
Jan 24 16:00:02 h1696522 update.pl[14292]: sending notifications ...
Jan 24 16:00:02 h1696522 update.pl[14292]: summary => updated: 0, removed: 0 files and 0 messages
Jan 24 16:00:02 h1696522 update.pl[14292]: Finish Success:   2011-01-24 16:00:02
Jan 24 16:00:02 h1696522 update.pl[14292]: Socket path is /var/drweb/run/updateSock

A: If you have console access
mount devpts /dev/pts -t devpts

A: Did you tried to re-create pty and tty devices ?
root@mydomain.de:~# /sbin/MAKEDEV tty
root@mydomain.de:~# /sbin/MAKEDEV pty

It seems to be a known issue on virtual servers...
If you don't have access to any shell, you could try sending the command via ssh :
florian@localmachine:~$ ssh root@mydomain.de "/sbin/MAKEDEV tty"
florian@localmachine:~$ ssh root@mydomain.de "/sbin/MAKEDEV pty"

Edited to reflect your comment :
If you use a chroot, you also have to mount /proc, /dev and /sys :
root@h1696522:/# mount -o bind /proc /repair/proc
root@h1696522:/# mount -o bind /dev /repair/dev
root@h1696522:/# mount -o bind /sys /repair/sys

It should work now.

A: The times I have encoutered this error I fixed it certifying that the udev package was installed and running. Udev takes care of creating device nodes when they are needed, like the PTS/x that are needed by ssh. Give it a try.

A: Try this:
ssh root@host "mount -o remount /dev/pts"

A: I had to do a combination of what is posted here. My permissions were wrong and /dev/pts was already mounted.
mount -t devpts -o remount,seclabel,nosuid,noexec,uid=0,gid=5,mode=620 devpts /dev/pts

Use this to verify that your permissions are correct.
grep devpts /proc/mounts

Also check /dev/pts. It should be 755 and owned by root.
ls -dl /dev/pts
chmod 755 /dev/pts
chown root:root /dev/pts

Check sshd_config file. PermitTTY should not be set to no. If it is either comment it out or set it to yes. Then restart sshd.
vi /etc/ssh/sshd_config
service sshd restart
systemctl restart sshd


text:
Q: SortedList porting to Silverlight It looks SortedList is excluded.. What do you think most appropriate out of existing collections? (to keep the same fast access and changes)
Can silverlight Dictionary be permanently sorted?
Best regards
VLK

A: I ported both the Wintellect Power Collections and the C5 Generic Collections to Silverlight. I made them available here - http://jaykimble.net/powercollections-and-c5-collections-for-silverlight4.aspx.
I did this mostly because this question peaked my interest. Feel free to use them in any type of project you would like to use them with.

A: To answer your question: No.  The dictionary does not guarantee ordered items by key.
However the List<T> supports the BinarySearch method.  This can help you acheive similar goals of the SortedList.
The documentation has a nice example of how that is basically acheived.  See:-
List<T>.BinarySearch Method (T)

A: You might take a look at Wintellect's Power Collections.  This library is free under the EPL.  I think the OrderedMultiDictionary will do the trick for you.  You should be able to compile this under Silverlight.  I have not used this for a couple of years but did use this library (and Richter's threading library) for a WPF project.
Edit:
After playing around with this it looks like you will need to do a little work to get the power collections to work in Silverlight.

A: My workaround for not having silverlight was to create a generic list with a KeyValuePair type and then ordering the list.
List<KeyValuePair<int, string>> sampleList = new List<KeyValuePair<int, string>>();

//Assuming you have a set of objects in an array or list
foreach(var item in items)
{
   sampleList.Add(new KeyValuePair<int, string>>(item.ID, item.Description))
}

sampleList = sampleList.OrderBy(data => data.Key).ToList();

The effect is the same as using a sorted list.


text: Q: Is Hessian=0 for linear Linear least square minimization as Jacobian is a constant matrix. As opposed to non-linear least square minimization? As we know the residual functions are linear for least square minization problem, this makes the jacobian a constant matrix so, will the Hessian which is a square matrix and considered as an analog of double derivative be 0 in the linear case? While, in some places I see that for linear case $H=J^{T}J$ is given.


text:
Q: How to show only 'x' amount of values on a graph in python I am new to python and am carrying out some little projects along side watching tutorials to enable me to learn.
I have recently been working with some APIs to collect data - I save this data in a CSV file and then open the CSV file to show the data as a graph.
I want the graph to show the data LIVE, but in doing so I only want 10 values on the screen at once, so when the 11th value is plotted, the 1st is no longer visible unless the scrolling function is used to look back at it..
I have managed to pull together the code that plots the live data from the CSV file, as well as some code that creates the graph in the desired format - but as I am quite new to python I am unsure of how I'd make them work together.. Any advice would be greatly appreciated.
Below is the code that I have created to read and plot from a CSV file:
import random
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

index = count()

def animate(i):
    data = pd.read_csv('x.csv')
    x = data['Time']
    y = data['R1Temp']
    y1 = data['R2Temp']
    y2 = data['R3Temp']

    plt.cla()

    plt.plot(x, y, marker = 'o', label='Room 1 Temp')
    plt.plot(x, y1, marker = 'o', label='Room 2 Temp')
    plt.plot(x, y2, marker = 'o', label='Room 3 Temp')

    plt.xlabel("Time")

    plt.ylabel("Temperature °C")
    plt.title("Live temperature of Rooms")

    plt.legend(loc='upper left')
    plt.tight_layout()

ani = FuncAnimation(plt.gcf(), animate, interval=1000)

plt.tight_layout()
plt.show()

Below is the code that shows the way in which I'd like the graph to format the data plots:
import numpy as np
import matplotlib.pyplot as plt

import matplotlib.animation as animation

def update(frame):
    global x, y

    start = x[max(frame-PAN//2, 0)]
    start = x[max(frame-PAN+1, 0)]
    end = start + PAN

    ax.set_xlim(start, end)

    start, end = ax.get_xlim()
    ax.xaxis.set_ticks(np.arange(start, end, TICK))

    ax.figure.canvas.draw()

    line1.set_data(x[0:frame+1], y[0:frame+1])

    return (line1,)

# main
NUM = 100
TICK = 1
PAN = 10

x = np.arange(start=1, stop=NUM + 1, step=1)

for i in range(NUM):
    y = np.random.rand(NUM) * 100

fig, ax = plt.subplots()

ax.set_xlim(0, PAN)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, TICK))

ax.set_ylim(0, 100)

line1, = ax.plot([], [], color="r")

ani = animation.FuncAnimation(fig, update, frames=len(x), interval=1000, repeat=False)

plt.show()

I have tried many ways to merge them together, but I just cant seem to find the correct way to go about it.
Thanks in advance!!

A: Showing the last N time points is quite easy. Just use DataFrame.tail() to get the last N rows of your dataframe.
Note that when doing an animation, the recommended way is to create your axes and artists outside the animation code, and only update your artists' data inside the animate code.
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()

l1, = ax.plot([], [], marker='o', label='Room 1 Temp')
l2, = ax.plot([], [], marker='o', label='Room 2 Temp')
l3, = ax.plot([], [], marker='o', label='Room 3 Temp')

plt.xlabel("Time")
plt.ylabel("Temperature °C")
plt.title("Live temperature of Rooms")
plt.legend(loc='upper left')
plt.tight_layout()

def animate(i, N):
    data = pd.read_csv('x.csv').tail(N)

    l1.set_data(data['Time'], data['R1Temp'])
    l2.set_data(data['Time'], data['R2Temp'])
    l3.set_data(data['Time'], data['R3Temp'])

    ax.relim()
    ax.autoscale_view()

    return l1, l2, l3

ani = FuncAnimation(fig, animate, interval=1000, frames=None, fargs=(10,))

plt.show()