text:
Q: Why is Upstart not starting uWSGI? I am trying to set up a django project on my VPS. I am trying to get a uWSGI Emperor to run and thus spawn vassals. I have set up all my config files as suggested by numerous websites including the uWSGI documentation. Yet when I run the file command paul@example:/$ sudo service uwsgi start
I get the following:

start: Unknown job: uwsgi
I figured this was because Upstart couldn't recognize the uwsgi.conf file http://uwsgi-docs.readthedocs.org/en/latest/Upstart.html I have in /etc/init/. But after review I can not find anything wrong with it.

paul@example:/etc/init$ sudo vim uwsgi.conf

# Emperor uWSGI script

pre-start script
    logger "pre-start for uWSGI Emperor"
end script

post-start script
    logger "post-start for uWSGI Emperor"
end script

description "uWSGI Emperor"

start on runlevel [2345]
stop on runlevel [!2345]

respawn

env LOGTO = /var/log/uwsgi.log

exec /usr/local/bin/uwsgi --master --die-on-term --emperor /etc/uwsgi/vassals --logto $LOGTO

I also checked over my /etc/uwsgi/vassals files to make sure they were in working order. My only file right now is a mysite.ini file:

paul@example:/etc/uwsgi/vassals$ sudo vim mysite.ini

[uwsgi]
base = /home/paul/djprojs/mysite/
chdir = %(base)
master = true
threads = 20
socket = /tmp/sockets/%n.sock
home = /home/paul/.virtualenvs/dj
env = DJANGO_SETTINGS_MODULE=%n.settings
module = django.core.handlers.wsgi:WSGIHandler()

But this looks okay to me also.
Finally, to test and see if uWSGI would run from the command line, I started it without Upstart. I ran

paul@exmaple/$ uwsgi --emperor /etc/uwsgi/vassals

and it worked:

*** Starting uWSGI 1.9.13 (32bit) on [Sat Jul 27 19:23:43 2013] ***
compiled with version: 4.6.3 on 21 July 2013 03:35:50
os: Linux-3.2.0-24-virtual #37-Ubuntu SMP Wed Apr 25 12:51:49 UTC 2012
nodename: example.me
machine: i686
clock source: unix
detected number of CPU cores: 1
current working directory: /
detected binary path: /usr/local/bin/uwsgi
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 3922
your memory page size is 4096 bytes
detected max file descriptor number: 1024
*** starting uWSGI Emperor ***
*** has_emperor mode detected (fd: 6) ***
[uWSGI] getting INI configuration from mysite.ini
*** Starting uWSGI 1.9.13 (32bit) on [Sat Jul 27 19:23:43 2013] ***
compiled with version: 4.6.3 on 21 July 2013 03:35:50
os: Linux-3.2.0-24-virtual #37-Ubuntu SMP Wed Apr 25 12:51:49 UTC 2012
nodename: example.me
machine: i686
clock source: unix
detected number of CPU cores: 1
current working directory: /etc/uwsgi/vassals
detected binary path: /usr/local/bin/uwsgi
your processes number limit is 3922
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
uwsgi socket 0 bound to UNIX address /tmp/sockets/mysite.sock fd 3
Python version: 2.7.3 (default, Apr 10 2013, 06:03:17)  [GCC 4.6.3]
Set PythonHome to /home/paul/.virtualenvs/dj
Python main interpreter initialized at 0x9bdb000
python threads support enabled
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 410112 bytes (400 KB) for 20 cores
*** Operational MODE: threaded ***
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x9bdb000 pid: 18213 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 18213)
spawned uWSGI worker 1 (pid: 18214, cores: 20)

Then I was left without a bash prompt. The uWSGI cli shows all the server requests and doesn't return to let me type another command. I really feel like there must be a better way to do this (aka. using 'sudo service uwsgi start/restart') but I'm not sure how. I have looked into this post but I'm not sure a different runlevel would solve the issue at hand.

A: Figure it out. Not sure I know how though.
I think it was the LOGTO portion of the uwsgi.conf file that made it not work. This is my uwsgi emperor file now:

description "uWSGI Emperor"

start on runlevel [2345]
stop on runlevel [!2345]

respawn

exec uwsgi --emperor /etc/uwsgi/vassals/ --master --uid www-data --gid www-data --logto /var/log/uwsgi/emperor.log

And this is my vassal, ie. mysite.ini

[uwsgi]
base = /home/paul/djprojs/mysite
chdir = %(base)
module = mysite.wsgi:application
pidfile = /tmp/uwsgi_vassal_%n.pid
socket = /tmp/sockets/%n.sock
vacuum = True
wsgi-file = /home/paul/djprojs/mysite/mysite/wsgi.py
home = /home/paul/.virtualenvs/dj

Still working on how to clean it up but it is working like a beaut.

A: The job is invalid - just run 'init-checkconf job.conf' and it will tell you what the problem is:
ERROR: File /tmp/job.conf: syntax invalid:
init:aa.conf:18: Unexpected token

In summary, you can't have spaces between the key and value in an env stanza. See init(5) for stanza syntax.

A: While an old question, I suspect I've just spent the last several hours bashing my head into a wall for the same issue. For me, uWSGI was trying to work with a file in a folder it did not have permissions in. A simple chmod on the directory in question fixed it all (the log files for me). The issue was constantly appearing to be something else, but in the end that's all it took. Might not be the true answer to your problem, but hopefully it might help someone else out there suffering as I have been.


text:
Q: Law of large numbers about non identical random sequence. I want to show the following statement.
Statement :
$Z \to 0 $, when $N \to \infty $.
where
$Z = \frac{{\left| {{e^{j{\theta _1}}}\left| {{x_1}} \right| + {e^{j{\theta _2}}}\left| {{x_2}} \right| + ,..., + {e^{j{\theta _N}}}\left| {{x_N}} \right|} \right|}}{N}$ and ${\theta _n}\sim {\text{uniform}}\left[ {0,2\pi } \right]$.
$x_n$ is not random variable but just sequence (it means that it does not have any specific distribution.)
$x_n$ is bounded such that $\left| {{x_n}} \right| < B < \infty $.
I think the law of large numbers can be used but I cannot prove that clearly.
Thanks for your help!

redpajama_set_name: RedPajamaStackExchange


text:
Q: sed replace text - escape characters I have a mysqldump file in which I want to replace the following text <a href="/tag/ with <a href="http://www.mydomain.com/tag/ but can't find a way to correctly escape all special characters.
I'm using the following command (+ a few other variants)
cat wordpress_posts.sql | sed 's%/<a href="\/\tag\/\/ wordpress_posts_new.sql
but it's not working.
Can anybody help?
Update 1:
Turns out that the source string in the mysqldump isn't <a href="/tag/ but <a href=\"/tag/ (note the extra backslash after the equal symbol)
Here's a pastebin of one line of the SQL file which contains the string I want to replace: http://pastebin.com/8G5mcxpJ
I tried all 3 suggested versions of the sed command, but none would replace the above string with <a href=\"http://www.mydomain.com/tag/
(yes I added the backslash after the equal symbol)

A: You don't have to escape /, you can just use any other delimiter:
sed 's#<a href=\\"/tag/#<a href="http://www.mydomain.com/tag/#' wordpress_posts.sql

A: No need to pipe cat to sed:
$ sed 's/<a href="\/tag\// wordpress_posts.sql


text:
Q: ffmpeg: how to get YUV data from AVframe and draw it using opengl? How could I access the YUV data from AVframe struct? by accessing its data[]?
And is there any simple way to draw YUV data using opengl instead of creating the shader and draw the Y,U,V image on their own?

A: Yes, you use frame->data[]. Typically everyone uses shaders/textures, so you should too. Just upload them as textures, use code like this to upload the texture:
glPixelStorei(GL_UNPACK_ROW_LENGTH, frame->linesize[0])
glActiveTexture(GL_TEXTURE0 + id);
glBindTexture(GL_TEXTURE_2D, texture[id]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, frame->width, frame->height,
             0, GL_LUMINANCE, GL_UNSIGNED_BYTE, frame->data[0]);

Upload data[1] and [2] in the same way but apply chroma subsamplings to width/height (e.g. uvwidth = (width + 1) >> 1). This code also assumes that you've created 3 textures in an array called texture[]. In your drawing loop, you can then refer to these texture ids to link them to uniform textures in your shaders, which you eventually use to draw. Shader examples that do YUV-to-RGB conversion can be found virtually anywhere.


text:
Q: \copy table via psql from local to Docker container from within the container Disclaimer: Not talking about this.
How can I execute \copy command from psql when I'm inside the live docker container?
When I try \copy table from '/home/Snow/Documents/table.csv' with delimiter as ',' csv header;
I get the error:

No such file or directory

Is there a different path I should write?

A: From outside the container you can import a file using psql with the following command:
$ cat table.csv | psql -h docker_container -d db -c \
"COPY table FROM STDIN WITH DELIMITER ',' CSV"

*

*Replace docker_container with the IP or hostname of the container

*In case your postgres isn't configured to accept external connections, change it in the postgres.conf file: e.g. listen_addresses = '*' to listen to all external connections.

A: You would have to either copy the file to your docker container or mount the directory.
To copy the file, follow the procedure in the question to which you linked, something like:
docker cp /home/Snow/Documents/table.csv your_container:/
Then, from within your container, you could import access the file:
\copy table from '/table.csv' with delimiter as ',' csv header;
Alternatively, when you created the container, you could have added a volume with the -v option like:
docker run -v /home/Snow/Documents:/data postgres
and then your Documents directory would be at /data allowing you to import like this:
\copy table from '/data/table.csv' with delimiter as ',' csv header;


text:
Q: I have built a WebView app but the popup under website not showing up Please help me I have developed a webview app in which I have added the Instagram link but I am not able to open that (+) sign to add images also on other websites so I am not able to open popup under any of the websites.
import android.Manifest;
import android.annotation.TargetApi;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class WebviewActivity extends AppCompatActivity {
    ConnectionDetector cd;
    static InterstitialAd mInterstitialAd;
    AdView adView;
    Spinner spUrls;
    WebView webView;
    ProgressBar pb;
    TextView tvGo;
    long time=0;
    String[] urls;
    String url="https://facebook.com/";
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        getSupportActionBar().hide();
        cd=new ConnectionDetector(this);
        spUrls=(Spinner)findViewById(R.id.spUrls);
        webView=(WebView)findViewById(R.id.webView);
        tvGo=(TextView)findViewById(R.id.tvGo);
        pb=(ProgressBar)findViewById(R.id.msw_progress);

        urls=getResources().getStringArray(R.array.urls);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAllowFileAccessFromFileURLs(true);
        webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webView.getSettings().setAppCacheEnabled(false);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        if(cd.isConnectingToInternet()) {
            webView.loadUrl(url);
        }else{
            Toast.makeText(this,"PLEASE CHECK YOUR INTERNET CONNECTION",Toast.LENGTH_LONG).show();
        }
        webView.setWebViewClient(new WebViewClient());
        webView.setWebChromeClient(new WebChromeClient(){
            public void onProgressChanged(WebView view, int progress) {
                pb.setProgress(progress);
                if(progress==0)
                    pb.setProgress(0);
                //Make the bar disappear after URL is loaded, and changes string to Loading...
                /*setTitle("Loading...");
                setProgress(progress * 100); //Make the bar disappear after URL is loaded
                // Return the app name after finish loading
                if(progress == 100)
                    setTitle(R.string.app_name);*/
            }
        });
        WebView wv=new WebView(this);
        wv.setWebChromeClient(new WebChromeClient() {
                                  @Override
                                  public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                                      //Required functionality here
                                      return super.onJsAlert(view, url, message, result);
                                  }
                              });
        adView=(AdView)findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("ca-app-pub-*******"); // Seems like you may be exposing your ad unit id to the public, may be better to keep this a secret or use the testing id found in the admob docs
        mInterstitialAd.loadAd(new AdRequest.Builder().build());

        tvGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                url=urls[spUrls.getSelectedItemPosition()];
                if(cd.isConnectingToInternet()) {
                    webView.loadUrl(url);
                    if (mInterstitialAd.isLoaded()) {
                        mInterstitialAd.show();
                    }
                }else{
                    Toast.makeText(WebviewActivity.this,"PLEASE CHECK YOUR INTERNET CONNECTION",Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            if((System.currentTimeMillis()-time)<2000){
                super.onBackPressed();
            }else{
                Toast.makeText(this, "PRESS AGAIN TO EXIT", Toast.LENGTH_SHORT).show();
            }
            time=System.currentTimeMillis();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }
    }
}

here you can see my all code for webview please tell me solution as fast as you can

A: Maybe try taking a look at This Stack Overflow post about showing popups in a webview.
I think the key for you would be the following piece of code in that post:
WebView newWebView = new WebView(WebpageActivity.this);
            newWebView.getSettings().setJavaScriptEnabled(true);
            newWebView.getSettings().setSupportZoom(true);
            newWebView.getSettings().setBuiltInZoomControls(true);
            newWebView.getSettings().setPluginState(PluginState.ON);
            newWebView.getSettings().setSupportMultipleWindows(true);
            view.addView(newWebView);
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(newWebView);
            resultMsg.sendToTarget();

            newWebView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }
            });

Hope this helps.


text:
Q: best way to use CoreLocation across multiple views I have two views in my app, one is a general view where CoreLocation works away calculating the users location while the user is doing other stuff in the view. The second view is accessed by the user when they touch a button allowing them to locate themselves more accurately using a mapview and MapKit, i would like the mapview in this view to show the location that CoreLocation has already identified in the first view AND to continue displaying this location based on updates from CoreLocation in the other view.
Is the best way here to create a singleton that encapsulates the CoreLocation stuff and have this referenced in the view with the map, or to use notifications ? or to use some other better practice for my scenario ?
Thanks

A: I have a couple of apps that use CoreLocation in multiple places. From what I've read, you definitely want there to be just one instance of CLLocationManager. It's worked great as a singleton for me.
Hope this helps!

A: If I were you, I would do it this way:

*

*Decide which view is going to be always loaded.
I assume, you want CalculatingView is loaded all the time, and MapView will be loaded/unloaded based on the user action.

*Allocate and initialize a pointer to CLLocationManager inside CalculatingView. This will provide location property and also call delegate messages. Since the CalculatingView is loaded and retained, this pointer is always working too.

*Set CLLocationManager's delegate to be CalculatingView, which might also be called self, if this view has allocated and initialized CLLocationManager pointer.

*Implement delegate methods of CLLocationManager, in CalculatingView

*If you like to, you can have MapView to be allocated and initialized within CalculatingView. But it's ok to have it in other places, as long as you can send message to MapView. Make sure they are valid by checking if it's not nil or if it respondsToSelector.

*When the CLLocationManager's delegate, which is CalculatingView receives messages, send a message to MapView.

*It's like relaying messages, but the messages that MapView should respond to don't have to be the same messages sent to CalculatingView like delegate method calls from CLLocationManager

*By checking if MapView is valid, meaning if it's loaded to be displayed, you can decide to send messages to MapView or not
The essence is to decide which view is loaded consitently, to use delegate methods for sending(or relaying) messages to other pointers(in this cases, MapView pointer).
The singleton is good, but unless you are going to use CLLocationManager from multiple places, like  more than 3~4 places, it's not that necessary, I think
Hope I didn't confuse you. Based on what you posted, it seems like this way can be simple solution for your goal. If I didn't catch your true intention, please let me know.

A: I am not sure this is the best way, but I've been setting up my main controller (the one that is loaded first) as a location manager delegate.  When the location updates it fires off a notification with the new location as the notification object.  Any controllers listening can then use that data however they need it.
As an aside, Apple's LocateMe app instantiates the location manager three times.  So, by their example, having multiple LocationManagers might not be a problem.

A: From what I've read, best practice for this is to add CLLocationManager to your App Delegate as you can access it from any view.
Short sample code to put in your view where you need the CLLocationManager
....imports....

@implementation YourViewController

- (void)viewDidLoad {
   self.myLocationManager = [[UIApplication sharedApplication] delegate].yourLocationManagerVarName;
}

@end

Hop that helps.

A: Maybe you should consider a MVC oriented approach. From your description your are missing a model layer representation of your user. Defining a simple User class with a basic CLLocation property would be a first step.
@interface User {}
@property (nonatomic, retain) CLLocation *location;
@end

@implementation User
@synthesize location;
- (void)dealloc {
  self.location = nil;
  [super dealloc];
}
@end

The same instance of the User will be passed to your view controller. It may be created in the app delegate.
Next create location services object for your app. It will start the CLLocationManager, and give the location to your user. You may have to set the GPS accuracy, ignore frames you don't want, and implement basic LBS logic here.
At this point, you have a feature full app, without any UI. This is a good design in the way it can be reused and tested.
Now stack your UI on top of that. Give your root controller a pointer to the User instance in your app delegate. Your view controller pass this pointer to modals / navigations view controllers it creates.
This controller start observing User's location changes in their viewDidLoad and react accordingly.
- (void)viewDidLoad {
   [self observeValueForKeyPath:@"location" ofObject:self.user change:0 context:NULL];
}

Your view controller would also register for notification raised by your location services objects to display an alert to the user.
Based on other answers:

*

*there is no real penalty to create multiple CLLocationManager instances in your code. The only side effect is that the api is asynchronous, thus you have to wait to get a valid location in your view controller. You can try to get the current location from the location manager on your viewDidLoad using locationManager.location API.

*don't share stuff from your app delegate. This prevent code reuse. What if you reuse your views and you app delegate don't have a location manager ?

if you need more code, please ask.


text:
Q: C++ Unrolled loop at compile time I have several segments of code in my c++ project which look something like this:
system<0>::global_instance.do_something();
system<1>::global_instance.do_something();
system<2>::global_instance.do_something();
system<3>::global_instance.do_something();
//...
system<29>::global_instance.do_something();
system<30>::global_instance.do_something();
system<31>::global_instance.do_something();

It seems a bit repetitive, right? It would be great if I could just do something like this:
for(int i = 0; i < 32; i++)
{
  system<i>::global_instance.do_something();
}

Unfortunately, that won't work because the value of i isn't known at compile time and therefore cannot be used as a template parameter for system.
What I need is a way to expand or unroll loops at compile time.
I've seen some implementations which use templates to achieve unrolling, but they don't work for what I'm trying to do. Ideally, the loop unrolling would take place during preprocessing, and could take any arbitrary statement as input.
For example, this:
#unroll NUM 0 5
foo<NUM>();
#endunroll

Would get translated into this:
foo<0>();
foo<1>();
foo<2>();
foo<3>();
foo<4>();
foo<5>();

And this:
#unroll NUM 0 5
blah blah blah NUM
#endunroll

Would get translated into this:
blah blah blah 0
blah blah blah 1
blah blah blah 2
blah blah blah 3
blah blah blah 4
blah blah blah 5

Even though blah blah blah NUM is a syntactically incorrect statement, it should still get copied and every instance of the token NUM should get replaced by the appropriate number value.
Is there any way to achieve this in vanilla c++? Or are there any special c++ compilers which add this functionality?
Edit: I found an answer from @HTNW in the comments.
#include <iostream>
using namespace std;

template<auto begin, auto end>
inline void unroll(auto f)
{
  if constexpr(begin < end)
  {
    f.template operator()<begin>();
    unroll<begin + 1, end>(f);
  }
}

template<int NUM>
struct thingy
{
  static void print(){cout << NUM << endl;}
};

int main()
{
  unroll<0,8>([]<int i>()
  {
    thingy<i>::print();
  });
}

Output:
0
1
2
3
4
5
6
7

The line which makes this work is f.template operator()<begin>();. I have no idea what this line means and I've never seen it before in my life. If someone could explain it to me, that would be great.

A: You can make use of std::index_sequence and a fold expression, for example:
#include <iostream>
#include <utility>

template <size_t x>
void foo ()
{
    std::cout << x << " ";
}

template <size_t... indices>
void unroll (std::index_sequence <indices...>)
{
    (foo <indices> (), ...);
}

int main ()
{
    unroll (std::make_index_sequence <32> {});
}

Output:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

Update: As per HTNW's comment, in C++20 you can pass a template lambda as an additional argument to unroll to avoid having to hard code a call to foo:
#include <iostream>
#include <utility>

template <size_t x>
void foo ()
{
    std::cout << x << " ";
}

template <size_t... indices>
void unroll (auto f, std::index_sequence <indices...>)
{
    (f.template operator () <indices> (), ...);
}

int main ()
{
    unroll ([] <size_t i> () { foo <i> (); }, std::make_index_sequence <32> {});
}

A: I am not sure if this is good for you but you can do something like this in c++17:
template <size_t curr, size_t max>
void unroll(){
    doSomething<curr>();
    if constexpr (curr < max)
        unroll<curr+1,max>();
}

Or as HTNW pointed out you can do:
template <size_t curr, size_t max>
void unroll(auto f){
    f.template operator()<curr>(); // See below
    if constexpr (curr < max)
        unroll<curr + 1,max>(f);
}

I had to adjust the suggestion, but this should work on c++20. You can then call this as:
unroll<0,20>([]<size_t i> () { system<curr>::do_something(); });

As to why you need f.template operator()<curr>(); see this.

A: I use this C++20 unrolling-helpers:
#pragma once
#include <utility>
#include <concepts>
#include <iterator>

template<size_t N, typename Fn>
    requires (N >= 1) && requires( Fn fn, size_t i ) { { fn( i ) } -> std::same_as<void>; }
inline
void unroll( Fn fn )
{
    auto unroll_n = [&]<size_t ... Indices>( std::index_sequence<Indices ...> )
    {
        (fn( Indices ), ...);
    };
    unroll_n( std::make_index_sequence<N>() );
}

template<size_t N, typename Fn>
    requires (N >= 1) && requires( Fn fn ) { { fn() } -> std::same_as<void>; }
inline
void unroll( Fn fn )
{
    auto unroll_n = [&]<size_t ... Indices>( std::index_sequence<Indices ...> )
    {
        return ((Indices, fn()), ...);
    };
    unroll_n( std::make_index_sequence<N>() );
}

template<size_t N, typename Fn>
    requires (N >= 1) && requires( Fn fn, size_t i ) { { fn( i ) } -> std::convertible_to<bool>; }
inline
bool unroll( Fn fn )
{
    auto unroll_n = [&]<size_t ... Indices>( std::index_sequence<Indices ...> ) -> bool
    {
        return (fn( Indices ) && ...);
    };
    return unroll_n( std::make_index_sequence<N>() );
}

template<size_t N, typename Fn>
    requires (N >= 1) && requires( Fn fn ) { { fn() } -> std::convertible_to<bool>; }
inline
bool unroll( Fn fn )
{
    auto unroll_n = [&]<size_t ... Indices>( std::index_sequence<Indices ...> ) -> bool
    {
        return ((Indices, fn()) && ...);
    };
    return unroll_n( std::make_index_sequence<N>() );
}

template<std::size_t N, typename RandomIt, typename UnaryFunction>
    requires std::random_access_iterator<RandomIt>
    && requires( UnaryFunction fn, typename std::iterator_traits<RandomIt>::value_type elem ) { { fn( elem ) }; }
inline
RandomIt unroll_for_each( RandomIt begin, RandomIt end, UnaryFunction fn )
{
    RandomIt &it = begin;
    if constexpr( N > 1 )
        for( ; it + N <= end; it += N )
            unroll<N>( [&]( size_t i ) { fn( it[i] ); } );
    for( ; it < end; ++it )
        fn( *begin );
    return it;
}

But be aware that unrolling isn't beneficial in most cases. But sometime it is: I optimized fletcher's hash with unroll_for_each and got 95% more througput on my machine. But the unrolling-factor was very crucial then: with an unrolling factor of 5 I got the mentioned 95%, with an unrolling-factor of 5 the code had the same performance than without unrolling.


text:
Q: dot (.) or source behavior in bash when POSIX mode set (OS X) I tried to check the difference in behavior of the . (or equivalently source) built-in. I'm using bash 3.2 on El Capitan. According to the documentation, setting the POSIX mode (set -o posix) should avoid the shell searching in current directory when . is issued with a filename not containing /.
I'm in tmp directory where myscript.sh (which echoes "Hello") resides:
MacBook:tmp simone$ set | grep SHELLOPTS
SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
MacBook:tmp simone$ . myscript.sh
Hello
MacBook:tmp simone$ set -o posix
MacBook:tmp simone$ set | grep SHELLOPTS
SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor:posix
MacBook:tmp simone$ . myscript.sh
Hello

It appears that the script in current directory is executed irrespectively of the POSIX setting. Did I misunderstand something or is there a more subtle explanation?

As pointed out in the comments, the behavior should be as described if . isn't in the PATH. My PATH variable contains the following string:
/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

A: It's a bug that was fixed in a subsequent version. From the bash changelog:

This document details the changes between this version, bash-4.0-alpha,
  and the previous version, bash-3.2-release. (…)
1.  Changes to Bash (…)
ggg. Fixed a bug that caused a shell running in Posix mode to search $PWD for a file specified as an argument to source/. when the file was not found in $PATH. (…)
iii. Fixed a bug that caused the shell to search $PATH for an argument to
       source/. even when it contained a /.


text:
Q: Need Some Quick Help With Preg_Replace :) Please :) so this is the issue I'm having.
I want to remove this:
[quote="RANDOMTHING"]

Inside the "" could be literarly anything
plus I want to remove
[/quote]

How can I do this with preg_replace?

A: $var = preg_replace('/(\[quote="[^"]+"\])|(\[/quote\]/)', '', $var);

Try that out. Added parenthesis for easier reading.

A: You just need to escape the [ and use a placeholder (a character class as below, or .*? for anything or \w+ for just letters) for the string in quotes:
$str = preg_replace('~
    \[/quote\]                    # either that
    |                             # or
    \[quote="[^\]"]+"\]           # with ="RANDOMTHING"
   ~x',
   '',
   $str
);

(You can remove the comments and linebreaks to compact it into one line. Just for illustration.)
Also check out https://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world if you frequently run into regex questions, but don't know yet how they work.


text:
Q: If a cell has a duplicate take value from another cell As you can see cell A4 with the quantity of B4 has a duplicate in cell A24 with quantity of B24. There is an 8 and 4 in total.
How can I find this kind of duplicate and sum them together?

A: You can use PivotTable to get the result directly:
Select the Range- go to Insert- PivotTable- drag Fields to areas:

For formula, try this method:
Copy column code to the new Column- select the new column and go to Data- Remove Duplicates:

Enter the formula:
=SUMIF($C$2:$C$30,F2,$B$2:$B$30)


text:
Q: Help resolving bug starting X with systemd as a user service I'm aware there is a question with a similar issue, like this one, however the solutions within there are not specific enough for my situation.
I understand there is a way to start X using startx and xinit and logind, but I wanted to do things this way instead:
For context: I am using OpenSUSE Tumbleweed and Systemd
I am trying to use custom user targets and user services to start a bunch of programs upon login from a specific tty, and one of these services is the X server. For the time being, I have the following service file sitting in ~/.config/systemd/user/Xserver.service, which is meant to start an empty Xorg server on vt7:
[Unit]
Description=Starts the X server
After=default.target

[Service]
Type=simple
ExecStart=/usr/bin/X vt07 :0
NoNewPrivileges=false

[Install]
# Irrelevant as of time being, just some custom targets I plan on isolating later.

When attempting to start this service,(systemctl --user start Xserver.service) however, it fails with exit code 1, and hen reading the Xorg logs I find they say that "switching VT failed".
I understand X at that point is suppposed to be running with root privileges (due to setuid), and is already connected to /dev/tty7, so how is this happening?
What could I do to make it work?
PS: (The reasoning behind systemd allocating ttys dynamically doesn't apply here since I'll have already logged in to the tty by the time this service is started)


text:
Q: Is there any way to test the order of Lists / Collections with jUnitJupiter? I'm using JunitJupiter for unit testing. Now I'm at a point where I don't know how to check the order of a list.
Code:
@Test
@DisplayName("Should be in ascending order")
void sortAscending() {
    List<List<AccountlinevaluesEntity>> finalList = monthlySuSa;
    for (List<AccountlinevaluesEntity> list : finalList) {
        list.sort(Comparator.comparing(AccountlinevaluesEntity::getAccountNumber));
        assert(list, ...........);

    }
}

I'm pretty new to unit testing, i searched a lot but I didn't figure out how to do it.
So, is there any way to do this with jUnitJupiter or are there other ways to do this?

A: Try
assertThat(list, Matchers.contains("your", "items", "in", "order")

From JavaDoc

Creates a matcher for {@link Iterable}s that matches when a single pass over the
  examined {@link Iterable} yields a series of items, each logically equal to the
  corresponding item in the specified items.  For a positive match, the examined iterable
  must be of the same length as the number of specified items.


text:
Q: 20.04 USB installation fails I have a home server that I want to upgrade (at long last :) from 16.04 LTS to 20.04 LTS. I put ubuntu-20.04-live-server-amd64.iso on a USB thumb drive and booted from it, and I got as far as "Profile Setup". But then after a few seconds that was replaced with a screen saying that an error had occurred, encouraging me to file a bug report (which I did of course). But how can I capture some diagnostics to post here to help identify the problem? It said something about writing the log to disk, but I don't know where it put it.
FWIW here are some more details. The computer is a Intel i5-2500K in a Gigabyte GA-Z68M-D2H motherboard. My boot disk has a swap partition at /dev/sda1 and the 16.04 partition at /dev/sda3. For 20.04 I used a spare 127G partition at /dev/sda2, asking the installer to format it ext4. There's also a 5-disk software RAID-6 array with one failed disk that I haven't replaced yet (so, state=clean,degraded, active devices=4) that I left unmounted during installation.
By the way I remember it offered to download an updated installer, 20.05.1 maybe. I said okay.
This sounds a lot like Ubuntu Server 20.04 LTS: Failed Install (subiquity...install_fail/add_info), except that my error screen contains less information. And in their case there was a RAID too... hmm . It also sounds a bit like When I am in profile set ubuntu server 18.04.1 an installation error occured, so I tried a couple of mirrors but that didn't change anything.
TIA everyone.

A: Update: I wasn't able to figure out exactly what was going wrong, but (as a guess) I tried installing on a partition on a new SSD (instead of sda that held the old 16.04 partition), and that worked. I guess there's something about the old volume that made the 20.04 installer fatally confused. Also, this means the RAID array wasn't a problem. I never did figure out if there's a good way to extract the installer logs, but now I don't need to anymore.


text:
Q: Mean of Exponential Families
Show that E{$e^{\delta T(Y)}|\eta$} = $e^{A(\eta + \delta) - A(\eta)}$. Then, prove that E{$T(Y)|\eta$} = $\frac{\partial A(\eta)}{\partial \eta}$.

First, we can begin by recognizing the fact that a PDF/PMF must integrate (or sum) to one, and now we just have to transform $e^{\delta T(Y)}$ into some recognizable PDF/PMF in order to try to find its expectation. However, I'm at a loss getting this started. Any help please?

A: Let $$f_Y(y|\eta) =h(y)\exp(\eta T(y)-A(\eta))$$
then
\begin{align}
E\{ e^{\delta T(Y)}|\eta\} &=\int h(y)\exp((\eta+\delta)T(y)-A(\eta)) \, dy \\
&= \exp(A(\eta+\delta)-A(\eta)) \cdot \int h(y)\exp((\eta+\delta)T(y)-A(\eta+\delta)) \, dy \\
&=\exp(A(\eta+\delta)-A(\eta))
\end{align}
You might like to use the property of cumulant generating function to solve the last part.


text:
Q: TypeORM: return updated object with single call to database? (async/await) TypeORM's entity.update() method does not return the updated object but a simple success/failure notification. The updated object can then be returned by doing entity.findOne() after the update, but that means two back and forth calls to the database instead of just one.
I've seen some people using entity.save() to do partial updates, but this creates new entities if the object does not exist, which is not desired. I could also use .then(), but I don't want to mix thens with my async/await code.
Is there any way of returning the updated entity in TypeORM with a single call to the database?
Edit:
My question originates from the answers and comments in this thread: TypeORM: update item and return it

A: There are several ways such as using queryBuilder.
You can see this, the answers to this question provide a lot of possible examples => TypeORM: update item and return it


text:
Q: configure zsh highlight for unknown command type I have currently set up my ZSH highlighting like this:
ZSH_HIGHLIGHT_HIGHLIGHTERS=(main brackets pattern line)
typeset -A ZSH_HIGHLIGHT_STYLES # For main-highlighter
ZSH_HIGHLIGHT_STYLES[command]='fg=blue'
ZSH_HIGHLIGHT_STYLES[function]='fg=green'
ZSH_HIGHLIGHT_STYLES[builtin]='fg=red'
ZSH_HIGHLIGHT_STYLES[unknown]='fg=green,bold'
ZSH_HIGHLIGHT_STYLES[arg0]='fg=white'

I wanted to add a directive, so that a command word, which is not a valid command (i.e. not in the PATH, nor a function or alias; i.e. a word w, for which type w would print w not found) is shown in a different colour, so that I can already find typing errors while typing the comman line.
Example: If I want to type gawk, but start typing the command
gwk ...

instead (and gwk is not a valid command in my environment), I would like to see it a different colour, so that I am alerted of the typing mistake early.
I first thought that the style named arg0 would handle this, but obviously it does not.
Is this possible to achieve, and which highlight style would I have to use for this?

A: You need to use unknown-token: https://github.com/zsh-users/zsh-syntax-highlighting/blob/master/docs/highlighters/main.md

PS: I maintain a Zsh plugin called Z Colors that can convert your $LS_COLORS to zsh-syntax-highlighting. It takes care of that stuff automatically.


text:
Q: Problems with void function in header of my static library I'm programming a .lib file for mobile robot.
Among other commands regarding robot movement, I also have command for scanning for Bluetooth devices looking something like:
void ScanForDevices(vector<Device> &Robot)
{
    /* code for searching Bluetooth devices and saving their names and addresses into vector of Device struct*/
}

My question is related with writing the header of the .lib file.
One of my commands is:
string RobotMove(int Translation, int Rotation)
    {
            /* create Command
        return string(Command);
    }

In the header, for that command I have:
// Returns MOVE command
        std::string RobotMove(int Translation, int Rotation);

What I have problem with is what to write in the header for:
void ScanForDevices(vector<Device> &Robot)

I keep getting "Incomplete type is not allowed" is I try to do the same way as RobotMove command. Do I have to declare in some way in the header struct Device?

A:
Do I have to declare in some way in the header struct Device?

If you want to create vectors for Devices, you need to let compiler know the size of the class by defining it. As noted by BoBTFish, the usual way is to just include Device.h header (or similar).
If you use pointers (vector<Device*> or even better, appropriate kind of smart pointer: vector<shared_ptr<Device>>) forward declaration (just stating class Device;) would be enough, as compiler knows size of the pointer on your architecture. (Note that this is completely different approach with different semantics than in your question, and this is just a side-note).

A: if your header file does not include (directly or indirectly),a definition for vector class you need to add #include <vector>  to your header file. The compiler does not know this data type without providing it the right information.


text:
Q: How to get specific terms from a python loop I have a list A.
 A = ['1','2','3','4','5','6','7','8','9','10','11','12']

I want to search the character 7 and if found,i would like the character before and after it get back as result.
desired result = ['6','7','8']

The numbers i have got from a loop.I am a newbie to Python.

A: You can try:
result = A[A.index('7')-1:A.index('7')+2]

But this only works with the first occurence of the searched item.
If you have more than one occurence of the item, use this:
A = ['1','2','3','4','5','6','7','8','9','7','11','12']

indexes = [ind for ind, val in enumerate(A) if val == '7']
for ind in indexes:
    result = A[ind-1:ind+2]
    print result

A: It would be slightly more efficient [complexity: O(2N) rather than O(N)] to store the index first, then slice:
i = A.index("7")
desired_result = A[i-1:i+2]
#['6', '7', '8']

The reason this works is that A.index(x) will return the index of x in the list - A. So in your example, A.index(7) would return 6 (remember lists start at 0). We then store this in a variable - i - to save calculating it again.
Then, we use list slicing to extract the section of the list one either side of the index. The syntax of slicing in general is:
[start : stop : step]

where all three options are optional and defaults of 0, len(list) and 1 will be used if emitted.
But you need to remember that, like with the range() function, this only slices up to stop, so we need to use a slice from i-1 to i+2 (which will include i+1 but not i+2).

The only slight problem with slicing this simply is if we are searching for an element which is the very first element in A - so here that would be "1". It wouldn't work in this case as A.index("1")-1 would be -1 (as 0 - 1 = -1) and all slicing treats negative values as indexes from the end of the list. This would mean are slice in this unique case would be A[-1: 1] which would result in an empty list ([]) for obvious reasons.
So, to fix this, all we need to do is make sure that the start index is never negative - if it is, we want it to be 0.
To achieve this, we could use a ternary which would look like:
desired_result = A[i-1 if i-1 < 0 else 0:i+2]

or, more succinctly, we could use max():
desired_result = A[max(0,i-1):i+2]

which would both now produce the correct slices for all inputs.

A: Here's a one-line solution that gets all matches of the searched character, returns the adjacent ones, and even wraps around if the matched character is at the beginning of the set
A = ['7','1','2','3','4','5','6','7','8','9','10','7','11','12']

output = [[A[idx-1], c, A[idx+1]] for idx, c in enumerate(A) if c=='7' and idx+1<len(A)]

print(output) # [['12', '7', '1'], ['6', '7', '8'], ['10', '7', '11']]

if you want something that returns only one index if the '7' is at the beginning or end it'll have to be a multiline function like this:
A = ['7','1','2','3','4','5','6','7','8','9','10','7','11','12', '7']
output = []

for idx, c in enumerate(A):
  if c=='7':
    output_list = []
    if idx == 0: # beginning of list
      output_list=[c, A[idx+1]] if idx+1<len(A) else None
    elif idx == len(A)-1: # end of list
      output_list=[A[idx-1], c] if idx-1>0 else None
    else: #somewhere in the middle
      output_list = [A[idx-1],c,A[idx+1]]
    output.append(output_list)

print(output) # [['7', '1'], ['6', '7', '8'], ['10', '7', '11'], ['12', '7']]

A: Probably there are more elegant ways to do it but...:
A = ['1','2','3','4','5','6','7','8','9','10','11','12']
print(A.index('7'))  # index of the seeked item
ll = [
    A[A.index('7')-1+i] for i in range(0,3)
    ]
print(ll)  # ['6', '7', '8']

A: Here is another way using a for loop and enumerate, this also happens to handle the case for repeats of '7', and the start, and end of a list, and has the added benefit of only iterating the list 1 time, it also assumes the list is unsorted:
for index, item in enumerate(A):
    if item is '7':
        # is first
        if index == 0:
             print('start', item, A[index+1])
        # is last
        elif index == len(A)-1:
            print(A[index-1], item, 'end')
        else:
             print(A[index-1], item, A[index+1])


text:
Q: Changing my PC's motherboard I have a Asus A7N266 motherboard currently with a Athlon XP 1.8GHz processor that I assembled in 2002. The Video RAM for this is just 32 MB. I would like to upgrade my motherboard and retain the Processor. Is that advisable? If so, could you also suggest a good motherboard that has a better VGA capability?

A: If you are unhappy with the video RAM why not buy a graphics card? It's way easier than swapping the motherboard.
And since your old computer is from 2002 I think it could be a problem for you to find a motherboard that would like your old RAM sticks and have the correct CPU socket. You'll probably have to buy a new motherboard, new RAM and a new CPU.

A: To be honest the only place you'll be able to buy a motherboard that will work with that processor is going to be on eBay, and even then I would question how reliable to board would be given its age.
I've got a couple of motherboards with Athlon XP 2400s (2.0GHz iirc) fitted that are gathering dust in a box of bits somewhere.  They pretty much became too expensive to upgrade any individual part about 7 years ago.
You'll be better off buying some sort of motherboard bundle from whoever your local supplier is, even the cheapest is likely to have a better processor and onboard graphics than a 2002 motherboard, with at least some current prospects for being upgradable without being extortionately expensive.

A: I suppose your processor has Socket A pins. I have bad news - these died more than 5 years ago. You'll not find a motherbord with such socket today.


text:
Q: Ubuntu 18.04 doesn't boot without monitor I have been trying to setup a headless server using Ubuntu 18.04 (server option) to no avail. My hardware is a mini computer Z83-F Minisforum. I have setup autostart on bios so that the computer starts up on its own after power outage. This works, and I can tell so because the lights on my keyboard keep flashing repeatedly after sometime which makes me feel like some activity is going on when the monitor is not connected to the server. However, the OS doesn't start and the server is not assigned an IP address from the router it's connected to.
When the server is connected to a monitor (via hdmi in my case), it works and I can log into it via ssh. If the monitor is not connected, the server does not indicate being bound on my router and I cannot connect to it via ssh.
I have tried the solutions on grub below to no avail.

*

*Option 1

*Option 2

*Option 3
Any help?

A: The OS doesn't care if a monitor is hooked up. However, the BIOS / UEFI settings on your device may recognize it as a fault and stop the POST process waiting for you to solve the issue.
Look for an option in the BIOS settings referring to halting startup on warnings or errors or ignoring warnings or errors on startup. Often times there is something related to the keyboard as well. If a keyboard is not plugged in it will halt.
If you can't find the related settings or continue to have issues, also try to download an install the latest firmware update.


text:
Q: How to use responses in neuralintents python library I created a voice assistant using python neuralintents module. but it didn't give a way to use responses in intents.json to give a feedback for user. Instead it is mapping response to a function.
Is there any way to use responses in intents.json.
I got this by watching this tutorial :
https://youtu.be/SXsyLdKkKX0
Github repo :
https://github.com/NeuralNine/neuralintents
Source code from video
from email.mime import audio
from fileinput import filename
from neuralintents import GenericAssistant
import speech_recognition
import pyttsx3 as tts
import sys

import webbrowser

recognizer = speech_recognition.Recognizer()

speaker = tts.init()
speaker.setProperty('rate', 150)

todo_list = ['Go shopping', 'Clean Room', 'Recpard Videos']

def create_note():
    global recognizer
    speaker.say("What do you want to write into your note")
    speaker.runAndWait()

    done = False

    while not done:
        try:
            with speech_recognition.Microphone as mic:
                recognizer.adjust_for_ambient_noise(mic, duration=0.2)
                audio = recognizer.listen(mic)

                note = recognizer.recognize_google(audio)
                note = note.lower()

                speaker.say("Choose a filename!")
                speaker.runAndWait()

                recognizer.adjust_for_ambient_noise(mic, duration=0.2)
                audio = recognizer.listen(mic)

                filename = recognizer.recognize_google(audio)
                filename = filename.lower()

            with open(filename, 'w') as f:
                f.write(note)
                done = True
                speaker.say(f"I sucessfully created the note {filename}")
                speaker.runAndWait
        except speech_recognition.UnknownValueError:
            recognizer = speech_recognition.Recognizer()
            speaker.say("I did not understand you! Please try again!")
            speaker.runAndWait()

def add_todo():
    global recognizer

    speaker.say("What doto do you want to add?")
    speaker.runAndWait()

    done = False

    while not done:
        try:
            with speech_recognition.Microphone() as mic:
                recognizer.adjust_for_ambient_noise(mic, duration=0.2)
                audio = recognizer.listen(mic)

                item = recognizer.recognize_google(audio)
                item = item.lower()

                todo_list.append(item)
                done = True

                speaker.say(f"I added {item} to the to do list!")
                speaker.runAndWait()

        except speech_recognition.UnknownValueError:
            recognizer = speech_recognition.Recognizer()
            speaker.say("I did not understand. Please try again!")
            speaker.runAndWait()

def show_todos():
    speaker.say("The items in your to do list are following")
    for item in todo_list:
        speaker.say(item)
    speaker.runAndWait()

def hello():
    speaker.say("Hello. What can I do for you?")
    speaker.runAndWait()

def exitt():
    speaker.say("Bye")
    speaker.runAndWait()
    sys.exit(0)

mapppings = {
    "greeting": hello,
    "create_note": create_note,
    "add_todos": add_todo,
    "show_todos": show_todos,
    "goodbye": exitt,
}

assistant = GenericAssistant('intents.json', intent_methods=mapppings)
assistant.train_model()
assistant.save_model()

def talk(text):
    engine = tts.init()
    voices = engine.getProperty('voices')
    engine.setProperty('voice', voices[1].id)
    engine. setProperty("rate", 150)
    engine.say(text)
    engine.runAndWait()

while True:
    try:
        with speech_recognition.Microphone() as mic:
            recognizer.adjust_for_ambient_noise(mic, duration=0.2)
            audio = recognizer.listen(mic)

            command = recognizer.recognize_google(audio)
            command = command.lower()
        assistant.request(command)

    except speech_recognition.UnknownValueError:
        recognizer = speech_recognition.Recognizer()

A: if you want the assistant to speak the response you call the function talk and pass assistant.request(command) as parameter, but if you have bindings for adding todo ect. u first call the assistant.request(command) alone and after that you chec if the request has any response and if it does you pass the response to the talk function

def talk(text):
    engine = tts.init()
    voices = engine.getProperty('voices')
    engine.setProperty('voice', voices[1].id)
    engine. setProperty("rate", 150)
    engine.say(text)
    engine.runAndWait()

while True:
    try:
        with speech_recognition.Microphone() as mic:
            recognizer.adjust_for_ambient_noise(mic, duration=0.2)
            audio = recognizer.listen(mic)

            command = recognizer.recognize_google(audio)
            command = command.lower()
        assistant.request(command)
        if(assistant.request(command))
            talk(assistant.request(command))

    except speech_recognition.UnknownValueError:
        recognizer = speech_recognition.Recognizer()


text:
Q: Find table name and its column name by column value (data's) Is there any possibility of getting a table name and its column name's by passing a column value(data) that is nothing but a data. passing a value to get the table name and the column name's.

A:
Is there any possibility?

Yes, of course. You can use the MySQL's information_schema to retrieve names of tables and columns in the current database.
SELECT TABLE_NAME, COLUMN_NAME
  FROM information_schema.COLUMNS
 WHERE TABLE_SCHEMA=DATABASE()
   AND DATA_TYPE IN ('char', 'varchar', 'text')

You can use that result set to write a program, in php or Java, or your favorite language, that will search every column of every table.
You didn't ask if this is a good idea.  But I will answer anyway. No.


text:
Q: Returning the first captured group in each match of a regex in javascript? I'm trying to use a regex in javascript that will find a section in a string that contains 3 different words. This is the expression that I have so far:
regEx = str.match(/(?=(\b(word1|word2|word3)\b(.+?)\b(word1|word2|word3)\b(.+?)\b(word1|word2|word3)\b))/gi);

This returns 6 empty matches. However, I know that it's matching the words because when I use .exec I can get all the groups in the first match. But how can I get it to return the first group in each match?

A: You can use the following code to get the first submatch in each match:

var re = /(?=(\b(word1|word2|word3)\b(.+?)\b(word1|word2|word3)\b(.+?)\b(word1|word2|word3)\b))/gi;
var str = 'gg word1 something word2 some word3 ggg';
var res= [];                           // Array for the results

while ((m = re.exec(str)) !== null) {  // Loop through matches
    if (m.index === re.lastIndex) {    //  if we have a zero-length match
        re.lastIndex++;                // advance the regex index manually
    }
    res.push(m[1]);                    // Add a value to the resulting array
}
document.body.innerHTML = JSON.stringify(res, 0, 4);


text:
Q: Asp.net cache or manual caching I'm going to cache some RSS data from other websites to my server and update caches every 10 minutes.
Should I use Asp.net system.web.caching or cache in database or file?
P.S: when a user requests a feed on my client application, my server downloads it from server. And in the next 10 minutes, if another user requests that feed, my server loads it from cache.
There may be for than 100 feeds...

A: The reason to go with custom database cache are:

*

*More control on how and when the cache expire

*The data are too many (more than 10Mg) *

*Need to keep them for too much time (days or months) *

*Access to the cache data on code behind (for any reason)

In your case, you only need to expire it soon, I think the data are small (less than 10Mg) and you keep it for 10 minutes, so go with asp.net cache that is faster because is lives in the core of the iis, and replays with out go to your code at all.
[*] I say that because the asp.net cache are keeped on the memory, but your custom cache are saved on database, so can live there for longer time, and can be huge.


text:
Q: Selenium can't connect to any driver I have the latest version of Selenium for python (Installed by doing pip install selenium, it installed version 2.53.6) and am running OS X 10.11.5.
If I try to do driver = webdriver.Firefox() a message comes up selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: .... If you specified a log_file in the FirefoxBinary constructor, check it for details..
I did brew install chromedriver. If I try to do driver = webdriver.Chrome() a message comes up selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service chromedriver.
I did npm install -g phantomjs. If I try to do driver = webdriver.PhantomJS() a message comes up selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service phantomjs.
I tried to Google and solve all these issues with these three drivers. Nothing seems to work. I am not sure if the port that selenium needs is being blocked or something, but I am out of ideas. It seems to be a fundamental problem with Selenium itself as all three drivers are failing. Anyone have a clue why?


text:
Q: Content of List gets Lost between start() and update() i try to create a list with tiles from tilemap and use that list to get coords of tiles on the tilemap.
I guess by looking at the comments in the update func the problem is pretty obvious but i dont know what to do
public class Spawner : MonoBehaviour
{
    private GameObject[] getCount;
    private int count;
    public int maxBags = 1;
    public Transform goldBag;
    public List<int> possibleTiles;
    public int possibleTilesLength;
    private int randomTileNr;
    public List<int> copyOfPossibleTiles;

    void Start()
    {
        Tilemap tilemap = GetComponent<Tilemap>();
        BoundsInt bounds = tilemap.cellBounds;
        TileBase[] allTiles = tilemap.GetTilesBlock(bounds);
        List<int> possibleTiles = new List<int>();
        for (int x = 0; x < bounds.size.x; x++) {
            for (int y = 0; y < bounds.size.y; y++) {
                TileBase tile = allTiles[x + y * bounds.size.x];
                if (tile != null) {
                    possibleTiles.Add(x);
                    Debug.Log(possibleTiles.Count);
                    possibleTiles.Add(y);
                    Debug.Log(possibleTiles.Count);
                    possibleTilesLength = possibleTiles.Count;
                }
            }
        }
    }
    void Update()
    {
        getCount = GameObject.FindGameObjectsWithTag("bagCoins");
        if(getCount.Length < maxBags)
        {
            randomTileNr = (int)UnityEngine.Random.Range(0,possibleTilesLength/2)*2;
            Debug.Log(possibleTiles.Count);                 //prints 0
            Debug.Log(possibleTilesLength);                 //prints 128
            Debug.Log(randomTileNr);                        //prints random even number between 0 and 128
            Debug.Log(copyOfPossibleTiles[randomTileNr]);   //prints error index out of range.
            maxBags = 0;
Instantiate(goldBag, new Vector3(possibleTiles[randomTileNr],possibleTiles[randomTileNr+1],0), Quaternion.identity);
        }
    }
}

A: You are storing them in a local variable in Start
List<int> possibleTiles = new List<int>();
for (int x = 0; x < bounds.size.x; x++) {
...

which hides the field with the same name. So your changes made in Start do not change the globally known list possibleTiles your Update method tries to access.
Rather use your field you already have and initialize it correctly
public List<int> possibleTiles = new List<int>();

and in Start do only
possibleTiles.Clear();
for (int x = 0; x < bounds.size.x; x++) {
...

A: Here you go, this is probably what you want
public class Spawner : MonoBehaviour
{
    private GameObject[] getCount;
    private int count;
    public int maxBags = 1;
    public Transform goldBag;
    public List<int> possibleTiles = new List<int>(); // Initialized list holding possible tiles
    public int possibleTilesLength;
    private int randomTileNr;
    public List<int> copyOfPossibleTiles;

    void Start()
    {
        Tilemap tilemap = GetComponent<Tilemap>();
        BoundsInt bounds = tilemap.cellBounds;
        TileBase[] allTiles = tilemap.GetTilesBlock(bounds);
        // Remove the line below since we want to declare the list as member variable and we already initialized it
        //List<int> possibleTiles = new List<int>();

        possibleTiles.Clear();
        for (int x = 0; x < bounds.size.x; x++) {
            for (int y = 0; y < bounds.size.y; y++) {
                TileBase tile = allTiles[x + y * bounds.size.x];
                if (tile != null) {
                    possibleTiles.Add(x);
                    Debug.Log(possibleTiles.Count);
                    possibleTiles.Add(y);
                    Debug.Log(possibleTiles.Count);
                    possibleTilesLength = possibleTiles.Count;
                }
            }
        }
    }
    void Update()
    {
        getCount = GameObject.FindGameObjectsWithTag("bagCoins");
        if(getCount.Length < maxBags)
        {
            randomTileNr = (int)UnityEngine.Random.Range(0,possibleTilesLength/2)*2;
            Debug.Log(possibleTiles.Count);                 //prints 0
            Debug.Log(possibleTilesLength);                 //prints 128
            Debug.Log(randomTileNr);                        //prints random even number between 0 and 128
            Debug.Log(copyOfPossibleTiles[randomTileNr]);   //prints error index out of range.
            maxBags = 0;
Instantiate(goldBag, new Vector3(possibleTiles[randomTileNr],possibleTiles[randomTileNr+1],0), Quaternion.identity);
        }
    }
}


text:
Q: How to work with AJAX as synchronously operation The following function checks errors in my form. One of the fields must be validated in the server. However, when I post the field the function continue and return from the function before I get answer from the server. I must get the result from the server before returning from the function.
This is my code:
function checkErrors()
    {
        var ErrorMsg = "";
        var buyerPublicKey = document.getElementById("BuyerAddressTxt").value;
        if (buyerPublicKey == "")
        {
            ErrorMsg = ErrorMsg+"Please Insert buyer Public Key.
";
        }

        var dealPrice = document.getElementById("PriceEthTxt").value;
        if (dealPrice == "")
        {
            ErrorMsg = ErrorMsg+"Please Insert buyer price.
";
        }
        var timeTobeOpen = document.getElementById("TimeSelector").value;
        if (timeTobeOpen == "Deafult")
        {
            ErrorMsg = ErrorMsg + "Please Insert time.
";
        }
        var url = "/CreateContract/CheckBuyerPublicKeyLegality";
        $.post(url, { BuyerPublicKey: buyerPublicKey }, function (data) //Here the problem begins
        {
           console.log("Buyer balance"+data)
           if (data == -1)
           {
            ErrorMsg = ErrorMsg + "Buyer Public Key is illegal.
";//
            console.log("1-->" +ErrorMsg );
           }

         });
        console.log("2-->" +ErrorMsg );
        return ErrorMsg;
    }

As you can see, I get the 2--> ErrorMessage before the 1--> ErrorMessage , which means the the posting operates asynchronously, while I need it to be synchronously.
What can I do here to change it?

A: Use async. By default async is set to be true, change it to false. Like this,
function checkErrors(){
var ErrorMsg = "";
var buyerPublicKey = document.getElementById("BuyerAddressTxt").value;
if (buyerPublicKey == "")
{
    ErrorMsg = ErrorMsg+"Please Insert buyer Public Key.
";
}

var dealPrice = document.getElementById("PriceEthTxt").value;
if (dealPrice == "")
{
    ErrorMsg = ErrorMsg+"Please Insert buyer price.
";
}
var timeTobeOpen = document.getElementById("TimeSelector").value;
if (timeTobeOpen == "Deafult")
{
    ErrorMsg = ErrorMsg + "Please Insert time.
";
}
$.ajax({
    url: "/CreateContract/CheckBuyerPublicKeyLegality",
    type: 'POST',
    async: false,
    data : { BuyerPublicKey: buyerPublicKey },
    success: function(data){
        console.log("Buyer balance"+data)
        if (data == -1)
        {
            ErrorMsg = ErrorMsg + "Buyer Public Key is illegal.
";//
            console.log("1-->" +ErrorMsg );
        }
    }
});
console.log("2-->" +ErrorMsg );
return ErrorMsg;}


text:
Q: Power Apps Canvas - import data from excel sheet I'm developing an application by using Powerapps canvas. I have a problem while importing data from the excel sheet, the first issue that some of the rows not been displayed on the page, second on all dates and time are not displayed correctly especially time. the table name Arrival and there are two columns STA for both date&time-"custom data type" and Arrival Time - "Time data type". I think I have a problem with zone time. I tried (TimeValue, DateVale, and DateTimeValue) functions and all of them didn't work or maybe I'm using these functions wrong way. look at the pictures to understand my problem more
I need help guys

A: You are correct that Excel times need to be adjusted for time zone. You can do that using the following expression:
Text(
    DateAdd(ThisItem.Time; TimeZoneOffset(ThisItem.Time); Minutes);
    DateTimeFormat.ShortTime24)

The DateAdd expression will take the time from Excel and adjust it to your local time; the Text will then convert it into a text so that you can display on a label in your gallery.
Hope this helps!


text:
Q: How does cross-origin AJAX request 'withCredentials' figure out which cookies to use? I can't figure out how this AJAX request knows which cookie to use. It uses the right one, but how does it know which one is the right one, or where is it specified (implicitly)?
$.ajax({
  url: 'https://remote-host.de/api/v2/session',
  crossDomain: true,
  xhrFields: {
    withCredentials: true
  },
  statusCode: {
    401: function() {
      // do stuff
    },
    200: function() {
      // do stuff
    }
  }
});

The request looks like this when I inspect it with Chrome and it has the right cookie set (the one of the remote host I am trying to request the login state from):
Accept:*\/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Cookie:_foo-bar_session=WjRMdExSQ1F6UlczbER0Ui9sQU9NNllIRWo1NmpCSXo2REh6akZmM1czODZ0M29adGh4aWg3ZmdrYWdxSU5KRVptUi8ybDladmJMHJhZWKZ3A5NlJCOTdWeFpCRGJQdHVvMnlxb0VQeWlCMGRtNDkxNDF3QVdhcnVRenlsQXExa3RNEtwZ1RNMW9oaE5TV1hLbHdnPT0tLXhtYUo3YytHY2wxWTFxanlXVTJjdlE9PQ%3D%3D--b22797a9b004d0759a43f4d94686edf909610a06
Host:remote-host.de
Origin:http://localhost:3001
Referer:http://localhost:3001/de
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36

The response:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:GET, POST, PATCH, PUT, DELETE, OPTIONS, HEAD
Access-Control-Allow-Origin:http://localhost:3001
Access-Control-Expose-Headers:ETag
Access-Control-Max-Age:86400
Cache-Control:no-cache
Connection:keep-alive
Content-Type:application/json; charset=utf-8
Date:Wed, 22 Mar 2017 10:18:15 GMT
Server:nginx
Set-Cookie:_foo-bar_session=SGhyWGtWTFVoc1AzUWlldmIxTjFGVXVCQU9YVkduSDFISWtLamwwT01heW5HN25saVNyYWJ1b2ZDZDI4RzNGT1BzYWZOOHNVK21DN0kxNmJRS1VDSTdwb1VVS2NtcTZ3Y1dRYUJSaTYxckpOdDZFZ2RpRlQzTHZPdDdTTjljenZzQ1hTUjlCN0RoZUlkcWlpNm5KK2VRPT0tLTkwUlNuM0Z6TDZ2TWJjZVVSUExpb0E9PQ%3D%3D--568e4688b6ff5e17faa32a3bab1a7cf01807a581; path=/; HttpOnly
Transfer-Encoding:chunked
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:b43ce1c4-2c80-4sd5-8333-0g93ae4df940f
X-Runtime:0.013627
X-XSS-Protection:1; mode=block

But how does it know?

A: Unless I'm misunderstanding the question, the browser just sends back whatever cookies it has that match the domain the request is being made to, and that match any path in the cookie.
How cookies work? has more details, with links to articles explaining how browsers handle cookies.


text:
Q: What algorithm can I use to turn a drunkards walk into a correlated RNG? I'm a novice programmer (the only reason I say this is because I'm not super familiar with all the terms yet) and I'm trying to make walls generate in respect to the wall before it. I've posted a question about it on here before
Randomly generated tunnel walls that don't jump around from one to the next
and sort of got the answer. What I was mainly looking for was the for loop that was used (I think). Th problem is I didn't know how to implement it properly without getting errors.
My problem ended up being "I couldn't figure out how to inc. this in to it. I have 41 walls altogether that i'm using and the walls are named Left1 and Right1. i had something like this
CGFloat Left1 = 14; for( int i = 0; i < 41; i++ ){
CGFloat offset = (CGFloat)arc4random_uniform(2*100) - 100;
Left1 += offset;
Right1 = Left1 + 100;

but it was telling me as a yellow text that Local declaration of  "Left1" hides instance variable and then in a red text it says "Assigning to 'UIImageView *__strong' from incompatible type 'float'. i'm not sure how to fix this"
and I wasn't sure how to fix it. I realize (I think) that arc4random and arc4random_uniform are pretty much the same thing, as far as i know, with slight differences, but not the difference i'm looking for.
As I said before, i'm pretty novice so any example would really be helpful, especially with the variables i'm trying to use. Thank you.

A: You want a "hashing" function, and preferably a "cryptographic" one because they tend to be significantly higher quality - at the expense of requiring additional CPU resources. But on modern hardware the extra CPU power usually isn't a problem.
The basic idea is you can give any data to the function, and it will spit out a completely random result, but always the same result if you provide the same input.
Have a read up on them here:

*

*http://en.wikipedia.org/wiki/Hash_function

*http://en.wikipedia.org/wiki/Cryptographic_hash_function
There are hundreds of different algorithms in common use, which is best will depend on what you need.
Personally I recommend sha256. A quick search of "sha256 ios" here on stack overflow will show you how to make one, with the CommonCrypto library. The gist is you should create an NSString or NSData object that contains every offset, then run the entire thing through sha256. The result will be a perfectly random 256 bit number.
If 256 bits is too much, just cut it up. For example you could grab just the first 16 bits of the number, and you will have a perfectly random 16 bit number.


text:
Q: ASP.Net Core Blazor: How to append different css file on _Host.cshtml based on session state user_id(Protected Browser Storage ) I would like to append two different CSS files based on session state user_id in an ASP.NET Core Blazor project (Server-side Blazor).
I have two css file for user 1 & 2
For example:

*

*If its user 1 css site1 should be appended on _Host.cshtml.

*If its user 2 css site2 should be appended on _Host.cshtml.

And the user_id= 1 and Userid = 2 in P
1.var user_id = await storage.GetAsync<int>("user");

this how the User_id is taken using await async. Now the requirement is to take
the user_id on _host.cshtml so that
On _Host.cshtml
@if(user_id ==1)
{
<link href="css/site1.css" rel="stylesheet" />
}
else if (user_id ==2)
{
<link href="css/site2.css" rel="stylesheet" />
}

Now iam unabe to use function (await storage.GetAsync(User_id);) on
_host.cshtml
This is how a _Host.cshtml page looks

@page

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    <meta charset="utf-8" />
    <title>ProjectName</title>
    <link rel="icon" type="image/png" sizes="32x32" href="images/tenantA/favicons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="images/tenantA/favicons/favicon-16x16.png">
</head>
<body class="something">
    <app>
        @(await Html.RenderComponentAsync<App>(RenderMode.Server))
    </app>

    <script src="_framework/blazor.server.js"></script>
    <link href="css/tenantA/site.css" rel="stylesheet" />
</body>
</html>

Now i need to get user_id on cshtml which is await call
    @page "/"
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@if(User_id =="1")
{
    <link href="css/site1.css" rel="stylesheet" />
    return;
}

<!DOCTYPE html>
<html lang="en">
<head>
....
...
..
.

This one is currently stopping my project . Please help me as soon as possible


text:
Q: Zend framework - form not rendering I'm just starting to use Zend Framework and was following the quick start documentation for the latest version (1.11.10). Everything was going just fine, but when I placed the form code and ran the application, the form did not render. My code is exactly like http://framework.zend.com/manual/en/learning.quickstart.create-form.html
On the view, I can dump the form just fine with var_dump($this->form);
I've tried echo $this->form(), echo $this->form->render(), but nothing appeared... What could it be?

A: This problem can occur when Zend can't find the template file for an element. Look at following code:
 $element->setDecorators(array(
            array('ViewScript',
                array(
                    'viewScript' => 'directory/_input.phtml'
                )
            )
        ));

The file _input.phtml must be in the right folder for this Controller. Otherwise Zend can't find the template for  input and can't successfully render your element and will not show anything.

A: Make sure you pass the form to the view from the controller.
In your action handler:
$this->view->form = $my_form;

In your view:
echo $this->form;

I suspected that this was the cause of your problem because Zend Framework doesn't complain if you try to echo a parameter that doesn't exist. (i.e. echo $this->some_fake_parameter won't do anything)

A: Ok so i tried your code, and it worked for me no problem.
Here is everything:
Controller

<?php
class IndexController extends Zend_Controller_Action
{
    public function myTestAction()
    {
        $form = new Form_Guestbook();

        // ... processing logics
    if($this->getRequest()->isPost())
    {
    if($form->isValid($this->getRequest()->getPost()))
    {
        var_dump($form->getValues());
    }
    }
        $this->view->assign('form', $form);
    }
}

Form

        <?php
        class Form_Guestbook extends Zend_Form
        {
            public function init()
            {
                // Set the method for the display form to POST
                $this->setMethod('post');

                // Add an email element
                $this->createElement('text', 'email', array(
                    'label'      => 'Your email address:',
                    'required'   => true,
                    'filters'    => array('StringTrim'),
                    'validators' => array(
                        'EmailAddress',
                    )
                ));

                // Add the comment element
                $this->addElement('textarea', 'comment', array(
                    'label'      => 'Please Comment:',
                    'required'   => true,
                    'validators' => array(
                        array('validator' => 'StringLength', 'options' => array(0, 20))
                        )
                ));

                // Add a captcha
                $this->addElement('captcha', 'captcha', array(
                    'label'      => 'Please enter the 5 letters displayed below:',
                    'required'   => true,
                    'captcha'    => array(
                        'captcha' => 'Figlet',
                        'wordLen' => 5,
                        'timeout' => 300
                    )
                ));

                // Add the submit button
                $this->addElement('submit', 'submit', array(
                    'ignore'   => true,
                    'label'    => 'Sign Guestbook',
                ));

                // And finally add some CSRF protection
                $this->addElement('hash', 'csrf', array(
                    'ignore' => true,
                ));
            }
        }
    ?>

View

<?php echo $this->form->render(); ?>

can be seen on: http://yaconiello.com/index/my-test
If this isnt working for you, you may be having a configuration error.

A: I had a problem like that (exact same form, since it is eclipse example)
My problem was due to misunderstanding. Since I thought that I have to directly access to the view script. I entered in the browser something like: hostname/application/view/script/something.php

But in zend all accesses should be through public folder. You have to access to the view like this: hostname/app_name/public/guestbook

hope that would help you


text:
Q: Excel - Where condition? I have two columns with data:
    A         B
1   HELIOS    AU
2   HELIOS
3   HELIOS    AU
4   SPARTA
5   HELIOS    AU

Countif(A..;"HELIOS") AND Countif(B..;"AU")

I can count the amount of HELIOS or SPARTA in a column. But how can I count the amount of AU per HELIOS or SPARTA?

A: Take a look at sumproduct function
http://www.meadinkent.co.uk/xlsumproduct.htm
=MATR.SOMMA.PRODOTTO((A1:A5="HELIOS")*(B1:B5="AU"))
=MATR.SOMMA.PRODOTTO((A1:A5="SPARTA")*(B1:B5="AU"))

These are the functions for my italian excel version.  :)
I think that english one is
=SUMPRODUCT((A1:A5="HELIOS")*(B1:B5="AU"))
=SUMPRODUCT((A1:A5="SPARTA")*(B1:B5="AU"))

A: DCOUNT should do what you're looking for.
It does require a label row, however, but then it allows stuff like this:

A: Use COUNTIFS to count with multiple criteria, e.g.
=COUNTIFS(A:A, "SPARTA", B:B, "AU")


text:
Q: Not able to launch one ec2 instance with count 1 and subnets(2) are created from the for_each loop Subnets are created from the below code:
    resource "aws_subnet" "Private" {
  for_each          = var.subnet_cidrs_private
  vpc_id            = aws_vpc.vpc.id
  cidr_block        = each.value
  availability_zone = each.key
  tags = {
    Name = format("%s-%s-%s", var.environment, "Pri-Subnet", substr(each.key, -2, -1))
  }
}

Trying to create 1 instance with count parameter.
    resource "aws_instance" "visualapp" {
  instance_type          = "t2.micro"
  ami                    = var.visualapp-ami
  key_name               = var.key_pair
  vpc_security_group_ids = [aws_security_group.visualapp.id]
  subnet_id              = element(aws_subnet.Private[*].id, count.index)
  count                  = 1
  tags = {
    Name = format("%s-%s", var.environment, "mage-varnish-${count.index + 1}")
  }
}

Getting the below error:
subnet_id = element(aws_subnet.Private[*].id, count.index)

This object does not have an attribute named "id".

Variables:
   variable "subnet_cidrs_private" {
  default = {
    eu-west-1a = "172.26.3.0/24",
    eu-west-1b = "172.26.4.0/24"
  }
}

Can anyone help me?.

A: element would be used if you had used count. Since you've used for_each you need to use values first:
subnet_id = element(values(aws_subnet.Private)[*].id, count.index)


text:
Q: google api 1.5 android how to download Google API 1.5 for android SDK using Eclipse if it is not in the available packages ????

A: Because my first Android dev device is Hero (Android 1.6), I never downloaded Android 1.5 SDK. I just checked the SDK Manager, Google API 3 is still in Available packages. This is the screenshot of my SDK Manager:

You can find that in "Available packages" -> "Third party Add-ons" -> "Google Inc." -> "Google APIs by Google Inc., Android API 3, revision 3". Please check again:)

A: If you have already set up the SDK, 1.5 probably isn't in your available packages because it's already in your installed packages. Just try creating a new project that targets 1.5 and see if it's there.

A: You are probably looking at the wrong place. The SDKs are not installed using "Install new software ..." that you used to install the ADT plugin. After installing it you must open in "Window"->"Android SDK and AVD Manager". From there clicking on "Available packages" and on the right pane on the "Android Repository" arrow should open all the available SDKs. There you can find "SDK Platform Android 1.5, API 3, revision 4". If you can not see the "Android SDK and AVD Manager" from within Eclipse you have not configured the ADT plugin (Eclipse preferences inside Android option) to use your base SDK files (those must be installed manually and then enter where you installed them).


text:
Q: OpenGL smoothing how? I need to do smoothing in OpenGL.
I find this code
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glShadeModel(GL_SMOOTH);

glHint(GL_POLYGON_SMOOTH_HINT, GL_FASTEST);
glEnable(GL_POLYGON_SMOOTH);

glDisable( GL_DEPTH_TEST );
glEnable( GL_ALPHA_TEST );

Smoothing is work in this case, but i don't need transparency. I think this 2 rows are responsible for transparency:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

But if i delete this strings - smoothing doesn't work. What i need to leave for smoothing? I need only smoothing in my project, don't need blend...

A: Well, smoothing works using transparency, the edges are not either colored or not but they are ... well ... transparent. Take a look at these images:

As you can see, the right line is not smoothed, it's pixels are either totally opaque or totally transparent. The left line is smoothed, it's outer pixels are transparent.
You may have a look into forcing Anti-Aliasing in your program, AA is a Hardware/Driver feature that just manages the smoothing of edges (and, depending on the type of AA, other things). Remember that this isn't a feature of OpenGL, but of the hardware, driver and operating system. In general you request something like AA when you create your OpenGL-Context.


text:
Q: ¿Por qué un enumerado no puede ser una plantilla?
enumeration cannot be a template

Ese es el error mostrado cuando intento compilar con BCC64 (basado en Clang) el siguiente código:
template <typename T> enum class enumerado : T
{
    a,b,c,d,e
};

Primero, pensé que esta prohibición explícita se debía a las limitaciones del tipo subyacente de los enumerados ya que si el tipo del enumerado puede ser un tipo plantilla, podría resultar en enumerados incorrectos, sin embargo cuando intentamos esto:
template <typename A> struct estructura
{
    enum class enumerado : A
    {
        a,b,c,d,e
    };
};

Compila sin problemas siempre que el tipo A cumpla con las limitaciones requeridas por el tipo subyacente de enumerados; de no ser así (tanto en un enumerado anidado en un objeto como en un enumerado contexto global) podemos ver otro error específico, como era de esperar:
enum class enumerado : mi_clase_fabulosa
{
    a,b,c,d,e
};

non-integral type 'mi_clase_fabulosa' is an invalid underlying type

Así pues, este es el motivo por el que me pregunto ¿por qué está explícitamente prohibido crear un enumerado plantilla cuando ya hay control sobre su tipo subyacente? ¿Dónde en el estándar de C++ está definida esta limitación?

Esta es una traducción de la misma pregunta en la versión Inglesa.

A: La pregunta original en stackoverflow ya tiene respuesta aceptada, que puedo trascribir acá:
Por definición [Estándar C++ 14.1], o por quedar fuera de la definición,

A template defines a family of classes or functions or an alias for a family of types.

Esto es: ''Un template define una familia de clases o de funciones o un alias para una familia de tipos.''
Y como un enum no es ninguno de esos, no puede ser un template.
Entonces, agrego yo, la limitación en el estándar es implícita, no explícita.


text:
Q: How do I get Django to run a case-insensitive query against my MySql 5.7 db? I'm using Django 2.0 and Python 3.7.  I have this model and manager for attempting to find my model by a name, case-insentively.  The backing database is MySql 5.7.
class CoopManager(models.Manager):
    ...

    # Look up coops by a partial name (case insensitive)
    def find_by_name(self, partial_name):
        queryset = Coop.objects.filter(name__icontains=partial_name, enabled=True)
        print(queryset.query)
        return queryset

class Coop(models.Model):
    objects = CoopManager()
    name = models.CharField(max_length=250, null=False)
    type = models.ForeignKey(CoopType, on_delete=None)
    address = AddressField(on_delete=models.CASCADE)
    enabled = models.BooleanField(default=True, null=False)
    phone = PhoneNumberField(null=True)
    email = models.EmailField(null=True)
    web_site = models.TextField()

Unfortunately, when the query actually gets created, it doesn't appear Django is doing anything to account for case-insensitivity.  This is an example query that results ...
SELECT `maps_coop`.`id`, `maps_coop`.`name`, `maps_coop`.`type_id`, `maps_coop`.`address_id`, `maps_coop`.`enabled`, `maps_coop`.`phone`, `maps_coop`.`email`, `maps_coop`.`web_site` FROM `maps_coop` WHERE (`maps_coop`.`name` LIKE %res% AND `maps_coop`.`enabled` = True)

What changes do I need to make so that Django executes the query in a case-insensitive way against my MySql database?
Edit: Here is the MySql output for "show create table ..."
| maps_coop | CREATE TABLE `maps_coop` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(250) COLLATE utf8_bin NOT NULL,
  `enabled` tinyint(1) NOT NULL,
  `phone` varchar(128) COLLATE utf8_bin DEFAULT NULL,
  `email` varchar(254) COLLATE utf8_bin DEFAULT NULL,
  `web_site` longtext COLLATE utf8_bin NOT NULL,
  `address_id` int(11) DEFAULT NULL,
  `type_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `maps_coop_address_id_f90898f3` (`address_id`),
  KEY `maps_coop_type_id_982652ce_fk_maps_cooptype_id` (`type_id`),
  CONSTRAINT `maps_coop_address_id_f90898f3_fk_address_address_id` FOREIGN KEY (`address_id`) REFERENCES `address_address` (`id`),
  CONSTRAINT `maps_coop_type_id_982652ce_fk_maps_cooptype_id` FOREIGN KEY (`type_id`) REFERENCES `maps_cooptype` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=933 DEFAULT CHARSET=utf8 COLLATE=utf8_bin |

A: You have to change the MySQL database/table collation to utf8_unicode_ci or utf_unicode_ci; the ci acronym at the end stands for "case insensitive".
Also check this Q/A utf8_bin vs. utf_unicode_ci.


text:
Q: Browser detection I need to separate IE and FF browsers from others
it's a pseudo-code :
If (CurrentBrowser == IE(6+) or FF(2+) )
{
...
}
else
{
...
}

in protected void Page_Load() event (think so)
if ((Request.Browser.Type == "IE") || (Request.Browser.Type == "FF"))
{
    WebMsgBox.Show("1111");
}

no effects :-/ what is IE and FF types?

A: if (Request.Browser.Type.Contains("Firefox")) // replace with your check
{
    ...
}
else if (Request.Browser.Type.ToUpper().Contains("IE")) // replace with your check
{
    if (Request.Browser.MajorVersion  < 7)
    {
        DoSomething();
    }
    ...
}
else { }

A: Here's a way you can request info about the browser being used, you can use this to do your if statement
System.Web.HttpBrowserCapabilities browser = Request.Browser;
    string s = "Browser Capabilities\n"
        + "Type = "                    + browser.Type + "\n"
        + "Name = "                    + browser.Browser + "\n"
        + "Version = "                 + browser.Version + "\n"
        + "Major Version = "           + browser.MajorVersion + "\n"
        + "Minor Version = "           + browser.MinorVersion + "\n"
        + "Platform = "                + browser.Platform + "\n"
        + "Is Beta = "                 + browser.Beta + "\n"
        + "Is Crawler = "              + browser.Crawler + "\n"
        + "Is AOL = "                  + browser.AOL + "\n"
        + "Is Win16 = "                + browser.Win16 + "\n"
        + "Is Win32 = "                + browser.Win32 + "\n"
        + "Supports Frames = "         + browser.Frames + "\n"
        + "Supports Tables = "         + browser.Tables + "\n"
        + "Supports Cookies = "        + browser.Cookies + "\n"
        + "Supports VBScript = "       + browser.VBScript + "\n"
        + "Supports JavaScript = "     +
            browser.EcmaScriptVersion.ToString() + "\n"
        + "Supports Java Applets = "   + browser.JavaApplets + "\n"
        + "Supports ActiveX Controls = " + browser.ActiveXControls
              + "\n";

MSDN Article

A: Try the below code
HttpRequest req = System.Web.HttpContext.Current.Request
string browserName = req.Browser.Browser;

A:     private void BindDataBInfo()
    {
        System.Web.HttpBrowserCapabilities browser = Request.Browser;
        Literal1.Text = "
";
        foreach (string key in browser.Capabilities.Keys)
        {
            Literal1.Text += "
" + key + "	" + browser[key] + "
";
        }
        Literal1.Text += "
";
        browser = null;
    }

A: I would not advise hacking browser-specific things manually with JS. Either use a javascript library like "prototype" or "jquery", which will handle all the specific issues transparently.
Or use these libs to determine the browser type if you really must.
Also see Browser & version in prototype library?

A: For browser compatibility you can use this code. This method returns browser name and version  :
private string GetBrowserNameWithVersion
{
    var userAgent = Request.UserAgent;
    var browserWithVersion = "";
    if (userAgent.IndexOf("Edge") > -1)
    {
        //Edge
        browserWithVersion = "Edge Browser Version : " + userAgent.Split(new string[] { "Edge/" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("Chrome") > -1)
    {
        //Chrome
        browserWithVersion = "Chrome Browser Version : " + userAgent.Split(new string[] { "Chrome/" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("Safari") > -1)
    {
        //Safari
        browserWithVersion = "Safari Browser Version : " + userAgent.Split(new string[] { "Safari/" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("Firefox") > -1)
    {
        //Firefox
        browserWithVersion = "Firefox Browser Version : " + userAgent.Split(new string[] { "Firefox/" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("rv") > -1)
    {
            //IE11
        browserWithVersion = "Internet Explorer Browser Version : " + userAgent.Split(new string[] { "rv:" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("MSIE") > -1)
    {
        //IE6-10
        browserWithVersion = "Internet Explorer Browser  Version : " + userAgent.Split(new string[] { "MSIE" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("Other") > -1)
    {
        //Other
        browserWithVersion = "Other Browser Version : " + userAgent.Split(new string[] { "Other" }, StringSplitOptions.None)[1].Split('.')[0];
    }

    return browserWithVersion;
}

A: I tried and found the solution for the same
        public static string GetBrowserDetails()
        {
          string  BrowserDetails = HttpContext.Current.Request.Browser.Browser + " - " + HttpContext.Current.Request.Browser.Version + ";  Operating System : " + HttpContext.Current.Request.Browser.Platform;
          return BrowserDetails;
        }

OUTPUT :
Chrome - 88.0; Operating System : WinNT

A: use from
Request.Browser

this link will help you :
Detect the browser using ASP.NET and C#


text:
Q: Wrapper TSQL Table-valued Function is slow I built a wrapper function that currently just calls another table-valued Function but it just added a huge amount to the execution time as Client processing time. Is there a faster way to do this?
Without wrapper:

With Wrapper:

Wrapper function:
CREATE FUNCTION [console].[getCalculosRequisita]
(

    @Disponivel BIGINT,
    @mediaDiaria float,
    @DiasStockArtigo INT,
    @DiasAntes INT,
    @SaidasPorMes float,
    @QtdEncomendada2Meses BIGINT,
    @StockAtual BIGINT,
    @QtdRequisitada BIGINT,
    @caixaMinima INT

)
RETURNS @tbl TABLE
(
    DiasAteRotura INT,
    AcaoRequisita varchar(10),
    Aconselhada BIGINT
)
AS
BEGIN

--future configuration check
--future log input

INSERT INTO @tbl SELECT DiasAteRotura, AcaoRequisita,Aconselhada
FROM [cartridge].[getCalculosRequisitaTSQL]
(
    @Disponivel ,
    @mediaDiaria ,
    @DiasStockArtigo ,
    @DiasAntes ,
    @SaidasPorMes ,
    @QtdEncomendada2Meses ,
    @StockAtual ,
    @QtdRequisitada ,
    @caixaMinima
)

--future log output

RETURN
END

GO

A: Do it as an inline TVF, which is much, much faster:
CREATE FUNCTION [console].[getCalculosRequisita]
(

    @Disponivel BIGINT,
    @mediaDiaria float,
    @DiasStockArtigo INT,
    @DiasAntes INT,
    @SaidasPorMes float,
    @QtdEncomendada2Meses BIGINT,
    @StockAtual BIGINT,
    @QtdRequisitada BIGINT,
    @caixaMinima INT
)
RETURNS TABLE -- WITH SCHEMABINDING  -- preferable, but then you can't change the underlying function
(
    DiasAteRotura INT,
    AcaoRequisita varchar(10),
    Aconselhada BIGINT
)
AS RETURN
(SELECT DiasAteRotura, AcaoRequisita, Aconselhada
FROM [cartridge].[getCalculosRequisitaTSQL]
(
    @Disponivel ,
    @mediaDiaria ,
    @DiasStockArtigo ,
    @DiasAntes ,
    @SaidasPorMes ,
    @QtdEncomendada2Meses ,
    @StockAtual ,
    @QtdRequisitada ,
    @caixaMinima
) AS t
);
GO

Obviously, if you do this then you cannot do any other inserts. In any case logging would be impossible, so I'm not sure what you were planning on doing.
You have not given the code for the underlying function. Perhaps that can be done as an iTVF also.

A: I really appreciate the replies. They were insightfull and I will upvote them all. I just post some code here for the sharing. Happy to hear your thougts if you have suggestions.
What I really wanted was to run Python from a View, I had to go complety for another direction and I think performance just went down the drain.
It seems Python runs only from Stored Procedures... so had to go for a OPENROWSET (!?) to have it as a VIEW. Not pretty, example below:
DROP PROC IF EXISTS PythonExample;
GO
CREATE PROC PythonExample
AS
BEGIN

set nocount on
SET FMTONLY OFF

    DROP TABLE [dbo].[MyRows]
    CREATE TABLE [dbo].[MyRows](
        [RowNum] [int] NULL
    ) ON [PRIMARY]

    INSERT INTO [MyRows]
        ([RowNum])
    VALUES
        (1),
        (2)

    DECLARE @tbl1 TABLE
    (
       COL1 INT,
       COL2 INT
    )

    INSERT INTO @tbl1

---ATTENTION Identing is important for Python code...
    EXEC sp_execute_external_script  @language =N'Python',
    @script=N'
import pandas as pd
df= MyInput
df["newCol"]= df["RowNum"]*2
MyOutput = df;
    ',
    @input_data_1_name = N'MyInput',
    @input_data_1 =N'SELECT [RowNum] FROM [MyRows]', --- it seems it cannot handle a temp table
    @output_data_1_name =N'MyOutput'
    --WITH RESULT SETS ((MyColName int, MyColName2 int));

    SELECT * FROM @tbl1
END;
GO

DROP VIEW IF EXISTS ViewExample;
GO
CREATE VIEW ViewExample
AS
    SELECT * FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;', 'exec [dbo].[PythonExample]')
GO

SELECT * FROM ViewExample


text:
Q: Finding a substring in a list of lists I have an issue and can't solve it, I have a dynamic list data (request data from web) that contains multiple lists, and each one contains strings, integers, etc., but I need the one which contains a specific text StreamCache. and just one and only one list in data contains the string StreamCache, which I store it in a new list. Almost all time my code works perfectly, but when it finds a list with a string like StreamCache@abnsdj12 or StreamCache*mljsgfn525, that are essentially the lists I need, my code doesn't work, just because StreamCache doesn't match exactly with StreamCache@kahsgsgh5 or so, I tried with list comprehension, regular expressions, but nothing works. Can someone help me?
These are my solutions:
# Works only if 'StreamCache' matchs exactly with the iterable
temp1 = [i for i in data if 'StreamCache' in i]
################ Solution 2 that doesn't work at all
search = 'StreamCache'
for element in data:
    if isinstance(element, list):
        new = [i for i in element]
        z = re.compile('|'.join(re.escape(k) for k in new))
        result = re.findall(z, search)

Hope you can help me with this.

A: You need to check if StreamCache is part of any string in the list, which you could do with something like this:
[l for l in data if any('StreamCache' in s for s in l)]

If StreamCache always occurs at the beginning of the string, this would be more efficient:
[l for l in data if any(s.startswith('StreamCache') for s in l)]

A: The 2nd approach you attempted only returns [StreamCache] because the content you searching in is only StreamCache and regex object is <element 1>|<element 2>|...., did you mean to find the StreamCache.* string inside an string like below example?
a|abc|StreamCache*mljsgfn777|123|StreamCache|aweafwfa|asfwqwdq|StreamCache@abnsdj12|somestring|StreamCache*mljsgfn525

If so, I think you got the argument reverse by mistake, which the regex object is the first parameter and the search content is the second parameter. Below is an example that seems to provide the expected result for me
search = 'a|abc|StreamCache*mljsgfn777|123|StreamCache|aweafwfa|asfwqwdq|StreamCache@abnsdj12|somestring|StreamCache*mljsgfn525' # search content
z = re.compile('StreamCache[^|]*|') # regex object
search_result = list(filter(lambda x: x, re.findall(z, search))) # use filter to remove empty strings
# search_result here would contain ['StreamCache*mljsgfn777', 'StreamCache', 'StreamCache@abnsdj12', 'StreamCache*mljsgfn525']


text:
Q: Git Install Mac Stuck Verification When I open the .pkg file I downloaded from git, to install git on my machine I'm stuck on this screen
Any idea how to force this verification/bypass? I already have XCode and the Command Line Tools installed.

A: The only thing I can think off the top of my head is system preferences like security or browser. I have a mac also and I used to try to download some things and it wouldnt let me until I set I think my browser preferences to allow anything.

A: Seems like it's a bug with 10.11.4, upgrading to 10.11.5 fixed the issue :)

A: I had (what I assume is) the same problem, although with VirtualBox instead of git.  As suggested here, I ran /System/Library/CoreServices/Installer.app explicitly, and "pointed it" at the .pkg file on the mounted dmg; that worked fine.