text:
Q: $pull from subschema with condition mongodb employeeStructureSchema.js
var employeeStructureSchema = new Schema({
    name: String
});
module.exports = mongoose.model('employeeSturctureModel', employeeStructureSchema);

companySchema.js
var employeeStructureSchema = require('./employeeStructureSchema.js').schema;

var companySchema = new Schema({
    companyName: String,
    phone: String,
    email: { type: String, lowercase: true },
    companyAddress: String,
    settings: {
        "employees": [employeeSchema],
    },
});
module.exports = mongoose.model('companies', companySchema);

My aim is to remove some employees whoever name starts with "dummy user" from settings.employees
i have tried following query. it is working. can you please suggest something
db.companies.update({"_id":objectId},{$pull:{"settings.employees":{ $elemMatch: {name: /^dummy user/}}}});

my single document is like this :
{
    "_id" : ObjectId("563b35d1f07cc9d80a26436c"),
    "settings" : {
        "employees" : [
            {
                "_id" : ObjectId("583d28253722e240103e0108"),
                "name" : "dummy user"
            },
            {
                "_id" : ObjectId("583d282e3722e240103e0109"),
                "name" : "dummy user1"
            },
            {
                "_id" : ObjectId("583d28403722e240103e010b"),
                "name" : "dummy user2"
            }
        ]
    }
}

A: Assuming your employee name is a type of list. You can try a query like this:
db.companies.update({},{$pull: {settings.employees.name: { $regex: '^dummy user'} }});

Since your schema is restricted, this query should work
  db.companies.update({},{
   '$pull': {
      'settings.employees': {
          'name':{ $regex: '^dummy user'}
      }
    }
  });


text:
Q: linkedin integration with cocoa app OS X. i need to send invitiations to linkedin contacts from my cocoa app linkedin integration with cocoa app OS X. i need to send invitiations to linkedin contacts from my cocoa app.please give detail explanation and sample codes as i am new biee to cocoa programming
i am using this project to try something atleast...https://github.com/nxtbgthng/OAuth2Client
but not able to do kindly please help..

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find required elements among multiple items in one list? I have a list which contains multiple filename:
example_list = ['2021-08-09_01.csv', '2021-08-09_02.csv', '2021-08-10_12.csv',
                '2021-08-10_03.csv']

I want to return a new list which includes the days that are inside the example_list:
new_list = ['09','10']

Regardless the number after the day string, what's the easiest way to achieve this?

A: You can use a set comprehension where you slice the needed part from the string elements, and then (if actually needed) convert the created set into a
list:
example_list = ['2021-08-09_01.csv', '2021-08-09_02.csv', '2021-08-10_12.csv', '2021-08-10_03.csv']

new_list = list({elem[8:10] for elem in example_list})

print(new_list)

Output:
['09', '10']

A: You can use str.split to get the day string and then use set() to remove duplicates:
new_list = list(set(s.split("-")[-1].split("_")[0] for s in example_list))
print(new_list)

Prints:
['10', '09']

A: You could try like this.
Split the sub-string (i[8:]) at _ and select the first item. Use a set to remove duplicates.
example_list = ['2021-08-09_01.csv', '2021-08-09_02.csv', '2021-08-10_12.csv', '2021-08-10_03.csv']

s = {i[8:].split('_')[0] for i in example_list}
print(list(s))

['09', '10']


text:
Q: sendmail not sending my sendmail is not sending to AOL emails
Here is the message I get
Jan  4 19:18:40 doonsroom sm-mta[10961]: STARTTLS=client, relay=mailin-04.mx.aol.com., version=TLSv1/SSLv3, verify=FAIL, cipher=DHE-RSA-AES256-SHA, bits=256/256
Jan  4 19:18:40 doonsroom sm-mta[10961]: s04FIdlJ010959: to=<email@aol.co.uk>, ctladdr=<www-data@doonsroom> (33/33), delay=00:00:01, xdelay=00:00:01, mailer=esmtp, pri=120558, relay=mailin-04.mx.aol.com. [64.12.91.196], dsn=5.0.0, stat=Service unavailable
Jan  4 19:18:40 doonsroom sm-mta[10961]: s04FIdlJ010959: s04FIelJ010961: DSN: Service unavailable

Please help
Thank you

A: Take a look at bounce email generated by your sendmail
OR
As user root send a test message with SMTP session tracking:
#!/bin/sh
RECIPIENT=email@aol.co.uk
SENDER=jd@example.net
/usr/sbin/sendmail -Am -i -v -f$SENDER -- $RECIPIENT <<END
To: $RECIPIENT
From: $SENDER
Subject: test!

test!
END


text:
Q: The desktop cannot be created because its area is too large with ati card and dual monitors I have two monitors (1920x1200 and 2550x1600) and ati card (hd 4870x2).
I installed the ati drivers from additional drivers panel.
Unfortunately ulike in previous versions of ubuntu I am unable to set the proper resolutions for my two monitors.
I get the message:
The desktop cannot be created because its area is too large.
Have you encountered this problem. What is the possible solution.

A: You need to define your 2 screens in AMD soft.

*

*Open ATI driver application

*and define your 2 screens display without any limit.

*and re-boot

*you might see no changes, but to end the manipulaation, use then the normal Screen application to set your 2 screens.
And for new Ubuntu behaviors too like:

*

*unity toolbar on only screen, or on both (in english it's got to be "launcher position")

*mouse stuck on screen border (in english it's got to be "sticky border")

A: I have the same issue on a 27 inch iMac running Ubuntu 12.04 64bit.
It has an ATI Mobility Radeon HD 4850 in it.
I get the same exact error message if I attempt to set the two monitors to their max resolution, and then arrange them side by side.
A couple of retarded workarounds are to move the second monitor below the first, as apparently the complete desktop resolution of the two combined at this arrangement is accepted.
Through some testing I found that the max Desktop Area width seems to be 4000, and I am going to guess the max height is also 4000.  It is not a total area calculation either, as I can arrange the monitors in such a way as to use more total screen area than the normal arrangement would, and that is allowed.
Seems to be something that limits it to 4000.
Another things that worked for me, is to rotate my second monitor so that it is vertical, this reduced the width enough to make the resolution acceptable.  This doesn't work very well for me, as my second monitor looks very bad vertical due to the viewing angle design of the monitor.
I found that you can forcibly set the resolution via the xorg.conf however, this doesn't work.  The section of the screen area beyond 4000 becomes corrupted.

A: There are two solutions I've found to the same problem.
Solution 1.  Disable proprietary driver.  Reboot.  Now go to Settings > Displays and uncheck the "mirror displays" box.  You may also wish to alter the "launcher placement" setting so that you have one launcher on one monitor, not an additional one on the 2nd monitor.  You may also wish to disable "sticky edges" so that your mouse won't catch when moving between the two monitors.
Solution 2. This is a clarification of Boris's answer who recommends using the AMD/ATI control panel, but his image was in French and there are more details needed. If you're really set on running the proprietary driver, open AMD Catalyst Control Center (I use the Administrative version, not sure if that's required or not).  Then you'll need to set the two monitors to have nothing to do with each other... not mirroring, and not multi-desktop.  Just single.  Then reboot.  THEN in the next page down in Catalyst Control Center's option pages, enable Xinerama, and reboot again.
In some cases the latter solution doesn't work.  For example in my current situation, something wasn't allowing me to dissociate the two monitors... they kept getting forced into cloning.  I was allowed to change the setting, but as soon as I closed the application the setting was lost.

A: Latest (v12.4) directly from AMD's site fixed this dual monitor resolution issue for me.
I have HD4850.
I presume that Jockey is offering older version.


text:
Q: Javascript - Is there an easier way to read obfuscated, condensed code? Is the code below an example of obfuscation? Is there a way to make code that has been obfuscated easier to interpret or follow the actions that lead through the script using chrome or firefox browsers? Are the original naming conventions somewhere behind the scenes? In other words, could I de-obfuscate the code short of downloading a couple hundred lines and then renaming everything based on what I think is happening?
main: function (a, b, c, d, e) {
    var r,
        o,
        s = null != t ? t : {
        },
        l = i.helperMissing,
        c = 'function',
        d = e.escapeExpression;

A: That code is a result of minification and obfuscation which results in condensed code, and thus unreadable code. The entire point of minification is to reduce file size, so you the "real" function, attribute, and values aren't stored somewhere to be found. The idea of obfuscation is to make the code hard to decypher and "steal".
If you found this somewhere and the file ended in .min.js, you can always see if the same file exists in that location without the .min part in the filename.
For example
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js
Also, it would be near impossible for software to deobfuscate code, but you could read through it and try to understand its meaning. Here's a simple example
x=(a,b)=>a+b // obfuscated/minified code

function sum(number1, number2) { return number1 + number2 } // original code


text:
Q: Login and verify user - Call to a member function getKey() on null I am trying to create a custom verification flow, where as soon as a user clicks the verification link, it logs him in and also verifies him, instead of first making him log in and only then the verification link works.
I built a custom notification URL in my CustomVerificationNotification, including the registered user_id, to login him later:
protected function verificationUrl($notifiable)
{
    if (static::$createUrlCallback) {
        return call_user_func(static::$createUrlCallback, $notifiable);
    }

    return URL::temporarySignedRoute(
        'verification.custom-verify',
        Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),
        [
            'id' => $notifiable->getKey(),
            'hash' => sha1($notifiable->getEmailForVerification()),
            'user_id' => $this->user->id
        ]
    );
}

Then in my web.php I added this route:
Route::get('/email/verify/{id}/{hash}/{user_id}','Auth\CustomVerifyController@login_and_verify')->name('verification.custom-verify');

Then in my CustomVerifyController:
public function login_and_verify(EmailVerificationRequest $request)
{
    //..
}

But I get Call to a member function getKey() on null. And I can't edit EmailVerificationRequest, so what can I do? Is it possible to somehow call Auth::login($user); before calling the EmailVerificationRequest? (Because I have the user_id from the route)
I tried to follow the best answer from this post as well: How to Verify Email Without Asking the User to Login to Laravel
But I'm not sure then how to trigger the verify() method from the web.php and send the $request when I'm first calling the verify_and_login method

A: First you need verify that the URL is signed by adding the middleware signed
You don't want that anoyone having the url /email/verify/{id}/{hash}/{user_id} able to access this ressource without the signature.
web.php
Route::get('/email/verify/{id}/{hash}/{user_id}','Auth\CustomVerifyController@login_and_verify')
      ->middleware('signed')
      ->name('verification.custom-verify');

Then you need to verify that the hash correspond the user_id and for that you can use a Request or a Middleware. I think the Request fits better since Laravel already uses a Request for this.
CustomEmailVerificationRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Http\FormRequest;

class EmailVerificationRequest extends FormRequest
{

    public function authorize()
    {

        $user = User::findOrFail($this->route('id'));

        if (! hash_equals((string) $this->route('hash'), sha1($user->getEmailForVerification()))) {
            return false;
        }

        return true;
    }

}

Finally you need to login with the user and set is email as verified
CustomVerifyController.php

public function login_and_verify(CustomEmailVerificationRequest $request)
{
    $user = User::findOrFail($this->route('id'));

    Auth::login($user);
    $user->markEmailAsVerified();

    event(new Verified($user));

    ...

}

[Edit to add addition feature from comments]
In order to have a middleware that verify the signed URL and resend automatically the verification email, you need to build a custom middleware.
ValidateSignatureAndResendEmailVerification.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Routing\Exceptions\InvalidSignatureException;
use URL;

class ValidateSignatureAndResendEmailVerification
{

    public function handle($request, Closure $next, $relative = null)
    {
        if(! URL::hasCorrectSignature($request, $relative !== 'relative')( {
            throw new InvalidSignatureException;
        }

        if (URL::signatureHasNotExpired()) {
            return $next($request);
        }

         return redirect()->route('resend-email-confirmation');
    }
}

Then you need to add the middleware to Kernel.php
Kernel.php
    protected $routeMiddleware = [
        ...
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'signed.email' => \App\Http\Middleware\ValidateSignatureAndResendEmailVerification::class,
        ...
    ];

Then, don't forget to update your route with the new middleware
web.php
Route::get('/email/verify/{id}/{hash}/{user_id}','Auth\CustomVerifyController@login_and_verify')
      ->middleware('signed.email')
      ->name('verification.custom-verify');


text:
Q: Where is specification for hex_md5 method in MongoDB shell I searched through many and many pages on the Internet and could not find anywhere a definition or specification of hex_md5(str) method in MongoDB shell. Did I missed it or it just does not exists?
Does it comes from Javascript itself? Chrome console does not know about this method. OR perhaps it is coming from Node.js somehow? I spend quite some good hours searching for this.
Additional, I would like to know what other builtin hash functions are available in MongoDB?


text:
Q: How to access Bluetooth device after receiving ACTION_ACL_CONNECTED I'm connecting to a Bluetooth device using connectGatt() with autoConnect=true. If the connection is lost and the device re-appears and re-connects, I get an ACL_CONNECTED intent from my BroadcastReceiver. However, I'm not clear on how I'm supposed to access the device to write/read data at this point.
Normally, I call connectGatt() with a BluetoothGattCallback. When the device is connected, the bluetooth stack gives me a BluetoothGatt which I can then use to access the device (e.g. BluetoothGatt.discoverServices()`.
But with autoconnect, when I receive ACTION_ACL_CONNECTED the device is already connected. If I call connectGatt() again, the stack ends up returning two copies of everything, so I think I shouldn't call connectGatt() again. However, if I don't, how I do get a BluetoothGatt object to access the device?

A: It turns out calling connectGatt() is the correct thing to do. The reason I was getting multiple copies is because the previous BluetoothGatt object lingered around. In order to allow auto-connect to work, that first BluetoothGatt object had to be kept. What worked for me is to keep that object until I get ACL_CONNECTED, close that object, and then create a new callback.


text:
Q: Yii2 RBAC DbManager error Call to a member function getRole() on null I've set up the database etc by having implemented SQL code to set up the tables and the rbac/init script to fill out the roles / permissions.
I have an assign() at user creation but I keep receiving this error on the getRole():
yii\base\ErrorException Call to a member function getRole() on null
   public function addUser()
{
    if($this->validate()) {
        $user = new User();
        $auth_key = Yii::$app->getSecurity()->generateRandomString(32);
        $this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password);

        $user->email = $this->email;
        $user->password = $this->password;
        $user->active = $this->active;
        $user->firstname = $this->firstname;
        $user->lastname = $this->lastname;
        // $user->nickname = $this->nickname;
        $user->datecreated = time();
        $user->auth_key = $auth_key;
        $user->save(false);

        $auth = Yii::$app->authManager;
        $authorRole = $auth->getRole($this->role);
        $auth->assign($authorRole, $user->getId());

        return $user;
    }else{
        return false;
    }
}

the $role variable is passed through $_POST along with the other user attributes.
Please help. Thanks.

A: You've gone the wrong way about it.
The issue here seems to be that Yii::$app->authManager is not set when it should be. This probably means that your main.php configuration file does not contain the correct information.
It should contain the following component:
return [
    // ...
    'components' => [
        'authManager' => [
            'class' => 'yii\rbac\DbManager',
        ],
        // ...
    ],
];

(http://www.yiiframework.com/doc-2.0/guide-security-authorization.html#configuring-rbac-manager)
In the example from the link above PhpManager is used but in your case you will want to use yii\rbac\DbManager
Doing it this way means that you will only have one loaded manager and will also unlock all action filtering options.

A: I seem to have fixed this by replacing
$auth = Yii::$app->authManager;

with
$auth = new DbManager;

Let me know if this is the wrong way to go about it!


text:
Q: Why aren't React components displayed? I'm trying my hand at studying react. I want to create a simple template from bootstrap components, but react doesn't see the components when compiling.
app.js
import React from "react";
import { BrowserRouter as Router, Route, Routes} from 'react-router-dom';
import Layout from './hocs/Layout';
import Home from './components/Home';
import Blog from './components/Blog';
import BlogDetail from './components/BlogDetail';
import Category from './components/Category';

function App() {
    return(
        <Router>
        <Layout>
            <Routes>
                <Route exact path='/' component={Home} />
                <Route exact path='/blog' component={Blog} />
                <Route exact path='/blog/:id' component={BlogDetail} />
                <Route exact path='/category/:id' component={Category} />
            </Routes>
        </Layout>
    </Router>
    );
};

export default App;

index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Home.js
import React from "react";

function Home(){
    return(

Card title

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

    );
};

export default Home;

import Navbar from '../components/Navbar'

const Layout = (props) =>(

        <Navbar />
        {props.children}

);

export default Layout

p.s. Navbar react sees, but the home component does not. There is no code even in the console, although they are identical in content.
Each route should show the layout navbar and load the component that is called by the route. Layout and Navbar are seen by the reactor, but everything else is not even reflected in the browser console.

A: You can upgrade to v6 and use an Outlet component in your Layout to do what you want using react-router-dom.
The Outlet allows nested UI to show up when child routes are rendered.
import { Outlet } from 'react-router-dom';

import Navbar from '../components/Navbar'

const Layout = () => {
  return (

      <Navbar />

        <Outlet />

  );
};

export default Layout;

Also, your App component would need to be refactored like this:
function App() {
  return(
    <Router>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<Home />} />
          <Route path='blog' element={<Blog />} />
          <Route path='blog/:id' element={<BlogDetail />} />
          <Route path='category/:id' element={<Category />} />
        </Route>
      </Routes>
  </Router>
  );
};


text:
Q: MDI Child Form Start Position Problem I am having this strange problem with the start position of the MDI child Form.
Here is my code for the start position, I wanted it to be the middle left of
the MDI Parent Form.
        //show the task bar
        ChildForm c1 = new ChildForm();

        c1.MdiParent = this;
        c1.StartPosition = FormStartPosition.Manual;
        c1.Location = new Point(0, this.Height/2);

Strange thing is every time I start my Mdi parent form, the vertical scrollbar show up
and the mdi child form is position lower than half of the MDI parent form's height.
Then if I scroll the scroll bar down to see the whole mdi child form, the scrollbar disappear.
After this point, no matter how I change the size of the mdi parent form, the scrollbar will
not show up again.
Does Anybody knows Why?
Also, I was wondering if it is possible to hide a mdi child form with only a handle-like control left
in the mdi parent form. If the user click that handle, then the form show up again. If the user
click somewhere else, the form hide. It is kind of like Window taskbar.
I tried to use form.hide(), but it hides the whole mdi child form.
Thanks
Alex

A: Is is possible that your calculation is taking into account the windows bar at the top.
You can have a look at PointToClient or PointToScreen

A: you sholud minuse child form height and width like this
c1.Location = new Point(0, (this.Height - c1.Height)/2);


text:
Q: What is the total variation of sin over an arbitrary interval? I need to find the total variation of $\sin$ over $[a,b]$. Just playing around with it, it would seem that $\int_a^b|\sin(x)|dx$ gives the correct answer, but I'm unsure of how I could show that to be the case. If that's not correct, then how else can I approach the problem?

A: For any $k\in\mathbb{Z}$, between $k\frac{\pi}{2}$ and $(k+1)\frac{\pi}{2}$ the sine function is monotonic and has a total variation equal to $1$, hence over some interval $[a,b]$ the total variation is bounded by:
$$\left\lceil\frac{2}{\pi}|b-a|\right\rceil.$$
Obviously the exact value of the total variation on $[a,b]$ depends on the positions of $\min\left([a,b]\cap\frac{\pi}{2}\mathbb{Z}\right)$ and $\max\left([a,b]\cap\frac{\pi}{2}\mathbb{Z}\right)$ with respect to the endpoints of $[a,b]$.


text:
Q: How to mapping Char(20) data type as Primary Key MySQL in C#? i want to ask about mapping Char(20) data type as Primary Key MySQL in C#?
I have some code in Models like :
public string StudentID { get; set; }

I have some code in DatabaseContext like :
builder
.Entity<Student>()
  .ToTable("Student")
    .HasKey(m => new
    {
      m.StudentID
    });

The data is like : ST-01-01-2017-001
Why in Swagger Response Body is no content and in Response Code is 500?
Thanks

A: try changing
.HasKey(m => new
{
  m.StudentID
});

to
.HasKey(m => m.StudentID);


text:
Q: Как отсортировать данные в List, чтобы строки с числами были по возрастанию? Есть список, в который мы грузим имена файлов из текущей директории
Пример файлов - 0.jpg,1.jpg,2.jpg и т.д. Как отсортировать список по возрастанию? Одно дело если бы там были цифры. А когда в list содержит строковые данные-они сортируются некорректно. 0.jpg,1.jpg и 10.jpg

List<string> list = new List<string>();
DirectoryInfo d = new DirectoryInfo(Directory.GetCurrentDirectory());
FileInfo[] Files = d.GetFiles("*.jpg"); //Getting Text files
string str = "";
foreach(FileInfo file in Files )
{
    list.Add(file.Name);

}

A: Можно попробовать так:
list.Sort((x, y) =>
    {
        int ix, iy;
        return int.TryParse(x, out ix) && int.TryParse(y, out iy)
              ? ix.CompareTo(iy) : string.Compare(x, y);
    });

Или так:
public class NaturalSortComparer<T> : IComparer<string>, IDisposable
{
    private bool isAscending;

    public NaturalSortComparer(bool inAscendingOrder = true)
    {
        this.isAscending = inAscendingOrder;
    }

    #region IComparer<string> Members

    public int Compare(string x, string y)
    {
        throw new NotImplementedException();
    }

    #endregion

    #region IComparer<string> Members

    int IComparer<string>.Compare(string x, string y)
    {
        if (x == y)
            return 0;

        string[] x1, y1;

        if (!table.TryGetValue(x, out x1))
        {
            x1 = Regex.Split(x.Replace(" ", ""), "([0-9]+)");
            table.Add(x, x1);
        }

        if (!table.TryGetValue(y, out y1))
        {
            y1 = Regex.Split(y.Replace(" ", ""), "([0-9]+)");
            table.Add(y, y1);
        }

        int returnVal;

        for (int i = 0; i < x1.Length && i < y1.Length; i++)
        {
            if (x1[i] != y1[i])
            {
                returnVal = PartCompare(x1[i], y1[i]);
                return isAscending ? returnVal : -returnVal;
            }
        }

        if (y1.Length > x1.Length)
        {
            returnVal = 1;
        }
        else if (x1.Length > y1.Length)
        {
            returnVal = -1;
        }
        else
        {
            returnVal = 0;
        }

        return isAscending ? returnVal : -returnVal;
    }

    private static int PartCompare(string left, string right)
    {
        int x, y;
        if (!int.TryParse(left, out x))
            return left.CompareTo(right);

        if (!int.TryParse(right, out y))
            return left.CompareTo(right);

        return x.CompareTo(y);
    }

    #endregion

    private Dictionary<string, string[]> table = new Dictionary<string, string[]>();

    public void Dispose()
    {
        table.Clear();
        table = null;
    }
}

Применение:
list.OrderBy(item => item, new NaturalSortComparer<string>()).ToList();

A: Насколько я понял из вашего описания, вас интересует "естественная" сортировка (natural sort), которая правильно отсортирует числа в строковом виде, например, "1, 2, 10, 20" вместо "1, 10, 2, 20". В Windows для этого есть встроенная функция StrCmpLogical. Чтобы воспользоваться ей для сортировки строк и файлов, вам понадобится реализовать интерфейс IComparer<T>.
[SuppressUnmanagedCodeSecurity]
internal static class NativeMethods
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    public static extern int StrCmpLogicalW(string psz1, string psz2);
}

public sealed class NaturalStringComparer : IComparer<string>
{
    public int Compare(string a, string b)
    {
        return NativeMethods.StrCmpLogicalW(a, b);
    }
}

public sealed class NaturalFileInfoNameComparer : IComparer<FileInfo>
{
    public int Compare(FileInfo a, FileInfo b)
    {
        return NativeMethods.StrCmpLogicalW(a.Name, b.Name);
    }
}

Ну а дальше эти компареры можно передавать в любую сортирующую функцию. Так как у вас массив, то можно так:
Array.Sort(Files, new NaturalFileInfoNameComparer());


text:
Q: Another expression for "bend over backwards" I am looking for another idiomatic expression for "bend over backwards" to help others.

A: "Give the shirt off his/her back" http://idioms.thefreedictionary.com/give+the+shirt+off+back

Fig. to give anything that is asked for, no matter the sacrifice
  required. Tom would give any of his old army buddies the shirt off his
  back. You can always count on Mark when you're in trouble; he'd give
  you the shirt off his back.

"Generous to a fault"
https://idioms.thefreedictionary.com/to+a+fault

Excessively, extremely, as in He was generous to a fault. This
  phrase, always qualifying an adjective, has been so used since the
  mid-1700s. Indeed, Oliver Goldsmith had this precise usage in The Life
  of Richard Nash (1762).


text:
Q: Which LiftResponse class is appropriate for returning an XML based file format? I have a Lift application which generates a Gephi file on the fly. The Gehpi native format is XML based. The current plan is that the file gets downloaded and opened in Gephi on the client, without being processed/displayed in the browser.
I looked through the LiftResponse subclasses and it seems that either StreamingResponse or PlainTextResponse are likely to work (I already made a simple prototype with StreamingResponse). While there is a specialized JsonResponse, I don't see an XML specific response.
What are the advantages and disadvantages of picking one class over the other? Which is the more appropriate to use? Or are they equally good in this case?

A: JsonResponse and PlainTextResponse are helpers that ultimately return an InMemoryResponse. You can see the source code here and here respectively. You will notice that PlainTextResponse sets a mimetype of "text/html" which is not necessarily correct for XML.
There is also an XmlResponse type that you can investigate here and which might be what you are looking for. It too returns an InMemoryResponse which as the name suggests, assumes your whole object is in memory before sending to the client.
A StreamingResponse is more suitable for larger files and objects where it takes a Stream and reads chunks of that stream into memory and sends them, repeating that process until it is finished - so you don't need to keep the whole structure in memory.
Both should work for you, just a question of the size of data you are dealing with and how you are working with it otherwise.


text:
Q: Value gets copied when entered manually, but not automatically on click Two fields input1 and input2 gives a total sum to input3 on click and it needs to be copied to the next input4 field, but it doesn't.
Although if you enter the value to input3 manually then it gets copied? (it actually doesn't get copied live until you click e.g. tab or click anywhere with the mouse, also don't know how to resolve)
Full code https://jsfiddle.net/tn6wr4xc/1/
So basically when you click the first Sum button it should copy the value to the input4, but it doesn't, only when entered manually.
Sorry for ghetto code, I know it's vanilla and jQuery, real beginner here.

A: You should use input event to make the immediate changes to output the result.
I will think of the solution in a different approach than yours.
First you can target all the inputs with class formA and formB using querySelectorAll(). Then loop through them to attach the event (input) using forEach() and addEventListener(). Inside the event handler function you can target only specific inputs related to the current element. You can find the sum of them using map() and reduce(). Finally store the sum in the relevant element.

var inputs = document.querySelectorAll('.formA, .formB');

Array.from(inputs).forEach(function(el){
  el.addEventListener('input', function(){
    var group = this.closest('div').querySelectorAll('[class^=form]');
    var sum = Array.from(group).map(i => Number(i.value)).reduce((a,c) => a+c,0);
    this.closest('div').querySelector('[name=total]').value = sum;
  });
});
<form id="forms">

Form A

    input1 : <input class="formA form-1" type="text" name="qty1"/>

    input2 : <input class="formA form-2" type="text" name="qty2"/>

    input3 (total) : <input class="total-1" type="text" name="total" id="total"/>

Form B

    input4 : <input class="formB form-3" type="text" name="qty3"/>

    input5 : <input class="formB form-4" type="text" name="qty4"/>

    input6 (total) : <input type="text" name="total" id="total2"/>

  <input type="reset" value="Reset">
</form>

A: I think you can't do it by that way because you update the value property by JavaScript which is not "by a user" so the event is not fired as desired.
But in order to achieve what you wanted, you can look through this link. They describe many ways to overcome the problem. And then one of the most common is to directly modify the input4 value after the you have modify the input3 one by this way

...
result.value = sum;
$('.form-3').val(sum);


text:
Q: Python: sum values of the third column if two columns have the same value I have the following dataframe df
df
    a   b   i
0   1.0 3.0 2.0
1   1.0 3.0 3.0
2   1.0 3.0 1.0
3   1.0 3.0 3.0
4   1.0 3.0 7.0
5   1.0 3.0 8.0
6   1.0 4.0 4.0
7   1.0 4.0 0.0
8   1.0 3.0 2.0
9   1.0 3.0 1.0
10  1.0 3.0 2.0

I want to make the sum over i for the same couple a and b, so
df2
    a   b   i
0   1.0 3.0 31.0
1   1.0 4.0 4.0
2   1.0 3.0 0.0

df2 = df2.groupby(['a', 'b']).sum(['i']).reset_index()

A: I think you need add column i to the end of groupby, then it is use for sum function:
df2 = df2.groupby(['a', 'b'])['i'].sum().reset_index()
print (df2)
     a    b     i
0  1.0  3.0  29.0
1  1.0  4.0   4.0

Or add parameter as_index=False for return df:
df2 = df2.groupby(['a', 'b'], as_index=False)['i'].sum()
print (df2)
     a    b     i
0  1.0  3.0  29.0
1  1.0  4.0   4.0

Another solution if necessary is use Series:
df2 = df2.i.groupby([df2.a,df2.b]).sum().reset_index()
print (df2)
     a    b     i
0  1.0  3.0  29.0
1  1.0  4.0   4.0

EDIT:
If need difference of groups by position in df use groupby by Series g with aggregate:
ab = df2[['a','b']]

#compare shifted values
print (ab.ne(ab.shift()))
        a      b
0    True   True
1   False  False
2   False  False
3   False  False
4   False  False
5   False  False
6   False   True
7   False  False
8   False   True
9   False  False
10  False  False

#check at least one True
print (ab.ne(ab.shift()).any(1))
0      True
1     False
2     False
3     False
4     False
5     False
6      True
7     False
8      True
9     False
10    False
dtype: bool

#use cumulative sum of boolean Series
g = ab.ne(ab.shift()).any(1).cumsum()
print (g)
0     1
1     1
2     1
3     1
4     1
5     1
6     2
7     2
8     3
9     3
10    3
dtype: int32

print (df2.groupby(g).agg(dict(a='first', b='first', i='sum')))
     a    b     i
1  1.0  3.0  24.0
2  1.0  4.0   4.0
3  1.0  3.0   5.0

A: you want to compare to see if the prior a, b combination has changed and do a cumsum to establish a grouping array
ab = df[['a', 'b']].apply(tuple, 1)

df.groupby(ab.ne(ab.shift()).cumsum()) \
  .agg(dict(a='last', b='last', i='sum')) \
  .reindex_axis(df.columns.tolist(), 1)

break it down

*

*ab = df[['a', 'b']].apply(tuple, 1)

*

*get me a series of tuples so I can see if the combination changed

*ab.ne(ab.shift())

*

*check if tuple is not the same as previous tuple

*ab.ne(ab.shift()).cumsum()

*

*if it isn't, then add the True value to the cumumlative sum.  This will create a handy grouping for each contigous set of identical pairs of a and b

*.agg(dict(a='last', b='last', i='sum'))

*

*just specifying what to do with each column in each group.  Get the last value for a and b, which is fine since I know its the same throughout the group.  Sum over column i

*.reindex_axis(df.columns.tolist(), 1)

*

*get my column order the way it was


text:
Q: How to Set ViewBag Properties for _Layout.cshtml I am trying to pass a ViewBag property to customize html in _Layout.cshtml.
@Styles.Render(ViewBag.IsEnglish ? "~/Content/css-en" : "~/Content/css-ur")

To do this, I have code in my base controller
public class BaseController : Controller
{
    protected virtual void OnAuthorization(AuthorizationContext filterContext)
    {
        ViewBag.IsEnglish = Request.RequestContext.RouteData.Values.ContainsKey("Culture") ?
            (Request.RequestContext.RouteData.Values["culture"].ToString().ToLower() == "en")
            : true;
    }
}

But my _Layout.cshtml gives error where ViewBag is called, before the controller's code setting that property is ever reached. I thought _Layout is executed by the ViewEngine, and ViewEngine runs after Controllers have run. Where should I place my ViewBag initialization code so that it becomes available to _Layout.cshtml?

A: In your base controller, try this:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);

    ViewBag.IsEnglish = requestContext.RouteData.Values.ContainsKey("Culture") ?
        (requestContext.RouteData.Values["culture"].ToString().ToLower() == "en") : true;

}

I assume you want to default to English. If that's not the case, change : true; to : false;
See also Controller.Initialize method on MSDN.

A: try using the Viewbag on your Action that returns the View that uses _Layout.cshtml


text:
Q: Error Creating Push Topic: 'Contract' is not supported Hi i am trying to create a Push Topic using workbench and i am getting the following error.
Error Creating Push Topic: 'Contract' is not supported
and my query is
SELECT CompanySignedDate FROM Contract
How to get contracts using push topic

A: The following subset of standard objects are supported in PushTopic queries: Account, Campaign, Case, Contact, Lead, Opportunity, Task.
Refer this link.
https://developer.salesforce.com/docs/atlas.en-us.196.0.api_streaming.meta/api_streaming/supported_soql.htm


text:
Q: Azure VPN cannot connect to sql server We have setup our VPN connection in Azure to our on-premises database, the connect is working with no problems.  I have written a MVC app that tries to connect to our on-premise database in SQL Server and am getting the following error:
System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
The connection string I am using is:
name="productdbConnectionString" connectionString="Data Source=172.16.x.xx,1433;Initial Catalog=productdb;User Id=poppy;Password=poppyxxxxx" providerName="System.Data.SqlClient"
I have opened TCP and named pipes and I am using port 1433 in the connection string so am a bit confused why I cannot access the database?
Thanks
Thanks


text:
Q: How to truncate text in Angular? I want to show smaller text. I see options like making custom pipe for truncating string but my case is different as follows.

In this I can't use a custom pipe. I'm doing this because I show text from backend & it comes with tags that's why [innerHtml] is used. Please help.

A: You can do with a custom function using TypeScript as,
truncateChar(text: string): string {
    let charlimit = 100;
    if(!text || text.length <= charlimit )
    {
        return text;
    }

  let without_html = text.replace(/<(?:.|\n)*?>/gm, '');
  let shortened = without_html.substring(0, charlimit) + "...";
  return shortened;
}

and in the HTML refer it as,

A: Avoid using a method call from HTML template as it will be called a lot of times, which would be unnecessary processing if the desired result is static or not modified very often.
Call the method truncateChar(in @Sajeetharan answer) from any of ngOnInit, ngOnChange or wherever you are updating the aboutUs variable and save the result in some variable in that component.
Use this variable in your template instead of calling the method directly.


text:
Q: Aurelia customAttribute multiple property passing I have created a custom attribute which is a wrapper for bootstrap tooltip
tooltip.ts
import {bindable, inject, customAttribute} from "aurelia-framework";
import * as $ from "jquery";

@customAttribute("tooltip")
@inject(Element)
export class Tooltip {
    element: HTMLElement;
    @bindable title: any;
    @bindable placement: any

    constructor(element) {
        this.element = element;
    }

    attached() {
        $('[data-toggle="tooltip"]').tooltip();
    }
}

header.html

So the question is how to I pass and bind data-placement and data-original-tile to title and placement in the Tooltip class. The current aurelia documentation doesn't say anything about multiple data binding for custom attributes.

A: You can pass multiple options to a custom attribute like this:

Please check the documentation for an explanation of how to implement the above. This information is just below the spot you linked to.
That being said your scenario might be better accomplished through a custom element. Then your markup could look like this:
<tooltip class="toggle-link" placement="bottom" original-title="Click to Search">

</tooltip>


text:
Q: Converting powerpoint presentations (ppt/x) to PDF without Interop I need to convert a PowerPoint (ppt/pptx) file to PDF using C#
Currently, I'm using this code:
public void PPTXToPDF(string originalPptPath, string pdfPath) {
    // Create COM Objects
    Microsoft.Office.Interop.PowerPoint.Application pptApplication = null;
    Microsoft.Office.Interop.PowerPoint.Presentation pptPresentation = null;
    try {
        object unknownType = Type.Missing;

        //start power point
        pptApplication = new Microsoft.Office.Interop.PowerPoint.Application();

        //open powerpoint document
        pptPresentation = pptApplication.Presentations.Open(originalPptPath,
            Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue,
            Microsoft.Office.Core.MsoTriState.msoFalse);

        // save PowerPoint as PDF
        pptPresentation.ExportAsFixedFormat(pdfPath,
            Microsoft.Office.Interop.PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF,
            Microsoft.Office.Interop.PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentPrint,
            MsoTriState.msoFalse, Microsoft.Office.Interop.PowerPoint.PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,
            Microsoft.Office.Interop.PowerPoint.PpPrintOutputType.ppPrintOutputSlides, MsoTriState.msoFalse, null,
            Microsoft.Office.Interop.PowerPoint.PpPrintRangeType.ppPrintAll, string.Empty, true, true, true,
            true, false, unknownType);
    } finally {
        // Close and release the Document object.
        if (pptPresentation != null) {
            pptPresentation.Close();
            pptPresentation = null;
        }

        // Quit PowerPoint and release the ApplicationClass object.
        if(pptApplication != null) {
            pptApplication.Quit();
            pptApplication = null;
        }
    }
}

This snippet uses the Interop libraries, which create an instance of the PowerPoint application and use it programmatically.
The problem is that the application randomly crashes.
Sometimes in the finally block, pptApplication comes null, which means that the application didn't even open, sometimes it says The message filter indicated that the application is busy, sometimes I see a dialog titled "Exporting..." with a progressbar showing the export progress, then the dialog disappears and the program hangs forever until I force-close it.
The application fails randomly with the same file: I run it once, it works, I run it again, it works, I run it again, it doesn't work, etc...
I cannot have an application that sometimes works and sometimes fails, so my question is: Is there a reliable alternative for converting PowerPoint files to PDF which doesn't use Interop? Did Microsoft provide an alternative API to do these things without opening an instance of PowerPoint?
The reason why I'm using Interop at the moment is that I also have to read the PowerPoint file and search for shapes in slides, if that matters.
UPDATE
The PC I'm running my application is a Windows 7 PC with Office installed. I cannot install anything else, that's why I need to find an independent library.

A: Only other way that comes to my mind is try using libreoffice for the same task. It has headless mode (no UI) and can be called from command line, like this:
"C:\Program Files (x86)\LibreOffice 5\program\soffice.exe" --headless --convert-to pdf:writer_pdf_Export test.pptx

Note that it will exit immeditaly (because it is designed for batched processing), but you can watch output directory using FileSystemWatcher and when desired file was created there (and when you are able to acquire exclusive lock on it) - it is done. You can also do batch processing with it, for more options available look here - https://help.libreoffice.org/Common/Starting_the_Software_With_Parameters. I used it for some conversions and had no problems doing that.

A: Using interop you can try to generate the pdf using this approach:
I have tested making fifty exports at one time and worked fine.
 _oPresentation.SaveAs(outputFullPath,

     PowerPoint.PpSaveAsFileType.ppSaveAsPDF,

     Microsoft.Office.Core.MsoTriState.msoCTrue);

Note: _oPresentation is just the interop presentation instance (Microsoft.Office.Interop.PowerPoint.Presentation).


text:
Q: what google registration id is I am using google registration id in Google cloud messaging for exemple, but I don't understand how this id is generated.
Id it link to the google play account or to the mobile ?
for exemple did two different mobiles using the same google play account will have the same registration id
If a user use two google play accounts, did the registration id will depend of the google play session ?
Thanks for your help

A: A GCM Registration id is unique to an android login & the device. If a user signs in to 2 devices using the same login, they will have different GCM Ids. Found the below from this link
An ID issued by the GCM servers to the Android application that allows it to receive messages. Once the Android application has the registration ID, it sends it to the 3rd-party application server, which uses it to identify each device that has registered to receive messages for a given Android application. In other words, a registration ID is tied to a particular Android application running on a particular device.


text:
Q: Changing xamarin android launcher theme that even applicable to preview window I use a style as theme for my splash activity that also is MainLauncher. This is my splash screen drawable:
<?xml version="1.0" encoding="utf-8" ?> <layer-list
xmlns:android="http://schemas.android.com/apk/res/android">   <item
android:id="@+id/itemSplashScreenBackgroundColor">
<shape android:shape="rectangle">
<solid android:color="@color/colorAppOrangeTheme" />
</shape>   </item>   <item>
<bitmap
android:src="@drawable/LogoSplashScreen"
android:tileMode="disabled"
android:gravity="center" />   </item> </layer-list>

And here is my style.xml file that uses mentioned drawable:
<resources>   <style name="styleAppSplashScreenTheme"
parent="android:Theme.DeviceDefault.NoActionBar">
<item name="android:scaleType">center</item>
<item name="android:windowBackground">@drawable/XMLFileSplashScreen</item>
<item name="android:windowDisablePreview">false</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowNoTitle">true</item>   </style> </resources>

As you see, to start my app quickly (user see app interaction quickly after tap app icon) I use value of windowDisablePreview as false.
Now I change background color of the splash screen by below coding in Activity OnCreate method:
LayerDrawable layerDrawable = (LayerDrawable)ContextCompat.GetDrawable(this, Resource.Drawable.XMLFileSplashScreen);
            GradientDrawable gradientDrawable = (GradientDrawable)layerDrawable.FindDrawableByLayerId(Resource.Id.itemSplashScreenBackgroundColor);

            if (stringAppThemeName == "Orange")
            {
                gradientDrawable.SetColor(ContextCompat.GetColor(this, Resource.Color.colorAppOrangeTheme));
            }
            else if (stringAppThemeName == "Blue")
            {
                gradientDrawable.SetColor(ContextCompat.GetColor(this, Resource.Color.colorAppBlueTheme));
            }
base.OnCreate(bundleSavedInstanceState);

The problem is here when I relaunch the app it first loads the style with its default color (@color/colorAppOrangeTheme) for a moment then changes to desired color!
Several solutions I saw like setting windowDisablePreview to true but I don't want to void of preview window, I want to change color of splash screen background color even in preview window.
Please suggest applicable solution. Thanks.


text:
Q: How to merge consecutive column values in Oracle into one and save initial order? I have the following table.

Table 1

+---------+-----------+
| col_key | col_value |
+---------+-----------+
| key1    | value1    |
| key1    | value2    |
| key1    | value3    |
| key1    | value2    |
| key1    | value2    |
| key1    | value2    |
| key1    | value1    |
| key1    | value1    |
| key1    | value3    |
| key1    | value3    |
| key1    | value3    |
| key1    | value2    |
+---------+-----------+

I want to get the following output:

Table 2

+---------+-------------------------------------------------------------------+
| col_key | col_value                                                         |
+---------+-------------------------------------------------------------------+
| key1    | value1 | value2 | value 3 | value 2 | value 1 | value 3 | value 2 |
+---------+-------------------------------------------------------------------+

Algorithm - if consecutive values same - merge them into one.
I am using Oracle and listagg function:

select
  col_key,
  listagg(distinct col_value, ' | ') within group (order by col_key) as col_value
from
  sample_table
group by col_key
order by col_key

But, listagg function with distinct keyword removes duplicates.
So, is it possible to make this in Oracle (like in table 2)?
Oracle versions (12c and 18c)

A: From Oracle 12, you can use MATCH_RECOGNIZE to perform row-by-row comparisons and aggregate the adjacent duplicates and then you can use LISTAGG to aggregate the unique values:
SELECT col_key,
       LISTAGG(value, ' | ') WITHIN GROUP (ORDER BY mno) AS col_value
FROM   (SELECT t.*,
               ROWNUM AS rn -- You need to provide a way of getting this order!
        FROM table1 t)
MATCH_RECOGNIZE(
  PARTITION BY col_key
  ORDER     BY rn
  MEASURES
    MATCH_NUMBER()   AS mno,
    FIRST(col_value) AS value
  PATTERN (same_value+)
  DEFINE
    same_value AS FIRST(col_value) = col_value
)
GROUP BY col_key;

Which, for the sample data:
CREATE TABLE Table1 (col_key, col_value) AS
SELECT 'key1', 'value1' FROM DUAL UNION ALL
SELECT 'key1', 'value2' FROM DUAL UNION ALL
SELECT 'key1', 'value3' FROM DUAL UNION ALL
SELECT 'key1', 'value2' FROM DUAL UNION ALL
SELECT 'key1', 'value2' FROM DUAL UNION ALL
SELECT 'key1', 'value2' FROM DUAL UNION ALL
SELECT 'key1', 'value1' FROM DUAL UNION ALL
SELECT 'key1', 'value1' FROM DUAL UNION ALL
SELECT 'key1', 'value3' FROM DUAL UNION ALL
SELECT 'key1', 'value3' FROM DUAL UNION ALL
SELECT 'key1', 'value3' FROM DUAL UNION ALL
SELECT 'key1', 'value2' FROM DUAL;

Outputs:

COL_KEY
COL_VALUE

key1
value1 | value2 | value3 | value2 | value1 | value3 | value2

db<>fiddle here

A: You said you'll edit the question and provide sorting column; so far, you didn't do that so I used ROWID instead. Change it with your own column (once you find out which one to use).
Read comments within code.
SQL> with
  2  temp as
  3    -- find COL_VALUE and the value that follows it (NEXT_VALUE in this query.
  4    -- As I already said, I used ROWID for sorting purposes)
  5    (select col_key,
  6       col_value,
  7       rowid rid,
  8       lead(col_value) over (partition by col_key order by rowid) next_value
  9     from sample_table
 10    ),
 11  temp2 as
 12    -- "new" COL_VALUE will be the "original" COL_VALUE if it is different from its
 13    -- next value (or - for the last row - if there's no next value)
 14    (select col_key,
 15       rid,
 16       case when col_value <> next_value or next_value is null then col_value
 17            else null
 18       end col_value
 19     from temp
 20    )
 21  -- finally, aggregate the result
 22  select col_key,
 23    listagg(col_value, ' | ') within group (order by rid) col_value
 24  from temp2
 25  group by col_key;

   COL_KEY COL_VALUE
---------- ------------------------------------------------------------
         1 val1 | val2 | val3 | val2 | val1 | val3 | val2

SQL>

A: Here's another take on it:
WITH
 cte1 AS (SELECT COL_KEY,
                 COL_VALUE,
                 LAG(COL_VALUE) OVER (ORDER BY ROWNUM) AS PREV_COL_VALUE
            FROM TEST_TAB),
 cte2 AS (SELECT COL_KEY,
                 COL_VALUE,
                 CASE
                   WHEN COL_VALUE = PREV_COL_VALUE THEN 0
                   ELSE 1
                 END AS FLAG
            FROM cte1),
 cte3 AS (SELECT COL_KEY,
                 COL_VALUE
            FROM cte2
            WHERE FLAG = 1)
SELECT COL_KEY,
       LISTAGG(COL_VALUE, ' | ') WITHIN GROUP (ORDER BY COL_KEY, ROWNUM) AS COL_VALUES
  FROM cte3
  GROUP BY COL_KEY

This produces:
COL_KEY  COL_VALUES
-------  ------------------------------------------------------------
key1     value1 | value2 | value3 | value2 | value1 | value3 | value2

which matches your desired output, but without an ordering column in your data you're at the mercy of the database and how it chooses to return the data. Remember - a basic rule of relational databases is that tables are unordered collections of rows, and there must an ORDER BY clause to impose an order on those rows when they are returned by a query.
db<>fiddle here


text:
Q: Android xmlparsing and putting data in listview I have two activity class of android. The main activity class contains xml parsing and i am trying to pass the data obtain from there to another activity class which is going to put it into listview of all the data. Below the is xml parsing main activity the problem is that, when I run the program it show nullpointer exception . I m stuck here can anyone help me where is the error . Thnx in advance
enter code here

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.main);

    try {
        stringXmlContent = getEventsFromAnXML(this);
        Intent i=new Intent(LocationSidActivity.this,FacebookData.class);
        i.putStringArrayListExtra("language", stringXmlContent);
        startActivity(i);
        // myXmlContent.setText(stringXmlContent);
    } catch (XmlPullParserException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

private ArrayList<String> getEventsFromAnXML(Activity activity)
        throws XmlPullParserException, IOException {
    ArrayList<String> al = new ArrayList<String>();
    Resources res = activity.getResources();
    XmlResourceParser xpp = res.getXml(R.xml.myxml);
    xpp.next();
    int eventType = xpp.getEventType();

    while (eventType != XmlPullParser.END_DOCUMENT) {
        if (eventType == XmlPullParser.START_DOCUMENT) {
            al.add(xpp.getName());
        } else if (eventType == XmlPullParser.START_TAG) {
            //if ((xpp.getName()).compareTo("id") != 0) {
                al.add(xpp.getName());
            //} else {
                //eventType = xpp.next();

        }

        else if (eventType == XmlPullParser.TEXT) {

            al.add(xpp.getText());
        }
        eventType = xpp.next();
    }
    return al;

}

}

A: The lines in your parser method getEventsFromAnXML:
if (eventType == XmlPullParser.START_DOCUMENT)
{
    al.add(xpp.getName());
}

may end up in a NullPointerException, because there is nothing read yet, and a null value will be added as the first member of your ArrayList.
The XmlPullParser.START_DOCUMENT in API Docs:

Signalize that parser is at the very beginning of the document and
  nothing was read yet. This event type can only be observed by calling
  getEvent() before the first call to next(), nextToken, or nextTag()).

Also, if the getEventsFromAnXML method is in your Activity class, you should remove the parameter, and simply use this. It is never a good practice to share a Context, it will most often end up in leaks.


text:
Q: Splitting python class into multiple files I wondered if anyone could tell me is it possible to divide the following code into two python classes which will then be placed in two different files:
from GUI import mainGUI
from GUI import subwindowGUI

class MyApp(QMainWindow, mainGUI.Ui_MainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setupUi(self)

        # mainGUI contains QMdiarea in which it opens
        # a subwindow by calling a function MySubWin(self)

        # QMdiarea name is 'body'

        self.OpenSub.triggered.connect(self.MySubWin)

    def MySubWin(self):
        self.MySubWin = QWidget()
        self.MySubWin.setObjectName('Module window')

        self.myTabs = QtabWidget(self.MySubWin)
        self.myTabs.setObjectName('myTabs')

        # now I call the function that will display
        # the gui elements inside this 'Module window'
        self.create_module_gui()

        self.body.addSubWindow(self.MySubWin)
        self.MySubWin.showNormal()

    def create_module_gui(self, *args):
        module_gui = subwindowGUI.Ui_ModuleWindow()
        module_gui.setupUi(module_gui)

        self.myTabs.addTab(module_gui, _('New tab'))
        self.myTabs.setCurrentWidget(module_gui)

As you can see from the code above my functions are interacting with the main window gui elements. I wanted to move these functions that are related to this specific module into a separate file for the maintaining purposes. That's why I'm asking you to help me on how to achieve that if it's even possible. Thanks in advance, Tomislav.
@Mel:
If I for move those functions into another file:
myFunctions.py

class MyFunctions(object):

    def MySubWin(self):
        self.MySubWin = QWidget()
        self.MySubWin.setObjectName('Module window')

        self.myTabs = QtabWidget(self.MySubWin)
        self.myTabs.setObjectName('myTabs')

        # now I call the function that will display
        # the gui elements inside this 'Module window'
        self.create_module_gui()

        self.body.addSubWindow(self.MySubWin)
        self.MySubWin.showNormal()

    def create_module_gui(self, *args):
        module_gui = subwindowGUI.Ui_ModuleWindow()
        module_gui.setupUi(module_gui)

        self.myTabs.addTab(module_gui, _('New tab'))
        self.myTabs.setCurrentWidget(module_gui)

and then I import that file into my main file.
import myFunctions

class MyApp(QMainWindow, mainGUI.Ui_MainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setupUi(self)

        # mainGUI contains QMdiarea in which it opens
        # a subwindow by calling a function MySubWin(self)

        # QMdiarea name is 'body'

        self.OpenSub.triggered.connect(MyFunctions.MySubWin)

What I end up with is the error saying that MyFunctions object has no attribute body.

A: 1st I must say that you won't gain any maintenance out of this ... but for example lets move the create_module_gui to another class
in a new file: creategui.py
class CreateGUI(object):

    def create_module_gui(self, *args):
        module_gui = subwindowGUI.Ui_ModuleWindow()
        module_gui.setupUi(module_gui)

        self.myTabs.addTab(module_gui, _('New tab'))
        self.myTabs.setCurrentWidget(module_gui)

in your code:
from GUI import mainGUI
from GUI import subwindowGUI
from creategui import CreateGUI

class MyApp(QMainWindow, mainGUI.Ui_MainWindow, CreateGUI):
     #yay you have your create_module_gui method now...

Now you can also just put create_module_gui  as a function in another file and call it with self as the first param...

A: See this solution: https://stackoverflow.com/a/47562412/10155767
In your case, don't make a class in myFunctions.py. Instead, define the functions at the top level. Thus myFunctions.py should look like:
def MySubWin(self):
    ...

def create_module_gui(self, *args):
    ...

Then in your original file, import the functions within the class like
class MyApp(QMainWindow, mainGUI.Ui_MainWindow):
    from myFunctions import MySubWin, create_module_gui

    def __init__(self, parent=None):
        ...


text:
Q: How can I print all the characters until a certain pattern (excluding the pattern itself) using grep/awk/sed? For example
echo "abc-1234a :" | grep <do-something>

to print only abc-1234a

A: I think these are closer to what you're getting at, but without knowing what you're really trying to achieve, it's hard to say.
echo "abc-1234a :" | egrep -o '^[^:]+'

... though this will also match lines that have no colon.  If you only want lines with colons, and you must use only grep, this might work:
echo "abc-1234a :" | grep : | egrep -o '^[^:]+'

Of course, this only makes sense if your echo "abc-1234a :" is an example that would be replace with possibly multiple lines of input.
The smallest tool you could use is probably cut:
echo "abc-1234a :" | cut -d: -f1

And sed is always available...
echo "abc-1234a :" | sed 's/ *:.*//'

For this last one, if you only want to print lines that include a colon, change it to:
echo "abc-1234a :" | sed -ne 's/ *:.*//p'

Heck, you could even do this in pure bash:
while read line; do
  field="${line%%:*}"
  # do stuff with $field
done <<<"abc-1234a :"

For information on the %% bit, you can man bash and search for "Parameter Expansion".
UPDATE:
You said:

It's the characters in the first line of input before the colon. The
  input could have multiple line though.

The solutions with grep probably aren't your best choice, then, since they'll also print data from subsequent lines that might include colons.  Of course, there are many ways to solve this requirement as well.  We'll start with sample input:
$ function sample { printf "abc-1234a:foo\nbar baz:\nNarf\n"; }
$ sample
abc-1234a:foo
bar baz:
Narf

You could use multiple pipes, for example:
$ sample | head -1 | grep -Eo '^[^:]*'
abc-1234a
$ sample | head -1 | cut -d: -f1
abc-1234a

Or you could use sed to process only the first line:
$ sample | sed -ne '1s/:.*//p'
abc-1234a

Or tell sed to exit after printing the first line (which is faster than reading the whole file):
$ sample | sed 's/:.*//;q'
abc-1234a

Or do the same thing but only show output if a colon was found (for safety):
$ sample | sed -ne 's/:.*//p;q'
abc-1234a

Or have awk do the same thing (as the last 3 examples, respectively):
$ sample | awk '{sub(/:.*/,"")} NR==1'
abc-1234a
$ sample | awk 'NR>1{nextfile} {sub(/:.*/,"")} 1'
abc-1234a
$ sample | awk 'NR>1{nextfile} sub(/:.*/,"")'
abc-1234a

Or in bash, with no pipes at all:
$ read line < <(sample)
$ printf '%s\n' "${line%%:*}"
abc-1234a

A: It is possible to do what you want with only sed.
Here is an example:
#!/bin/sh
filename=$1
pattern=yourpattern

# flag -n disables print everyline (default behavior)
sed -n "
  1,/$pattern/ {
    /$pattern/n # skip line containing pattern
    p           # print lines ranging from line 1 untill pattern
  }
" $filename

exit 0

This works at least for GNU's sed. It should work for other sed too, except
regarding the comments (some implementations of sed don't support comments).
Source: https://www.grymoire.com/Unix/Sed.html


text:
Q: Generalizations of Chen's theorem The two famous theorems of Jingrun Chen, both with similar proofs, state (respectively) that all sufficiently large even numbers are the sum of a prime and an element of $P_2$, and that there are infinitely many numbers $n$ such that $\{n, n+2\}$ consists of a prime and an element of $P_2$. Here $P_2$ is the set of numbers with at most two (not necessarily distinct) prime factors.
His latter theorem can be restated as the polynomial $f(n) = n(n+2)$ hits $P_3$ infinitely often. Note in particular that $3 = \deg(f) + 1$, which seems to be the best possible result of this type (any smaller and we run into the infamous parity problem in sieve theory).
Has Chen's theorem been generalized to higher degree polynomials? In particular, let $\mathcal{H}$ be an admissible set in the sense defined in Goldston-Pintz-Yildirim, that for all primes $p$, $\mathcal{H}$ does not contain a complete residue system modulo $p$. Let $|\mathcal{H}| = k$ and let $f(n) = \prod_{h \in \mathcal{H}} (n + h)$. Then can one prove that $f(n)$ hits $P_{k+1}$ infinitely often?
Note: the recent series of results regarding bounded gaps between primes essentially boils down to showing that for any admissible set $\mathcal{H}$, we have $f(n)$ hits $P_{k+l}$ infinitely often for some small positive $l$ (say $l \leq\sqrt{k}$). My question is are there any specific cases where we can take $l = 1$.

A: This has not been proven unconditionally (or conditionally on the Elliot-Halberstam conjecture).
Consider the case $k=3$. If the product of an admissible $3$-tuple had at most $4$ prime factors infinitely often, this would imply that the 3-tuple contains $2$ primes infinity often. In turn, this would imply that there are prime gaps of at most size at most $6$ infinity often.
The current records are a ways away from this.
[Also a correction to your question:  one needs $l < k$ to get bounded gaps, some positive $l$ is not sufficient.]


text:
Q: Template view property points to parent view I have a container view into which i insert components dynamically.
When trying to access properties in that components template i've discovered that the template context is not the component but the container view, for some reason. Meaning that "view" property in template is not pointing to the component but to the container view above it.
Can't find any documentation that indicates that this is supposed to happen, so any ideas as to why this is happening?

A: So, i got this to work.
What i did was override the _yield method in the component:
_yield: function () {
    return Ember.View.prototype._yield.apply(this, arguments);
}

Not sure why this is needed so if someone can enlighten me, please do so


text:
Q: In iptables, what is the difference between targets DNAT and REDIRECT? More specifically, is
-A PREROUTING -i $INT -p $PROTO --dport $PORT -j REDIRECT --to-ports $NEWPORT

equivalent to one or both of these?
-A PREROUTING -i $INT -p $PROTO --dport $PORT -j DNAT --to-destination :$NEWPORT
-A PREROUTING -i $INT -p $PROTO --dport $PORT -j DNAT --to-destination $IP_OF_INT:$NEWPORT

A: According to netfilter documentation, redirection is a specialized case of destination NAT. REDIRECT is equivalent to doing DNAT to the incoming interface.
Linux 2.4 NAT HOWTO -- Destination NAT
So it means the first and second strings are equivalent.
-A PREROUTING -i $INT -p $PROTO --dport $PORT -j REDIRECT --to-ports $NEWPORT
-A PREROUTING -i $INT -p $PROTO --dport $PORT -j DNAT --to-destination :$NEWPORT

The string:
-A PREROUTING -i $INT -p $PROTO --dport $PORT -j DNAT --to-destination $IP_OF_INT:$NEWPORT

does the same job only if $IP_OF_INT - is the IP address on the incoming interface (IP of $INT).


text:
Q: jQuery get json values I'm trying to fetch the last 3 blog posts with the draft = false for my system via jQuery json and following some tutorials if found online but without luck, and with the following keys:
"slug"
"updated"
"title"
"content"
"draft = false"
Here is the json output
{
  "posts":[
      {
         "Blog":{
            "id":"1252",
            "client_id":"1432",
            "slug":"my-blog-slug",
            "last_updated_by":"614",
            "draft":false,
            "created":"2014-09-17 11:18:39",
            "updated":"2014-09-17 11:18:39",
            "locale":"isl",
            "title":"This is the blog title",
            "content":"
My excellent content.<\/p>",
            "author":"John Doe"
         },
         "UpdatedBy":{
            "id":"614",
            "name":"John Doe"
         }
      }
   ]
}

My current script is below, but i'm pretty sure that i'm doing a lot of things wrong.

Any help would be so much appreciated.

A: try this way:
JS

$(document).ready(function() {
    $.ajax({
        url: "blogs.json",
        dataType: "json",
        success: function(data) {
            var json = $.parseJSON(data);
            $.each(json.posts, function(){
                $('#results').html('Title: ' + this.Blog.title + '
Description: ' + this.Blog.content);
            });
        }
    });
});

Demo

A: Try this : posts is first key in json object and there could be multiple so access it using index, here it is zero. after getting posts, access each element by its key.
 var blog = json.posts[0]["Blog"];

 $('#results').html('Title: ' + blog["created"] + '
Description: ' + blog["content"]);

EDIT - as per OP comment, adding below code
$(document).ready( function() {
 $.parseJSON("/blogs.json", function(data){
    var json = $.parseJSON(data);
    var blog = json.posts[0]["Blog"];
    $.each(blog, function(){
      $("div#posts").append("
Title: "+blog['title']+"

Content: "+blog['content']+"

");
    });
 });

Demo


text:
Q: LINQ Where Exists GROUP BY How can i convert this in LINQ?
SELECT B.SENDER, B.SENDNUMBER, B.SMSTIME, B.SMSTEXT
FROM MESSAGES B
WHERE EXISTS ( SELECT A.SENDER
        FROM MESSAGES A
    WHERE A.SENDER = B.SENDER
    GROUP BY A.SENDER
    HAVING B.SMSTIME = MAX( A.SMSTIME))
GROUP BY B.SENDER, B.SENDNUMBER, B.SMSTIME, B.SMSTEXT ;

Thanks a lot :)
EDIT!!
Resolved with:
  var Condition = "order by SMSTime desc";

  IEnumerable<ClassMessaggio> messaggi = Database.Select<ClassMessaggio>(Condition);; // Load all but sorted

  ElencoConversazioni =  messaggi.GroupBy(m => new { m.Number })
                .Select(g => g.OrderByDescending(m => m.SMSTime).First()).ToObservableCollection();

A: Try
db.Messages.Where(b => b.SmsTime == Messages.Where(a => a.Sender == b.Sender)
                                            .Max(a => a.SmsTime))

Or
db.Messsages.GroupBy(m => new { m.Sender, m.SendNumber })
            .Select(g => g.OrderByDescending(m => m.SmsTime).First())

Where db is your DataContext.

A: To show the list of conversations along with "the last message of every contact", you could try something like:
// a query to find the last Sms time per sender
var lastSmsQuery = from m in db.messages
                 group m by m.Sender into grouping
                 select new
                 {
                     Sender = grouping.Key,
                     LastSmsTime = grouping.Max(x => x.SmsTime)
                 };

// a query to find the messages linked to the last Sms per sender
var lastMessageQuery = from m in db.messages
                       join l in lastSmsQuery on new { m.Sender, m.SmsTime } equals new { l.Sender, l.LastSmsTime }
                       select m;

The 2-query method used is similar to that of this question from earlier today - Convert SQL Sub Query to In to Linq Lambda


text:
Q: Plotting square function with ggplot2 geom_line? How can I use ggplot2's geom_line to plot a square function, where x,y coordinates are connected by squares rather than by lines?
Something that looks like:

Is this possible?

A: For this you can use geom_step:
df = data.frame(x = 1:10,
                y = sample(c(1,2), 10, replace = TRUE))
ggplot(df, aes(x = x, y = y)) + geom_step()


text:
Q: Tensor Rank for derivatives and integrals How can I go about determining the rank of a tensor if I am taking a derivative or an integral?
For example, I have a 2nd order Tensor, $A_{ij}$ and I take the derivative with respect to $x_i$ or $x_j$, how does this affect the rank? $(dA_{ij}/dx_i)$
What about if I were to take an integral in the same fashion? ($\int(A_{ijk} dx_i)$)
I keep seeing something about covariant differentiation of tensors but as this is my first time dealing with tensors, I am not sure how to go about this.
Any help would be greatly appreciated


text:
Q: Azure Scheduler Certification error I'm using new Azure Scheduler service and I have this issue.
I have one console application that works fine with this few code lines
var credentials = new CertificateCloudCredentials(subscriptionId, certificate);
var schedulerClient= new SchedulerManagementClient(credentials);
var jobCollAvailable = schedulerClient.JobCollections.CheckNameAvailability(cloudServiceName, jobCollectionName_NE);

I use the same code lines in a API service with service stack.
When CheckNameAvailability method is called system throws this exception :
Forbidden Error: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.

*

*Since Friday everything worked also into the service. I had only changed the certificate with another one.

*If I remove certificate from Azure the console app throws the same error( but in this case is correct). I have tried with more than one certificate for to be sure and console app has worked fine.

*The Certificate loaded and used from Service has the same thumbprint that the console app one.

Thanks for your suggests


text:
Q: Codeigniter not able to connect to firebird I have seen and tried all the solutions in Codeigniter - multiple database connections, You have specified an invalid database connection group codeigniter error, firebird - codeigniter connection and none of them worked.
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'testing';
$db['default']['dbdriver'] = 'mysqli';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

$db['fbird']['hostname'] = "localhost";
$db['fbird']['username'] = "SYSDBA";
$db['fbird']['password'] = "masterkey";
$db['fbird']['database'] = "C:\waitkyl.fdb";
$db['fbird']['dbdriver'] = "firebird";

After this configuration, I call the fbird database this way:
class Fb_model extends CI_Model{

    public function __construct(){
        parent::__construct();
    }

    public function getAll(){
        $db = $this->load->database('fbird', TRUE);

        return $db->get('categories')->result();
    }
}

And the error I get after trying output the values print_r($this->fb_model->getAll()); is:

Fatal error: Call to a member function result() on a non-object

That usually means that the table 'categories' doesn't exists..which isn't true.
So I have tried to change my configuration file into:
$db['fbird']['hostname'] = "localhost";
$db['fbird']['username'] = "SYSDBA";
$db['fbird']['password'] = "masterkey";
$db['fbird']['database'] = "C:\waitkyl.fdb";
$db['fbird']['dbdriver'] = "firebird";
$db['fbird']['dbprefix'] = "";
$db['fbird']['pconnect'] = FALSE;
$db['fbird']['db_debug'] = TRUE;
$db['fbird']['cache_on'] = FALSE;
$db['fbird']['cachedir'] = "";
$db['fbird']['char_set'] = "utf8";
$db['fbird']['dbcollat'] = "utf8_general_ci";

And also removed from the php.ini file the ; from the following lines:
extension=php_pdo_firebird.dll
extension=php_interbase.dll

And if I refresh the page now the error I receive is:

Unable to connect to your database server using the provided settings.
Filename: C:\xampp\htdocs\projtesting\system\database\DB_driver.php
Line Number: 124

In order to see if the credentials from the database were fine I opened it on the software SQL Manager 2008 Lite for Interbase and Firebird, and it was ok.
Any ideas of what's going wrong?

A: Solution: Codeigniter 3 (dbdriver = ibase)
$db['firebird'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'sysdba',
    'password' => 'masterkey',
    'database' => 'c:/database.GDB',
    'dbdriver' => 'ibase',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'ANSI',
    'dbcollat' => 'NONE',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);


text:
Q: Fade out div on scroll I am fading out the div #hero-image when my page scrolls. At the moment, the code below uses a nominal value of 1000 to ensure a slow fade, but my #hero-image div is 100% the height of the browser, so I'd like the full opacity transition from 1 to 0 to happen when the user scrolls the 100% height div out of the initial viewport.
Any help much appreciated!
/* Fade #hero-image on scroll */
$(document).ready(function(){
    $(window).scroll(function(){
        $("#hero-image").css("opacity", 1 - $(window).scrollTop() / 1000);
    });
});

A: Use the height of the element instead of the generic 1000 value.
Fiddle: http://jsfiddle.net/e84enbf2/
$(document).ready(function(){
    $(window).scroll(function(){
        $("#hero-image").css("opacity", 1 - $(window).scrollTop() / $('#hero-image').height());
    });
});

If I understand your comment correctly to make the fade out complete after scrolling half the height of the div just divide by 2.
Fiddle: http://jsfiddle.net/e84enbf2/1/
$(document).ready(function(){
    $(window).scroll(function(){
        $("#hero-image").css("opacity", 1 - $(window).scrollTop() / ($('#hero-image').height() / 2));
    });
});


text:
Q: Data validation on a comma separated entry? I have a sheet that lists out Job Expenses like this:
COL A            COL B
CB100            $100
CB101            $200
CB100, CB101     $50

A few columns over, in COL D, is a running list of each JOB#:
COL D
CB101
CB102
CB103 etc.

I'm trying to use Data Validation to ensure any JOB# inputted into COL A already exists in COL D. Doesn't seem this can be done with List format of validation criteria. Any way to do it via custom formula?

A: Use this custom Formula
=SUMPRODUCT(--ISNUMBER(MATCH(TRIM(MID(SUBSTITUTE(A1,",",REPT(" ",99)),(ROW($1:$10)-1)*99+1,99)),D:D,0)))>=LEN(A1)-LEN(SUBSTITUTE(A1,",",""))+1

Note the data validation is applied to the whole column A.  As you can see it was allowed to enter the first two but the last one was not as it is not in the list.
As is it will only test the first 10 number in a comma delimited field.


text:
Q: Can Blogger API retrieve metrics such as pageviews? Is there a way to get blogger blog metrics such as pageviews via the Blogger API? I've searched through the API docs, and it seems very limited.

A: Here it is :)
Seems they developed it lately.
https://developers.google.com/blogger/docs/3.0/reference/pageViews/get


text:
Q: Springboot: Callback URL not approved for this client application. Approved callback URLs can be adjusted in your application settings? I created an app in twitter and trying to do basic authentication but I am getting the below error so can anyone help me with this? How to resolve the error?
Callback URL not approved for this client application. Approved callback URLs can be adjusted in your application settings

A:
If you do receive this error message, please check the URL that you are using with the callback_url parameter in your oauth/request_token call and make sure that this URL has been whitelisted in your Twitter app settings in the developer portal.

Here is a description on how to solve your issue:
https://developer.twitter.com/en/docs/basics/developer-portal/guides/callback-urls.html

A: I've been struggling with callback_url and Spring Social for some time.
Add following url to Twitter whitelisted. For localhost use:
https://localhost/auth/twitter
for deployed app:
https://example.com/auth/twitter
or
https://IP.ADR.ESS/auth/twitter
First make sure it works on localhost, meaning your machine.
If it works on localhost but fails afted deploy on specific IP, the problem is most probably with your server IP. Spring Social Twitter creats this urlcallback based on some host parameters. If you deploy on a machine that is behind a proxy, a real callack url may be different than IP addres the app is running on. That was my case. I had two VPS from different vendors. Same config worked on first, failed on second.


text:
Q: Why is my Win10 VirtualBox machine so slow? I'm running a Windows 10 guest in VirtualBox, and I'm having a hard time understanding why it's so incredibly slow to run. I'm allocating 2 virtual cores to it, 4 gigabytes of my RAM (in a 16 gig host), and provided a 50 gigabyte fixed size virtual disk image file running on a 3,500 MB/s Samsung 500 gigabyte SSD. Yet it takes a huge amount of time to boot, and sometimes it doesn't boot at all, and just freezes (at least I don't wait around for a long time). The mouse is also really unresponsive to the machine. I just don't know what else I have to take into consideration here

A: Generally, all operating system installed on virtualbox or on VMware runs slow as compared to the host machine speed. But if you are still facing this issue then check how much RAM is allocated, if host system has 8GB RAM then I would suggest you to only allocate 2-3 GB for Virtual machine. But if RAM is not the issue then update your Virtualbox application because 2GB is also enough for running Windows 10 on Virtualbox.


text:
Q: How can I speed up Spring's form:options tag? I'm using Spring 5.0.6.RELEASE.  I'm trying to render SELECT menus for country and state on my page, so I have
<form:select path="countries[${vs.index}]" cssClass="country">
    <form:option value="" label="Select Country" />
    <form:options items="${countryList}" itemValue="id" itemLabel="name" />
</form:select>

<form:select path="states[${vs.index}]" cssClass="state">
    <form:option value="" label="Select State" />
    <form:options items="${stateList[vs.index]}" itemValue="id" itemLabel="name" />
</form:select>

There are about 239 country options and 50 state options, but yet the above two functions take about 11 seconds to render.  This is ridiculously slow, especially considering that data never changes.  Is there a way to speed this up or somehow get my application to cache these fragments?  I'm using Wildfly 11.0.0.Final and Java 8.

A: Maybe it isn't what you are looking for, but why go to server for static list of countries (/states)?
You can easily write or use components for displaying such drop down in Javascript vanila or framework that will reduce network latency and also load.
Sending those list over network for every client every page loading seems awfully redundant and expansive.


text:
Q: Obtener información de un HTTP response para manejarla con ajax | Sección de comentarios con Django Estoy haciendo una aplicación web con django, en donde tengo una sección de comentarios. Estoy intentado:

*

*Que al publicar el comentario se haga un POST request al view de esa página

*Crear un nuevo comentario con mi modelo de comentarios y guardarlo

*Pre renderizar una página html que solo contiene los comentarios

*Mandar un http response que contenga el html de los comentarios

*Del lado del cliente, con javascript remplazar la sección de comentarios con el nuevo html que obtengo (los comentarios actualizados)

Todo esto con el motivo de que la página no haga refresh, cada vez que hago un comentario.
(Explico el error al final)
Esto es lo que llevo hasta el momento
En mi views.py esta es la vista que renderiza mi pagina que tiene una sección de comentarios.
No estoy devolviendo el renderizado de los comentarios todavía. Porque estoy teniendo problemas que explicaré más adelante.
def make_bid(request, pk):
    listing = Listing.objects.get(id = pk)
    comments = listing.comments.all()
    if request.method == "POST":
        if request.user.is_authenticated:
            comment = Comment(
                user = request.user,
                comment= request.POST['comment'],
                date = datetime.datetime.now().date(),
                listing = listing)
            comment.save()
            context = {'comments': listing.comments.all()}
            rendered = render_to_string("auctions/comments.html", context)
            return HttpResponse("object")
        else:
            return HttpResponse("user is not even authenticated")
    else:
        return render(request, "auctions/make-bid.html", {
            'article' : listing,
            'comments': comments
        })

La sección de comentarios de la página con html

Comments

        <form action="{% url 'make-bid' article.id %}" method="post" id="form-comment">
            {% csrf_token%}
            <textarea id="textbox" class="field form__field--block" value="" name="comment" placeholder="What do you think about this listing?"></textarea>
            <input class="button button__primary" type="submit" value="Publish">
        </form>

Ajax para mandar el POST request y recibir el http response
Esto lo copié de otra página de stackoverflow. Preferiría hacerlo sin jquery, lo intenté con javascript y no obtenía el resultado esperado. Así que para asegurarme lo hice con jquery y de igual forma no obtengo el resultado que quiero
    $("#from-comment").submit(function(e) {

    e.preventDefault(); // avoid to execute the actual submit of the form.

    var form = $(this);
    var url = form.attr('action');

    $.ajax({
        type: "POST",
        url: url,
        data: form.serialize(), // serializes the form's elements.
        success: function(data)
        {
            alert(data); // show response from the php script.
            console.log('Submission was successful.');
            console.log(data);
        },
        error: function(data){
            console.log("no response")
        }
        });

    });

Así se ve la sección de comentarios de mi página

Ahora aquí viene el problema
Al enviar el comentario el http response me devuelve el mensaje como html en toda la pantalla. Yo quiero obtener ese mensaje y hacer algo con él con javascript. No quiero que se vea
Ya se que pueden haber otras cositas mal en el código pero por ahora lo que necesito es que el http response no haga esto:

Ya he intentado mandar un JsonResponse y es lo mismo. Me devuelve lo que escribir en HttpResponse("el json pero bien hecho") como un texto en toda la página

A: Ya lo resolvi! El problema era yo. Hice unos errores muy bobos en el javascript
Aqui esta el jquery. No me di cuenta que jquery no estaba cargando y tenía un typo

Asi quedo el views.py
def make_bid(request, pk):
    listing = Listing.objects.get(id = pk)
    context = {'comments': listing.comments.all()}
    rendered = render_to_string("auctions/comments.html", context)
    if request.method == "POST":
        if request.user.is_authenticated:
            comment = Comment(
                user = request.user,
                comment= request.POST['comment'],
                date = datetime.datetime.now().date(),
                listing = listing)
            comment.save()
            context = {'comments': listing.comments.all()}
            rendered = render_to_string("auctions/comments.html", context)
            return HttpResponse(rendered)
        else:
            return HttpResponse("user is not even authenticated")
    else:
        return render(request, "auctions/make-bid.html", {
            'article' : listing,
            'comments': rendered
        })

Y así modifique el HTML de la sección de comentarios

Comments

        <form method="post" id="form-comment">
            {% csrf_token%}
            <textarea id="textbox" class="field form__field--block" value="" name="comment" placeholder="What do you think about this listing?"></textarea>
            <input class="button button__primary" type="submit" value="Publish">
        </form>

            {{comments}}


text:
Q: Open a URL in browser as a post build step in Jenkins I am planning to open a URL in browser as a post build step in Jenkins. I tried using Pipeline Jenkins and included the code below:
node {
    stage ("execute"){
        bat 'start www.google.com'
    }
}

I'm getting output as:
Started by user anonymous
[Pipeline] node
Running on master in C:\Program Files (x86)\Jenkins\workspace\free
[Pipeline] {
[Pipeline] stage
[Pipeline] { (execute)
[Pipeline] bat
[free] Running batch script

C:\Program Files (x86)\Jenkins\workspace\free>start www.google.com
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

But the URL specified is not getting opened in browser. When I run the same command start www.google.com in command prompt, it is opening the Google site in default browser. How to solve this?


text:
Q: Отображение img и работа src в js На клиенте в браузере выводятся изображения фотографий небольших размеров, например, 20 штук в формате :

 стили :
.my_img img{width: 10%; height: 10%;}

По клику, на приведенный выше блок, сделал отображение соответствующей ему фотки в блоке больших размеров, например, сюда :

стили :
#my_i img{width: 100%; height: 100%;}

Делал двумя способами :
 (кратко)

 1.
 document.getElementById('my_i').innerHTML = document.getElementsByClassName('my_img')[...].innerHTML;

 2.
 var img2 = document.createElement('img');
 img2.src = '/img_02.JPG';
 img2.alt = '';
 document.getElementById('my_i').removeChild(document.getElementById('my_i').childNodes[0]);
 document.getElementById('my_i').appendChild(img2);

У меня два вопроса :
правильно ли я понял, что если была загрузка фоток по src=..., в моём случае с отображением в малых размерах, то дальнейшие манипуляции с таким src будут происходить всегда без запросов. Я смотрел в хроме в network и думаю, что да, - идет работа с кэшем, но не нашел по этому поводу ничего в публикациях по теме. Например, так работает во всех браузерах, мобилках ? Второе, как правильно делать : через innerHTML или HTMLImageElement ? Спасибо.


text:
Q: ElasticSearch transformation, scripted_metric without nested fieldnames I created a ElasticSearch transformation like this:
"source": {
    "index": "input_index"
  },
  "dest" : {
    "index" : "output_index"
  },
  "pivot": {
    "group_by": {
      "device_id": { "terms": { "field": "device_id.keyword" }}
    },
    "aggregations": {
      "@timestamp": {
        "max": {
          "field": "@timestamp"
        }
      },
      "latest_doc": {
        "scripted_metric": {
           "init_script": ...,
           "map_script": ... }",
           "combine_script": "return state",
           "reduce_script": .... return last_doc   (last_doc contains document from input_index)
        }
      }
    }
  }

This works great, but all fields in the destination index start with "latest_doc.".
Is there a way to prevent fieldnames being preceeded with this latest_doc label ?
(Otherwise i have to use different index-templates for input indexes and output indexes)

A: found a workaround, for anyone who wants to know:
added a ingest pipeline:
PUT _ingest/pipeline/remove_trailing_
{
    "processors": [{
            "script": {
                "source": """
                for(item in ctx['latest_doc'].entrySet()) {
                   def f1 = 'latest_doc.' + item.getKey();
                   def f2 = item.getKey();
                   ctx[f2] = item.getValue();
                }
                ctx.remove('latest_doc');
                """
            }
        }
    ]
}


text:
Q: Pagination on php array and calling it to html I've read about pagination on arrays and I know there are already tutorials about it but I guess I have a different problem. I have a view.php which contains the code for array which is from the database, and it is encoded as json array. When you open with browser the view it shows the array but what I did was I connected my index.html to my javascript. I append the values from view.php. I check if tbody is empty and I append the data if it is empty. Now my problem is I don't know how can I do the pagination. I don't know if I'm going to put it on view.php or index.html or on the javascript. And I don't know how will I be able to do the pagination because I did different process with json encoding.
view.php
<?php
include_once('db.php');
$sql = "SELECT * FROM `user` order by datetime desc";
$res = mysql_query($sql);
$result = array();

while($row = mysql_fetch_array($res))
    array_push($result, array('name' => $row[0],'username' => $row[1]));

    echo json_encode(array("result" => $result ));
?>

index.html

            Name
            Username

javascript
function updates() {
    $.getJSON("view.php", function(data){

        $("tbody").empty();
        $.each(data.result, function(){

            $("tbody").append("
"+this['username']+
            "	"+this['name'] )
        });
    });
}

By the way, I used javascript because I want to automatically update the data once there is an additional record on the database.


text:
Q: How to query abstract-class-based objects in Django? Let's say I have an abstract base class that looks like this:
class StellarObject(BaseModel):
  title = models.CharField(max_length=255)
  description = models.TextField()
  slug = models.SlugField(blank=True, null=True)

  class Meta:
    abstract = True

Now, let's say I have two actual database classes that inherit from StellarObject
class Planet(StellarObject):
  type = models.CharField(max_length=50)
  size = models.IntegerField(max_length=10)

class Star(StellarObject):
  mass = models.IntegerField(max_length=10)

So far, so good.  If I want to get Planets or Stars, all I do is this:
Thing.objects.all() #or
Thing.objects.filter() #or count(), etc...

But what if I want to get ALL StellarObjects?  If I do:
StellarObject.objects.all()

It of course returns an error, because an abstract class isn't an actual database object, and therefore cannot be queried.  Everything I've read says I need to do two queries, one each on Planets and Stars, and then merge them.  That seems horribly inefficient.  Is that the only way?

A: Don't use an abstract base class if you need to query on the base. Use a concrete base class instead.

A: This is an example of polymorphism in your models (polymorph - many forms of one).
Option 1 - If there's only one place you deal with this:
For the sake of a little bit of if-else code in one or two places, just deal with it manually - it'll probably be much quicker and clearer in terms of dev/maintenance (i.e. maybe worth it unless these queries are seriously hammering your database - that's your judgement call and depends on circumstance).
Option 2 - If you do this quite a bit, or really demand elegance in your query syntax:
Luckily there's a library to deal with polymorphism in django, django-polymorphic - those docs will show you how to do this precisely. This is probably the "right answer" for querying straightforwardly as you've described, especially if you want to do model inheritance in lots of places.
Option 3 - If you want a halfway house:
This kind of has the drawbacks of both of the above, but I've used it successfully in the past to automatically do all the zipping together from multiple query sets, whilst keeping the benefits of having one query set object containing both types of models.
Check out django-querysetsequence which manages the merge of multiple query sets together.
It's not as well supported or as stable as django-polymorphic, but worth a mention nevertheless.

A: At its root, this is part of the mismatch between objects and relational databases. The ORM does a great job in abstracting out the differences, but sometimes you just come up against them anyway.
Basically, you have to choose between abstract inheritance, in which case there is no database relationship between the two classes, or multi-table inheritance, which keeps the database relationship at a cost of efficiency (an extra database join) for each query.

A: You can't query abstract base classes.  For multi-table inheritance you can use django-model-utils and it's InheritanceManager, which extends standard QuerySet with select_subclasses() method, which does right that you need: it left-joins all inherited tables and returns appropriate type instance for each row.

A: In this case I think there's no other way.
For optimization, you could avoid inheritance from abstract StellarObject and use it as separate table connected via FK to Star and Planet objects.
That way both of them would have ie. star.stellar_info.description.
Other way would be to add additional model for handling information and using StellarObject as through in many2many relation.

A: I would consider moving away from either an abstract inheritance pattern or the concrete base pattern if you're looking to tie distinct sub-class behaviors to the objects based on their respective child class.
When you query via the parent class -- which it sounds like you want to do -- Django treats the resulting ojects as objects of the parent class, so accessing child-class-level methods requires re-casting the objects into their 'proper' child class on the fly so they can see those methods... at which point a series of if statements hanging off a parent-class-level method would arguably be a cleaner approach.
If the sub-class behavior described above isn't an issue, you could consider a custom manager attached to an abstract base class sewing the models together via raw SQL.
If you're interested mainly in assigning a discrete set of identical data fields to a bunch of objects, I'd relate along a foreign-key, like bx2 suggests.

A:
That seems horribly inefficient. Is that the only way?

As far as I know it is the only way with Django's ORM. As implemented currently abstract classes are a convenient mechanism for abstracting common attributes of classes out to super classes. The ORM does not provide a similar abstraction for querying.
You'd be better off using another mechanism for implementing hierarchy in the database. One way to do this would be to use a single table and "tag" rows using type. Or you can implement a generic foreign key to another model that holds properties (the latter doesn't sound right even to me).


text:
Q: winform localization If there are hundreds of form and 20-30 projects in the application and during localization the number of .resx files generated will be very high.
Is there any way to organize the .resx files and satellite assembly?
If I move the .resx file to common assembly then the design time support for previewing the form is lost.
Is there any standard ways for handling projects with large number form.

A: I wouldn't recommend that option.
Just switch Localizable to true and handle translations via external tool (not Visual Studio). There are plenty of them, you only need to find the one that suite your needs.
That said, you should only have neutral culture resources in your project. Other languages could be added by compiling translated .resx into satellite assemblies.
Some tools that could be useful:

*

*WinRes - Windows Forms Resource Editor

*ResGen - Resource File Generator