text:
Q: jquery: How to stop html anchors moving the document? I have about 40 links which are all handled within jquery but when they are clicked it moves the page position to the top. Is there a better way to stop this happening without giving each one an event handler then doing e.preventDefault() ? Even if I could just include it in the function that is executed without doing return false as that never seems to work for me.

A: Rather than applying e.preventDefault to each one individually, you can apply it to them all in one function by using jQuery's powerful matching features.
This code will match all <a> tags with their href attribute set to #.
$("a[href='#']").click(function(e) {
    e.preventDefault();
});


text:
Q: I want to redirect an SEO friendly URL to a non-SEO friendly but keep the URL SEO friendly I hope you can help me.  I'm trying to create a URL rewrite, redirect, or combination of the two in a .htaccess file, but I don't know how.  It's kinda hard to find anything definitive on URL rewrites.
Basically, I want the user to be able to type in a SEO friendly URL (just one level) and have that sent to a page where I can do a $_GET['data'] and do a mysql query and serve up a web page.  I don't want the URL the user sees to change though so I'm not sure if I need to redirect it back to the SEO friendly or if it can just stay the same SEO friendly version.
Here's my example:
The user would type in this URL:
www.mysite.com/cars
somehow, that would be either redirected or rewritten as:
www.mysite.com/getpage.php?page=cars
but the URL stays the same:
www.mysite.com/cars
I'm pretty sure this is a URL rewrite or redirect or a combination of the two but I have no idea how to write the rewrite rules.  I
Any assistance you can offer would be extremely helpful!
Thanks
Keyogee

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to wrap a HTML tag around placeholders using a regular expression? My input text looks like this:
something [something] some text [other] some [other] text

It contains "placeholders" that are wrapped in square brackets and I want to wrap them in html   tags.
The output should look like this:
something [something] some text [other] some [other] text

A: You may try the following regex replacement:

var input = "something [something] some text [other] some [other] text";
var output = input.replace(/(\[.*?\])/g, "$1");
console.log(input);
console.log(output);


text:
Q: how to increase the performance of loading an image from url i m loading an image from an url and displaying it in imageView .i m using NSBLockOperation to load the image and it  runs in the background and it takes time to load the image in imageview..is there any way to increase the performance so that it takes less time..below is the code.
NSOperationQueue *queue=[[NSOperationQueue alloc]init];
NSBlockOperation *operation=[NSBlockOperation blockOperationWithBlock:^{

    [activityIndicator startAnimating];
    NSString *imagefile = [banner1 objectAtIndex:0];
    NSURL *url1=[NSURL URLWithString:imagefile];
    NSData *data = [NSData dataWithContentsOfURL:url1];
    UIImage *ui=[[UIImage alloc]initWithData:data];
    bigbanner.image=ui;
    [activityIndicator stopAnimating];
    bigbanner.alpha=0.0;

}];
[operation setCompletionBlock:^{
    [UIView animateWithDuration:3.0 animations:^{bigbanner.alpha=2.0;}
                     completion:^(BOOL finished){}];
}];

[queue addOperation:operation];

A: I would guess that your limiting factor is the image download.
Loading an image and placing it on screen happens quite fast on iOS.
Other than changing your three second fade-in to a shorter interval, I think you're stuck.
You might try doing the download using [NSURLRequest], but I doubt you'll notice a major difference.
I'd say your options are (ranked in order of speed):

*

*cache or include images in your bundle (don't download).

*make your images smaller

*increase the speed of your server

Also: a side note, and hopefully someone else passing through can answer this... is setting the image property of a UIImageView from a non-main-thread safe to do? I was under the impression that everything that happened to the UI was supposed to happen on the main thread.

A: Give ASIHTTPRequest a try, just maybe loading image asynchrony in the background can improve speed when loading several images at the same time, checkout ASINetworkQueue
Didn't try it but here it is:
#import "ASIHTTPRequest.h"
#import "ASINetworkQueue.h"

-(void)loadImages
{
    ASINetworkQueue * asiNetworkQueue = [ASINetworkQueue queue];
    [asiNetworkQueue setDelegate:self];
    [asiNetworkQueue setShouldCancelAllRequestsOnFailure:NO];

    for(int i=0; i < 20; i++)
    {
        NSURL *url = [NSURL URLWithString:@"some_url"];

        ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
        [request setDidFinishSelector:@selector(imageRequestFinished:)];
        [request setUserInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:i] forKey:@"id"]];
    }
    [asiNetworkQueue go];
}

-(void)imageRequestFinished:(ASIHTTPRequest *)request
{

    UIImage* image = [UIImage imageWithData:[request responseData]];

    //Use the id to match the request with a specific UIImageView
    int imageId = [request.userInfo objectForKey:@"id"];
    //imageViewArray[imageId].image = image;
}

//------------------------------------
EDIT - Loading a single image
//------------------------------------
-(void)loadImage:(NSString*)imagePath
{
    //_activityIndicator.hidden = FALSE;
    //[_activityIndicator startAnimating];
    NSURL*imageURL = [NSURL URLWithString:imagePath];

    ASIHTTPRequest* request = [[[ASIHTTPRequest alloc] initWithURL:imageURL] autorelease];

    [request setDidFailSelector:@selector(requestDidFailed:)];
    [request setDidStartSelector:@selector(requestDidStarted:)];
    [request setDidFinishSelector:@selector(requestDidFinished:)];
    [request setDelegate:self];
    [request startAsynchronous];

}

- (void)requestDidFinished:(ASIHTTPRequest *)request
{
    //_activityIndicator.hidden = TRUE;
    //[_activityIndicator stopAnimating];
    self.imageView.image = [UIImage imageWithData:[request responseData]];

    // NSLog(@"image download finished");
}

- (void)requestDidFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    //NSLog(@"Loading Image Failed");
    //_activityIndicator.hidden = TRUE;
    //[_activityIndicator stopAnimating];
}

- (void)requestDidStarted:(ASIHTTPRequest *)request
{
    //NSLog(@"image download started");
}

A: As others have mentioned there's not much that you can do if the limiting resource is network speed. If the files aren't too large (and they don't look to be) you could preload them before the user reaches the page. For example, if there's only a few banners you could start loading all of them right when the app starts. If there's too many to do that you could try making educated guesses - e.g. If the user lands on a screen that can only lead him to 4 possible banners start downloading them all when the user lands on that screen in preparation for when they make their selection. Finally you should cache the banners once downloaded so you only have to pay for the network access once.
Hope that helps.


text:
Q: Python UDP socket don't work after making first connection I am traing to make simple application on python that works with sockets and use UDP protocol. I have a client.py and server.py. I whant to send messages from client to server in infinity loop and catch resive message from server. For making this I have following code:
server.py
import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 8000
print(host)
print(port)
serversocket.bind((host, port))

serversocket.listen(5)
print('server started and listening')
while 1:
    (clientsocket, address) = serversocket.accept()
    print("connection found!")
    data = clientsocket.recv(1024).decode()
    print(data)
    r = 'I can hear you by UDP!!!!'
    clientsocket.send(r.encode())

client.py
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 8000
addr = (host, port)
s.connect(addr)

def send(user_input):
    s.sendto(user_input.encode(), addr)
    data = s.recv(1024).decode()
    print('Server tell that: ', data)

while 1:
    if input('Exit? (y/n)') == 'y':
        break
    i = input('>> ')
    send(i)

s.close()

It's work correctly, but when i try to send message second time, my program make stop on line
s.sendto(user_input.encode(), addr)

I don't understand what's happening in this moment.

A: If you'd like to build server/client for UDP, you need to read the documents carefully to prevent from using the APIs which are for connection-oriented protocols.
Below is one working sample for UDP: (I added some comments in the codes, then you will see why adjusted them).
Server:
For one UDP server, you need to initialize with one socket socket.SOCK_DGRAM instead of SOCK_STREAM, then bind the port you'd like.
import socket

#The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
serversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = "127.0.0.1"
port = 8000
print(host)
print(port)
serversocket.bind((host, port))

#serversocket.listen(5)  #--This method sets up and start TCP listener.
print('server started and listening')
while 1:
    #(clientsocket, address) = serversocket.accept() #---This passively accept TCP client connection, waiting until connection arrives (blocking)
    #print("connection found!")
    #data = clientsocket.recv(1024).decode() #This method receives TCP message
    data, addr = serversocket.recvfrom(2048)
    print(data)
    r = 'I can hear you by UDP!!!!'
    serversocket.sendto(r.encode(), addr)
serversocket.close()

Client:
For one UDP client, you need to initialize one socket with socket.SOCK_DGRAM instead of SOCK_STREAM, then uses sendto to send the data to the server.
import socket
#The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = "127.0.0.1"
port = 8000
addr = (host, port)
#s.connect(addr) #---This method actively initiates TCP server connection.

def send(user_input):
    s.sendto(user_input.encode(), addr)
    data = s.recvfrom(1024).decode()
    print('Server tell that: ', data)

while 1:
    if input('Exit? (y/n)') == 'y':
        break
    i = input('>> ')
    send(i)

s.close()

For more details:
Check Python Socket


text:
Q: Clob size in bytes I have a database with the below NLS settings
NLS_NCHAR_CHARACTERSET  - AL16UTF16

NLS_CHARACTERSET - AL32UTF8

There's a table with a clob column storing a base64 encoded data.
Since the characters are mostly english and letters, I would assume each character takes up 1 byte only as clob using the charset of NLS_CHARACTERSET for encoding.
With a inline enabled clob column, the clob will be stored inline unless it goes more that 4096 bytes in size. However, when I tried to store a set of data with 2048 chars, I found that it is not stored inline (By checking the table DBA_TABLES).  So does it mean each character is not using only 1 byte? Can anyone elaborate on this?
Another test added:
Create a table with clob column with chunk size 8kb so that initial segment size is 65536 bytes.
After insert a row with 32,768 chars in clob column. The 2nd extent creation can be told by querying dba_segments.

A: http://docs.oracle.com/cd/E11882_01/server.112/e10729/ch6unicode.htm#r2c1-t12
It says:

Data in CLOB columns is stored in a format that is compatible with
  UCS-2 when the database character set is multibyte, such as UTF8 or
  AL32UTF8. This means that the storage space required for an English
  document doubles when the data is converted

So it looks like CLOB internally stores everything as UCS-2 (Unicode), i.e. 2 bytes fixed per symbol. Consequently, it stores inline 4096/2 = 2048 chars.


text:
Q: Launching Chrome with .bat file with specific scroll-down This is a follow-up question to Launching 2 Google Chrome windows in different positions and Launch Google Chrome from the command line with specific window coordinates.
Apart from what has already been said in those 2 posts, I am wondering if there is a command I can add to a batch file which allows me to open a new Chrome window scrolled down to a specific position, or by a specific "amount".
I have checked this page and this page but have not found anything.

A: Here I use sendkeys after opening chrome to open the console, focus on the console, and input some javascript to scroll 100px down.
@if (@CodeSection == @Batch) @then
@echo off

rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"

rem Start the other program in the same Window
call "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.sendkeys.send?view=netframework-4.8
timeout /t 2
%SendKeys% "^(+({J}))"
timeout /t 2
%SendKeys% "^(`)"
%SendKeys% "window.scrollBy{(}0, 100{)};~"

goto :EOF

@end
// JScript section

var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));


text:
Q: Main activity class of loaded Dynamic feature is not found I am trying to add dynamic feature support to  my app, so I created a test app.
The test app has a main app part that loads a dynamic feature and try to execute it.
The feature module has MainActivityCalled as main activity.
What I get is that the feature loading process works because I get successful log messages, and I get the list of installed modules.
Note that the app is run on a virtual device and no real download happens, I thinks everything gets installed automatically by deployment procedure from AndroidStudio.
The fact is that I get this kind of error when trying to call the main activity of the module:
W/System.err: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.dynamicfeature1/MainActivityCalled}; have you declared this activity in your AndroidManifest.xml?
W/System.err:     at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
    at android.app.Activity.startActivityForResult(Activity.java:4225)
    at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
    at android.app.Activity.startActivityForResult(Activity.java:4183)
    at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
    at android.app.Activity.startActivity(Activity.java:4522)
    at android.app.Activity.startActivity(Activity.java:4490)
    at com.example.mymodules.MainActivity$2.onClick(MainActivity.java:227)
    at android.view.View.performClick(View.java:5637)
    at android.view.View$PerformClick.run(View.java:22429)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)

Everything is done as in the documentation at https://developer.android.com/guide/app-bundle/playcore#java
except for the explicit call to the module activity that I guessed has to be performed with an intent (no example in the above linked page).
Important part of the code you find below are:
new OnSuccessListener<Integer>() {
                        @Override
                        public void onSuccess(Integer result) {
                            Log.d("request feature load","success "+result);
                            mySessionId=result;
                            Set<String> installedModules = splitInstallManager.getInstalledModules();
                            String[] modules = new String[installedModules.size()];

                            installedModules.toArray(modules);
                            for (int i=0;i<modules.length;i++)
                            {
                                Log.d("module",modules[i]);
                            }

                        }
                    })

that is OK.
Then
Button button2 = findViewById(R.id.fab2);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Log.d("feature1","called");
            Intent intent=new Intent();
            intent.setClassName("com.example.dynamicfeature1","MainActivityCalled");

            try{  startActivity(intent);}
            catch (Exception e){
                e.printStackTrace();
            }

        }
    });

All main activities has this overidden method
@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    // Emulates installation of on demand modules using SplitCompat.
    SplitCompat.installActivity(this);
    Log.d("attachBaseContext",base.getPackageName().toString());
}

that is not called in the dynamic feature module when installed.
What is wrong with my code?
This is the Mainactivity of the app
package com.example.mymodules;

...imports...

public class MainActivity extends AppCompatActivity {
private static int MY_REQUEST_CODE=1;
Activity activity;
int mySessionId;

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    // Emulates installation of future on demand modules using SplitCompat.
    SplitCompat.install(this);
 Log.d("attachBaseContext",base.getPackageName().toString());

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == MY_REQUEST_CODE) {
        // Handle the user's decision. For example, if the user selects "Cancel",
        // you may want to disable certain functionality that depends on the module.
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    activity = this;
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Button button1 = findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Creates an instance of SplitInstallManager.
            final SplitInstallManager splitInstallManager =
                    SplitInstallManagerFactory.create(activity);

// Creates a request to install a module.
            SplitInstallRequest request =
                    SplitInstallRequest
                            .newBuilder()
                            // You can download multiple on demand modules per
                            // request by invoking the following method for each
                            // module you want to install.
                            .addModule("dynamicfeature1")

                            .build();

// Creates a listener for request status updates.
            SplitInstallStateUpdatedListener listener =new SplitInstallStateUpdatedListener() {
                @Override
                public void onStateUpdate(SplitInstallSessionState state) {
                    if (state.status() == SplitInstallSessionStatus.REQUIRES_USER_CONFIRMATION) {
                        // Displays a dialog for the user to either "Download"
                        // or "Cancel" the request.
                        try {
                            splitInstallManager.startConfirmationDialogForResult(
                                    state,
                                    /* activity = */ activity,
                                    // You use this request code to later retrieve the user's decision.
                                    /* requestCode = */ MY_REQUEST_CODE);
                        } catch (IntentSender.SendIntentException e) {
                            e.printStackTrace();
                        }
                    }

                    if (state.sessionId() == mySessionId) {
                        switch (state.status()) {

                            case SplitInstallSessionStatus.INSTALLED:
                                Context tempNewContext=null;
                                try {
                                    tempNewContext = activity.createPackageContext(activity.getPackageName(), 0);
                                } catch (PackageManager.NameNotFoundException e) {

                                }
                                final Context newContext =tempNewContext;
                                // If you use AssetManager to access your app's raw asset files, you'll need
                                // to generate a new AssetManager instance from the updated context.
                                AssetManager am = newContext.getAssets();

                                if (BuildCompat.isAtLeastO()) {
                                    // Updates the app's context with the code and resources of the
                                    // installed module.
                                    SplitInstallHelper.updateAppInfo(newContext);
                                    new Handler().post(new Runnable() {
                                        @Override public void run() {
                                            // Loads contents from the module using AssetManager
                                            AssetManager am = newContext.getAssets();

                                        }
                                    });
                                } else
                                {SplitInstallHelper.updateAppInfo(newContext);}

                        }
                    }
                }

            } ;
            splitInstallManager.registerListener(listener);
            splitInstallManager
                    // Submits the request to install the module through the
                    // asynchronous startInstall() task. Your app needs to be
                    // in the foreground to submit the request.
                    .startInstall(request)
                    // You should also be able to gracefully handle
                    // request state changes and errors. To learn more, go to
                    // the section about how to Monitor the request state.
                    .addOnSuccessListener(new OnSuccessListener<Integer>() {
                        @Override
                        public void onSuccess(Integer result) {
                            Log.d("request feature load","success "+result);
                            mySessionId=result;
                            Set<String> installedModules = splitInstallManager.getInstalledModules();
                            String[] modules = new String[installedModules.size()];

                            installedModules.toArray(modules);
                            for (int i=0;i<modules.length;i++)
                            {
                                Log.d("module",modules[i]);
                            }

                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        void checkForActiveDownloads() {
                            splitInstallManager
                                    // Returns a SplitInstallSessionState object for each active session as a List.
                                    .getSessionStates()
                                    .addOnCompleteListener(
                                            new OnCompleteListener<List<SplitInstallSessionState>>() {
                                                @Override
                                                public void onComplete(Task<List<SplitInstallSessionState>> task) {
                                                    if (task.isSuccessful()) {
                                                        // Check for active sessions.
                                                        for (SplitInstallSessionState state : task.getResult()) {
                                                            if (state.status() == SplitInstallSessionStatus.DOWNLOADING) {
                                                                // Cancel the request, or request a deferred installation.
                                                            }
                                                        }
                                                    }
                                                }

                                            });
                        }

                        @Override
                        public void onFailure(Exception e) {
Log.d("request feature load","failure "+e.getMessage());
                            switch (((SplitInstallException) e).getErrorCode()) {
                                case SplitInstallErrorCode.NETWORK_ERROR:
                                    // Display a message that requests the user to establish a
                                    // network connection.
                                    break;
                                case SplitInstallErrorCode.ACTIVE_SESSIONS_LIMIT_EXCEEDED:
                                    checkForActiveDownloads();
                            }

                        }
                    });

        }
    });
   Button button2 = findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d("feature1","called");
 Intent intent=new Intent();
            intent.setClassName("com.example.dynamicfeature1","MainActivityCalled");

            try{  startActivity(intent);}
            catch (Exception e){
                e.printStackTrace();
            }

        }
    });
   Button button3 = findViewById(R.id.button3);
    button3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d("feature2","called");
        }
    });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

here's the main app manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.example.mymodules">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:name="com.google.android.play.core.splitcompat.SplitCompatApplication"
android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>
</manifest>

Then there is the MainActivity of the dyamic feature module
package com.example.dynamicfeature1;

...imports...

public class MainActivityCalled extends AppCompatActivity {
@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    // Emulates installation of on demand modules using SplitCompat.
    SplitCompat.installActivity(this);
    Log.d("attachBaseContext",base.getPackageName().toString());
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "1-Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

}

and the module manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.example.dynamicfeature1">

<dist:module
    dist:instant="false"
    dist:title="@string/title_dynamicfeature1">
    <dist:delivery>
        <dist:on-demand />
    </dist:delivery>

    <dist:fusing dist:include="false" />
</dist:module>

<application>
    <activity
        android:name=".MainActivityCalled"
        android:label="@string/title_activity_main"
        android:theme="@style/AppTheme.NoActionBar"></activity>
</application>

</manifest>

A: The right instruction to call the activity is
intent. setClassName(BuildConfig.APPLICATION_ID, "com.example.dynamicfeature.MainActivityCalled");

It works, the activity gets called.
Note that BuildConfig.APPLICATION_ID is
com.example.mymodules

If this string is used in the dynamic modules too, you can make cross-calls:
-from one module to another
-from one module to the main app
but you do not want to use BuildConfig.APPLICATION_ID in modules because there it is a different value, so the main string value has to be put into a variable.


text:
Q: Creating a right mouse button click event handler I'd like to have a certain event handler to work when I press my ImageButton control by the right mouse button. How can I achieve this? I use asp.net.

A: You must use client side technique to catch it, for example js/Jquery. Something like
<script type="text/javascript"> $(function () { $("#ImageButton").mousedown(function (e) {
 if (e.which == "3") {
// Do magic.
} }) }); </script>


text:
Q: CSS transitions not applying when switching a div's CSS classes (no keyframe method) I have a component called "FadeImage" who's purpose is to cross-fade two images smoothly when the current index changes (current index and previous index are supplied by props). Two images are stacked on one another. The bottom-layer image becomes the current image index, and the top-layer image becomes the 'previous' image, is faded away by switching its CSS class to a class with an opacity of 0 after a 200ms delay.
The images indeed have their new CSS class selector applied (I set the top image to only fade to 50%, and it does do that, but with no transition to opacity).
I think I may be misunderstanding something about how and when the transition of a CSS property is applied.
I am using ChakraUI (<Box> is a div, <Image> is an <img>, etc.) for easier CSS styling:
FadeImage.tsx
const FadeImage = (props) => {
        let prev:number = props.prevImageIndex;
        let current:number = props.currentIndex;
        return(
            <Box>
            {sliderData[current] &&
                <Image

                    position={'absolute'}
                    minH={sliderHeight}
                    maxH={sliderHeight}
                    w={'100%'}
                    objectFit='cover'
                    src={sliderData[current].image ?? ''}
                    alt='banner image' />}

            {sliderData[prev] ? (

        <Box>
                <Text className="DEBUG" zIndex={125} position='absolute' right='50%'>
                    {bottomOpacity}
                </Text>

            <Image
                className={bottomOpacity ? 'transition1' : 'transition'}
                position={'absolute'}
                minH={sliderHeight}
                maxH={sliderHeight}
                w={'100%'}
                objectFit='cover'
                src={sliderData[prev].image ?? ''}
                alt='banner image' />
        </Box>
            ) : <Box/>
                }

        </Box>
        );
    }

The two classes associated with the second image are simple,  when bottomOpacity is 1 it applies the first class 'transition1' which has an opacity of 1, and after a delay in the parent component, it sets it to the second selector with an opacity of 0. I tried switching the classname to be applied to a parent div of the image instead, that didn't work. I also tried directly altering the 's opacity css rule by using opacity={bottomOpacity ? 1 : 0 } which also did not work. I also tried including the transition rule inside the Image props xor a parent div.
globals.css
.transition1 {
  transition: transform 15s ease, opacity 2s ease;
  opacity: 1!important;
}
.transition {
  transition: transform 15s ease, opacity 2s ease;
  opacity: 0!important;
}

And below is the main component that I whittled down into just the essentials
Slider.tsx

export default function Slider(){
    const [current, setCurrent] = useState(0);
    const [oldIndex, setOldIndex] = useState(0);
    const [bottomOpacity, setBottomOpacity] = useState(0);

    useInterval(() => {
        nextSlide();
    }, 4500);

    const nextSlide = () => {
        setOldIndex(current);
        setCurrent(current < length - 1 ? current + 1: 0);
        setBottomOpacity(1);
        const timer = setTimeout(() => {
            setBottomOpacity(0);
          }, 200);
          return () => clearTimeout(timer);
    }

    return( <Box> <FadeImage prevImageIndex={oldIndex} currentIndex={current} bottomOp={bottomOpacity} /> </Box>
}


text:
Q: Nested Ternary Implicit type Conversion issue: Type of conditional expression cannot be determined because there is no implicit conversion between I have used nested ternaries in the past quite frequently with c#. After I introduced An event handler, as the assignment operation, I was presented with the error: "Type of conditional expression cannot be determined because there is no implicit conversion between 'void' and 'void'"
Here are two snippets of the code I am writing, the top one is functional and the bottom one gives the type conversion error:
   AppTableConfigCollection collection =
            tableType == TableType.Attribute
                ? _attributeTableConfigs = new AppTableConfigCollection(_db, AppTableConfigCollection.ATTRIBUTE)
                    : tableType == TableType.Core
                        ? _coreTableConfigs = new AppTableConfigCollection(_db, AppTableConfigCollection.CORE)
                        : tableType == TableType.Domain
                            ?_domainTableConfigs = new AppTableConfigCollection(_db, AppTableConfigCollection.DOMAIN)
                            : tableType == TableType.Configuration
                                ?_configTableConfigs = new AppTableConfigCollection(_db, AppTableConfigCollection.CONFIG)
                                    :_offlineTableConfigs = new AppTableConfigCollection(_db, AppTableConfigCollection.OFFLINE);

        PropertyChangedEventHandler property =
            tableType == TableType.Attribute
                ? _attributeTableConfigs.PropertyChanged += new PropertyChangedEventHandler(appTableConfigs_PropertyChanged)
                : tableType == TableType.Core
                    ? _coreTableConfigs.PropertyChanged += new PropertyChangedEventHandler(appTableConfigs_PropertyChanged)
                    : tableType == TableType.Domain
                        ? _domainTableConfigs.PropertyChanged += new PropertyChangedEventHandler(appTableConfigs_PropertyChanged)
                        : tableType == TableType.Configuration
                            ? _configTableConfigs.PropertyChanged += new PropertyChangedEventHandler(appTableConfigs_PropertyChanged)
                                : _offlineTableConfigs.PropertyChanged += new PropertyChangedEventHandler(appTableConfigs_PropertyChanged);

Thank you for any help you are able to provide!

A: First of all, do listen to the commenters. Switch/case really does seem like it would result in more readable, maintainable code.
Second of all, what you are trying to do in your second code snippet is set your property changed handler to the result of subscribing to a handler, which is void.
Specifically, _attributeTableConfigs.PropertyChanged += new PropertyChangedEventHandler(appTableConfigs_PropertyChanged) does not return a value--it returns void. So, you're assignment is not possible.
You must do what you're trying to do in separate steps.
For example:
PropertyChangedEventHandler handler;
switch (tableType)
{
    case TableType.Attribute:
        handler = new PropertyChangedEventHandler(appTableConfigs_PropertyChanged);
        _attributeTableConfigs.PropertyChanged += handler;
        break;
    case TableType.Core:
        handler = new PropertyChangedEventHandler(appTableConfigs_PropertyChanged);
        _coreTableConfigs.PropertyChanged += handler;
        break;
    case TableType.Domain:
        handler = new PropertyChangedEventHandler(appTableConfigs_PropertyChanged);
        _domainTableConfigs.PropertyChanged += handler;
        break;
    case TableType.Configuration:
        handler = new PropertyChangedEventHandler(appTableConfigs_PropertyChanged);
        _configTableConfigs.PropertyChanged += handler;
        break;
    default:
        handler = new PropertyChangedEventHandler(appTableConfigs_PropertyChanged);
        _offlineTableConfigs.PropertyChanged += handler;
        break;
}

Or, if the handler is always the same:
PropertyChangedEventHandler handler = appTableConfigs_PropertyChanged;
switch (tableType)
{
    case TableType.Attribute:
        _attributeTableConfigs.PropertyChanged += handler;
        break;
    case TableType.Core:
        _coreTableConfigs.PropertyChanged += handler;
        break;
    case TableType.Domain:
        _domainTableConfigs.PropertyChanged += handler;
        break;
    case TableType.Configuration:
        _configTableConfigs.PropertyChanged += handler;
        break;
    default:
        _offlineTableConfigs.PropertyChanged += handler;
        break;
}

A: I would suggest using a switch statement as it is easier to read and update
switch (tableType)
        {
            case TableType.Attribute:
                _attributeTableConfigs = new AppTableConfigCollection(_db, AppTableConfigCollection.ATTRIBUTE);
                _attributeTableConfigs.PropertyChanged += new PropertyChangedEventHandler(appTableConfigs_PropertyChanged);
                break;
            case TableType.Core:
                _coreTableConfigs = new AppTableConfigCollection(_db, AppTableConfigCollection.CORE);
                _coreTableConfigs.PropertyChanged += new PropertyChangedEventHandler(appTableConfigs_PropertyChanged)
                break;
            case TableType.Domain:
                _domainTableConfigs = new AppTableConfigCollection(_db, AppTableConfigCollection.DOMAIN);
                _domainTableConfigs.PropertyChanged += new PropertyChangedEventHandler(appTableConfigs_PropertyChanged)
                break;
            case TableType.Configuration:
                _configTableConfigs = new AppTableConfigCollection(_db, AppTableConfigCollection.CONFIG);
                _configTableConfigs.PropertyChanged += new PropertyChangedEventHandler(appTableConfigs_PropertyChanged)
                break;
            default:
                _offlineTableConfigs = new AppTableConfigCollection(_db, AppTableConfigCollection.OFFLIINE);
                _offlineTableConfigs.PropertyChanged += new PropertyChangedEventHandler(appTableConfigs_PropertyChanged);
                break;
        }


text:
Q: How to properly clear the cache on Awesomium.NET WPF 1.7.1 while running My WebControl is defined in XAML like so
<aw:WebControl Source="http://google.com" Name="wpfWebControl"/>
I found this, and attempted to follow it's instructions by disposing the WebSession and views, like this
        var webSession = this.wpfWebControl.WebSession;
        this.wpfWebControl.Dispose();
        webSession.Dispose();
        WebCore.Update();

then tried to delete the directory where the cache was stored with a simple
Directory.Delete(WEBSESSION_CACHE_PATH), true);
where WEBSESSION_CACHE_PATH is the directory where the cache files are stored.
I encounter an UnauthorizedAccessException, therefore the files are still in use. Not only that, if I dispose my WebControl, the screen goes blank, and restoring it with
this.wpfWebControl = new WebControl() won't work either.
How am I supposed to do this?

A: A WebSession.ClearCache has been added in v1.7.2.


text:
Q: "How many public playgrounds exist in the United States?" How to answer using statistics and probability I have a goal of estimating how many public playgrounds exist in the United States.
There are many methods of gathering real data about playgrounds, but, unfortunately, there is no single authority that can answer this question or provide a comprehensive list.
Contacting every city in the nation would be too prohibitive, and other options such as working with regional park & rec departments have proven to show how little information those departments have. (Edit: I should also note that parks != playgrounds, but playgrounds may be contained inside parks).
This problem is akin to the old interview question: How many gas stations are there in Los Angeles?
How would one go about constructing a valid estimate on the total number of public playgrounds in the United States, with a margin of error <= 5%?
Can the community think of such a methodology that is purely grounded in math?
If you propose a solution, can you calculate what your result is for comparison with the others?

A: If you really want 5% error bounds, you will have to survey a bunch of cities.  The interview question generally accepts more like a factor of 2 to 5, even factor 10  error.  Then you can make rough but reasonable estimates and hope to be OK.
For playgrounds I would do the following:  there are about 3E8 people in the US.  About 10% are of playground age (say 4-12), so 3E7.  Weekends are probably the most popular time-say 25% of the children go for 1 hour each out of 12 hours available.  Then at any one time there are 625,000 children at the playground.  If a playground can handle 50 children, you need 12,500 playgrounds.  Feel free to come up with your own numbers-I made them up very quickly.  If anything, I suspect this is high in the number of children, but many playgrounds are not that busy.


text:
Q: Fastest way to multiply large numbers in python? Take a look at the following code:
total = 0
for j in range(int(start)-1,int(end)):
    total += (A+j)*(B+j)*(C+j)*(D+j)
print(total%1000000007)

Now the code is working fine but I need to reduce the time complexity.
1<=A,B,C,D<=10^5
1<=start<=end<=10^5
As you can see the numbers can be very large.
How can I speed up the multiplication part?
I tried Russian Peasant technique. It is still not fast enough.
Also I read similar posts on python multiplication but it couldn't solve my issue.

A: You can use modular arithmetic here.
(a+b)%c=(a%c+b%c)%c

(a∗b)%c=((a%c)∗(b%c))%c

(a−b)%c=((a%c)−(b%c)+c)%c

(a/b)%c=((a%c)∗(b−1%c))%c

This will ensure integer overflow as well as keep time complexity in check.

A: I think for this, it would be enough to remember that (a+b)%c = a%c +b%c
Since each part of the loop isn't very big you can try:
total = 0
for j in range(int(start)-1,int(end)):
    total = (total + (A+j)*(B+j)*(C+j)*(D+j)) %1000000007
print(total)


text:
Q: Is there a better way to write this query to short-circuit the 2nd condition? The following is similar to a query I have that needs to cast a field to a type and evaluate it, and I want to ignore rows that have data that cannot be cast to the target data type.
select * from MyTable
where case when isnumeric(SomeField) = 1 then SomeField else null end > 1

So in the above example I am able to test for values greater than one while avoiding the conversion error that would be caused if there were any non-numeric fields in the SomeField.  I'm okay with this solution, but I'm just wondering if there's a better way to do it?

A: I get an error "Maximum integer value exceeded" using the where criteria in your query.  Though, there are some very large numbers in my database, perhaps that doesn't come into play for you.
An alternative that handles large numbers is listed below:
where isnumeric(SomeField) = 1 and convert(numeric(18,0),SomeField) > 1

The isnumeric() check must come before the convert().
Performance wise they're about the same.

A: I've come to the conclusion that there's not a better way to do this.


text:
Q: Set ColdFusion variables in JS for use in jQuery? I am trying to toggle a dynamic number of divs if a user clicks a little pencil glyph. I'm setting the IDs for the glyph and the hidden divs as "pencilX" and "hiddenY" where X and Y correspond to the autoincrementing ID as stored in the database. Here is the code I have:
I will loop through the query of items in the table outputting this code for each item, so that the user can click a different pencil for each item and it will show toggle the div containing the info for that item.
My research so far is pointing me in the direction of having to use AJAX, but I don't understand AJAX very well and I'm wondering if it's really necessary here. I know I can't access the CF variables directly from jQuery, so I'm wondering if I can just set the variables in JS from the CF side before it hits the client, as I am trying to do below. But of course it isn't working!
I have also tried using the ToScript function which isn't working either. jQuery doesn't seem to recognize either.
<cfoutput>
<!---Query huddle item, set div ID--->
<cfquery name="huddleItem" datasource="LPKCMA">
    SELECT *
    FROM CMA_COMM_HDDL
    WHERE ID = 1
</cfquery>
<cfset pencilID = "##pencil" & huddleItem.ID>
<cfset hiddenID = "##hidden" & huddleItem.ID>
<!---Div toggle--->
<script type="text/javascript" language="JavaScript">
<!--- Didn't work
    var #toScript(pencilID, "pencil")#;
    var #toScript(hiddenID, "hidden")#;
--->
    var pencil = '#pencilID#';
    var hidden = '#hiddenID#';

    $(document).ready(function(){
        $('#' + pencil).click(function(){
            $('#' + hidden).toggle('fast');
        });
    });
</script>
<!--- Content below including pencil and div... --->


text:
Q: how to get post value from multiple array in yii2 I want to get value of post array in yii2,
I have array like this
[Brand] => Array
                (
                    [name] => Array
                        (
                            [0] => testing
                            [1] => jkhkjhjkhjk
                        )

                    [tagline] => Array
                        (
                            [0] => kjhjkh
                            [1] =>
                        )

                    [meta_keyword] => Array
                        (
                            [0] =>
                            [1] =>
                        )

                    [sort_order] =>
                    [image] => brand/1452498338552.jpg
                    [status] =>
                )

        )

I tried to get value with below function, but i am unable to get it.
$request = Yii::$app->request;
$request->post('Brand[name][0]');

How can i get value of name array ?
I don't want to use it like $_POST['Brand']['name'][0], I need to use only yii2 function

A: Try to use ArrayHelper class
$var = ArrayHelper::getValue($request->post(), 'Brand.name.0');

The way $request->post() method works, it just returns to you a value from $_POST, so usage is:
$brand = $request->post('Brand'); // now $brand variable contains $_POST['Brand']
$var = $brand['name'][0]


text:
Q: Issue with running ansible playbook on docker containers on MAC I spin up 3 ubuntu containers to practice ansible playbooks. As in docker for MAC, I can't use ssh directly on container ip and have to go via port forwarding route followed this question
docker run -d -p 2024:22 dockerReg/ubuntu-ssh-enabled
docker run -d -p 2023:22 dockerReg/ubuntu-ssh-enabled
docker run -d -p 2022:22 dockerReg/ubuntu-ssh-enabled

My current inventory file looks like below
MacBook-Pro:~$ cat inventory.txt
target1 ansible_host=172.17.0.2 ansible_ssh_pass=Passw0rd
target2 ansible_host=172.17.0.3 ansible_ssh_pass=Passw0rd
target3 ansible_host=172.17.0.4 ansible_ssh_pass=Passw0rd

What command I need to run now to run ping module on all targets in my inventory file. Of course this won't work : ansible target* -m ping -i inventory.txt
What's the best way to solve this problem or is there any simple workaround ?

A: If you are spinning up docker containers, why don't you use the docker connection plugin ? I have never used any machintosh so I might miss something, but I don't see why it would not work as expected as long as you can interact with your containers using "normal" docker commands.
Fast POC to get you going.
Inventory inventories/docker-poc.yml
---
all:
  children:
    my_poc_hosts:
      vars:
        ansible_connection: docker
      hosts:
        target1:
        target2:
        target3:

If you want to keep the ini format, this is the equivalent:
[my_poc_hosts]
target1
target2
target3

[my_poc_hosts:vars]
ansible_connection=docker

Spin up test containers
I used the python:3.8 image (to make sure python is installed as it is mandatory for ansible) with a long running custom command.
for i in {1..3} ; do docker run -d --rm --name target$i python:3.8 sh -c "while true; do sleep 20000; done"; done

Fast test with ad-hoc ping
$ ansible -i inventories/docker-poc.yml my_poc_hosts -m ping
[WARNING]: Platform linux on host target1 is using the discovered Python interpreter at /usr/bin/python, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.

target1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
[WARNING]: Platform linux on host target3 is using the discovered Python interpreter at /usr/bin/python, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.

target3 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
[WARNING]: Platform linux on host target2 is using the discovered Python interpreter at /usr/bin/python, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.

target2 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

Cleanup
for i in {1..3}; do docker rm -f target$i; done


text:
Q: IronRuby and C++ DLL I want to call c++ function from dll. Is it possible to use something like DllImport from C# in IronRuby?

A: There is no option to do that directly from IronRuby at the moment. You will need to wrap the C++ library with a C# assembly (using P/Invoke) and then use the C# assembly from IronRuby.


text:
Q: How to push my code safely to remote repository? I want to push my code to the remote repository, but:

*

*I haven't updated my local repository for a month

*I've added some code to the staging area but didn't commit the changes

*I've moved files to another directory in my workspace

What should I do if I want to push my code safely to the remote repository and also update my local repo and workspace?

A: You will need to git pull to get the changes from remote into your local repo before you can push your local changes. If there are differences between remote and local you'll need to merge. This helped me: marklodato.github.io/visual-git-guide/index-en.html

A: If all you need is getting your files up to your remote repository (and remove the ones that you've moved),
Open your local repository with terminal,
git pull
git add *
git commit -m "whatever you want to name this commit"
git push

and everythng will be up in your remote repository.


text:
Q: Mostrar contenido de una base de datos con php estoy haciendo un trabajo para la escuela, en que me piden que haga una "mini réplica" de lo que vendría siendo twitter, para que veamos el manejo de datos con php y demás.
Bien, he llegado al punto de registrar usuarios, hacer login y guardar tweets en una base de datos, pero algo tan simple como mostrar estos, pues no me sale. Veréis, tengo dos bases de datos;

Base de datos usuarios: guardo los campos name, username, password y id, por ese orden.
  Base de datos tweets donde guardo: id del tweet, text (contenido del tweet), date (fecha en que se publicó) y userId (id del usuario que publicó el tweet), también, en ese orden.

Bueno, pues tengo la siguiente función, que es la que se encarga de recuperar el contenido de los tweets
function obtenirTuits(){
    $conn = connectar();

    $sqlTweets = "SELECT * FROM tweets";
    $rowsTweets = $conn->query($sqlTweets);
    $rowsTweets = $rowsTweets -> fetch();

    if (!$rowsTweets){
        echo "
"."
"."No hi ha tuits a mostrar!";
    }else{

    }
}

Como podemos ver, si la variable $rowsTweets no tiene contenido, nos mostrará que no hay tweets que mostrar, en cambio, si no, debería mostrar lo siguiente:
Publicado por "usuario" a las "fecha de publicación"
Contenido del tweet
Pero no se como hacer esto, además, tendría que dar la opción de que "x" usuario pudiese borrar su tweet, apareciendo un botón de la siguiente forma:
Publicado por "usuario" a las "fecha de publicación"
Eliminar tweet
Contenido del tweet
A ver si alguien puede echarme una mano, por favor.

A: Asumo que intentó decir que tiene 2 tablas y no 2 base de datos , tal cuál está su código es erróneo por como emplea el fetch y la consulta no obtendrá el nombre del usuario al que corresponde el Tweet solo su id de acuerdo a su relación .
Teniendo la consulta correcta empleando INNER JOIN , se puede acceder al nombre de usuario que publico el tweet, además como no tiene parámetrizada la consulta no utilicé consultas preparadas en la respuesta , para saber si no hay filas puede comparar  num_rows del resultado que retorna ->query()  si es 0 no hay resultados, caso contrario iteramos las filas con el while de siempre. (el formato de presentación de los datos ya queda a su requerimiento)
Código
$sqlTweets = "SELECT t.id, t.date, u.name as usuario
                FROM tweets t
                INNER JOIN usuarios u ON  t.userId = u.id";
if($sqlTweets  = $conn->query($sqlTweets)){
    if($sqlTweets->num_rows === 0)
    {
        echo "
"."
"."No hi ha tuits a mostrar!";
    }else{
         while($fila = $sqlTweets->fetch_assoc())
        {
            echo "
Publicado por " . $fila['usuario']. " a las " . $fila['date']. "";
            echo "<button>  Eliminar Tweet</button>";
        }
    }
}


text:
Q: Change font style in openpyxl Hi I am working on setting the font style to automate the stuff and I can't get the results I want. I want to change the font of column A but I cannot find the correct command for it. Thanks for your time!
import openpyxl
from openpyxl.styles import Font

wb = openpyxl.Workbook()
sheet = wb["Sheet"]
italic24Font = Font( size = 24, italic = True)
sheet['A']  #I do not know the command here
wb.save( 'test.xlsx' )

A: You can use font attribute of worksheet column, something like this:
>>> my_col = sheet.column_dimensions['A']
>>> my_col.font = italic24Font

But, note that this applies only to cells created (in Excel). If you want to apply styles to entire column then you must apply the style to each cell by iteration.


text:
Q: Using ontology URI's end up in 'error 404 not found' I am querying the NIFSTD ontology.
I have loaded the ontology into a triple store. When clicked on some query results, they ended in 'error 404 - not found.
Then I looked into the header of ontology files and found out using all uri's related to NIFSTD ended in the same error. I have mentioned some of them below:
@prefix NIFEXT: <http://uri.neuinfo.org/nif/nifstd/nifext_> .
@prefix NIFRID: <http://uri.neuinfo.org/nif/nifstd/readable/> .
@prefix NIFSTD: <http://uri.neuinfo.org/nif/nifstd/> .
@prefix NLX: <http://uri.neuinfo.org/nif/nifstd/nlx_> .
@prefix NLXANAT: <http://uri.neuinfo.org/nif/nifstd/nlx_anat_> .
@prefix NLXSUB: <http://uri.neuinfo.org/nif/nifstd/nlx_subcell_> .

Does this mean they have moved the ontology or it is not available?

A: Correct, these references were moved or deleted without also performing a referential integrity check.
So the old links were not updated, or (by the look of it) were updated with the root part(s) of the URI but not the final identifying element.  Bad code


text:
Q: Negative smoke tests / defect seeding for validating PACT implementation We're implementing Pact framework for testing couple of microservices (Scala Backend & iOS-Android Frontend). So to test the Pact implementation itself, what sort of negative tests / defect seeding we can do to make sure that - the implemented Pact is catching what it supposed to catch?
i.e. once our Pact work's complete we're thinking to do defect seeding & see if errors like Query parameters, API response structure change , spelling changes in API paths etc are getting caught correctly by the PACT or not?
So on that line what other -ve tests & defect seeding, could we run on the implemented PACT framework? viz- Checklist for smoke test / exploratory tests to quickly test implemented PACT framework before its launched to live.
Thanks

A: Pact is not really designed for those types of tests. It can be done, but the extra variations in data often becomes an issue for providers [1].
There is a proposal to be able to "annotate" interactions by adding arbitrary labels for purposes such as this. If you'd like to add your thoughts to https://github.com/pact-foundation/pact-specification/issues/75 that would be helpful.

*

*https://docs.pact.io/consumer#use-pact-for-isolated-unit-tests


text:
Q: What are the options and best practices for PV3D inspired modeling The studio I work at is currently developing the Tony Hawk XI website and I am responsible for the flash/AS3 development.  As part of the pitch, I entered an augmented reality skateboard example to be shown which impressed the client very much.
After a few weeks of getting stronger with Papervision3D, and getting to know the Flar Toolkit, I have successfully imported md2 and dae files that load and interact with my custom marker.
Now it has come time to develop some of my own models; I will be using 3DSMAX.  I want to know what the limitations are on things like poly-count, character rigging and animation, texturing, tricks for exporting and creating the proper format file and any other bits of information that may save me some serious headaches down the road.
Currently I have a Quake2 MD2 model, Ernie, pulled inside of a FlarToolkit demo here.
This is very low-poly and I was wondering how many polys could I expect to get away with being that today's machines are so much faster;
Brian Hodgeblog.hodgedev.com hodgedev.com

A: I've heard that 2000 polys is about the threshold for good performance.  In practice though, its been hit or miss and a lot of things can have an impact.  So far I've run into perfomance hits when using animated movieclip materials, animated materials with an alpha chanel and precise materieals.
Having to clip objects seems to be a double edged sword.  In some cases, it will increase performance by a good deal, and in others (seems to be primarily when there are alot of polys on the edge of the viewport) it'll drop the framerate by a good 10-15 fps.  So, I'd say the view you setup is something to think about as well.
For example, we have a model of an interior of a store with some shelves and products and customers walking around.  In total we have just under 600 triangles (according to the StatsView, which you should check out if you haven't yet: org.papervision3d.view.stats.StatsView).  On my computer, which is a new computer with a quad core it runs at a steady 30fps (which is where we want it), but on an old Dell XPS (Pentium 4) it runs between 20 and 30fps depending on what objects are being clipped, etc.
We try to reduce the poly count and texture creatively to fix as many of the performance issues as possible.  Unfortunatley our minimum specs are really low, so we need to do alot to get it to run well.
Edit:
Another thing we're doing is swapping out less detailed models for higher detailed ones when zoomed in. If you aren't zooming at all, than this probably won't help.
Hope that helps a bit.


text:
Q: React-Router Middleware with Mobx I am trying to set up an Admin page that is only accessible to people with a user "level" greater than 2. I am using MobX and React-Router. The problem is likely based on the fact that I don't know how to connect to the MobX store properly. I am importing a function, isAdmin, that is located in a seperate file from routes.js. The function looks like:
export const isAdmin = (nextState, replace) => {
    const user = this.context.store.auth.user;
    if (user.level < 2 || !user) {
        replace({
            pathname: '/',
        });
    }
};

This is loosely based on the final example from the gitHub page for react-router located here.
Thanks for any help!

A: This link explains what Context object is and where to use it. `isAdmin' function will need access to your Store class to get the user level.
Create an AuthStore (/stores/auth.js) -
import { observable, computed } from 'mobx';
import singleton from 'singleton';

export default class Auth extends singleton {
  @observable user = null;

  @computed get isLoggedIn() {
    return !!this.user;
  }

  login(username, password) {
    return post('/api/auth/login', {
      username, password
    })
    .then((res) => {
      this.user = res.data.user;
      return res;
    });
  }

  logout() {
    Storage.remove('token');
    return get('/api/auth/logout');
  }
}

In your routes file, you can import the AuthStore and use it like this
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import Auth from './stores/Auth'; // note: we can use the same store here..

function authRequired(nextState, replace) {
  if (!Auth.isLoggedIn) {
    replace('/login');
  }
}

export default (
  <Route name="root" path="/" component={App}>
    <Route name="login" path="login" component={Login} />
    <Route name="admin" path="admin" onEnter={authRequired} component={Admin}>
      <IndexRoute name="dashboard" component={Dashboard} />
    </Route>
  </Route>
);

This stackoverflow question should give you more info


text:
Q: Keyboard shows up automatically when the app starts in Xamarin WebView Hello everyone recently I am working on the project which related to the hybrid webview in xamarin and keyboard hides input field. So in order to solve this problem I used this
Window.SetSoftInputMode(SoftInput.AdjustResize | SoftInput.StateVisible);
inside OnCreate method.Every thing is fine but the keyboard shows up automatically when the app starts. Please help me.
namespace CheongnyeonNara.Droid
{
[Activity(Label = "Young",
    Icon = "@mipmap/ic_launcher",
    Theme = "@style/Theme.Splash",
    MainLauncher = true,
    ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation |
    ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        //TabLayoutResource = Resource.Layout.Tabbar;
        //ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);

        SetTheme(Resource.Style.MainTheme);

        UserDialogs.Init(this);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        App app = new App();
        LoadApplication(app);
        Window.SetSoftInputMode(SoftInput.AdjustResize | SoftInput.StateVisible);

    }

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions,
    [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions,
        grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

}


text:
Q: DNS cname TYPE and IP address assume a website is aliased. for instance  www.sunnyweather.com is the alias and CNAME is xyzverycomplex.sunnyweather.com. After you query and get the CNAME you then need to query the A Type for the xyzverycomplex.sunnyweather.com . the question is: why do I should care about the CNAME? why I can't get directly the IP address of the alias from the name server?

A: You can do both.
If you use A records for all your ip addresses you must change each and every record affected every time you need to change the ip address, e.g., when you change the ip address of a server.
Using CNAME records enable you to group the ip addresses in a logical way so you often only need to change a few entries, e.g., an A record to change all the references to a server.


text:
Q: Sqlite taking too long to fetch pictures I have a few large DB file (each around 50GB) which contain Images of costumer documents (each pic size around 300KB).
I'm trying to load the pictures into my viewer but it's taking too long, like 1min. Specially for the first query/record.
string query = "select pic from tbl_pictures where record_id = '" + SearchID + "'";

            SQLiteConnection con = new SQLiteConnection(conString);
            SQLiteCommand cmd = new SQLiteCommand(query, con);
            con.Open();
            try
            {
                IDataReader rdr = cmd.ExecuteReader();
                try
                {
                    ListOfImagesBytes.Clear();
                    while (rdr.Read())
                    {
                        byte[] a = (System.Byte[])rdr[0];
                        ListOfImagesBytes.Add((System.Byte[])rdr[0]);

                    }
                }
                catch (Exception exc) { MessageBox.Show(exc.Message); }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            con.Close();

And here is the properties of DB files when I created them:
PRAGMA auto_vacuum = 1;
PRAGMA main.page_size = 4096;
PRAGMA main.locking_mode=NORMAL;
PRAGMA main.synchronous=NORMAL;
PRAGMA main.journal_mode=WAL;
PRAGMA main.cache_size=5000;
PRAGMA main.temp_store=Memory;

A: You may just be accessing a record deep inside the table with zero indexes to help.  Maybe add an index?
CREATE INDEX record_id_index ON tbl_pictures(record_id);

A: A page size on the database of 8k or 16k may be better - the SQLite guys have a page about BLOBs and performance at http://www.sqlite.org/intern-v-extern-blob.html ; however it seems to show that files up to 100kB are okay. Much larger than 100kB and you take a performance hit.


text:
Q: Why is an AMD Ryzen 2700x 2x slower than a 3-year-old laptop Intel i7-6820HQ with Python? I just finished installing a desktop computer based on an AMD Ryzen 2700x and 32GB RAM (running Ubuntu 18.04).
At work, I have a 3-year-old laptop workstation with an Intel i7-6820HQ and 16GB RAM (running Windows 10).
I installed Anaconda on both platforms and ran a custom Python code which relies heavily on basic numpy matrix operations.
The code does not involve any GPU-specific computation (my work laptop does not have any).
The Ryzen is running at 3.7GHz, the laptop i7 is running at 3.6GHz. Both systems have been fully updated.
To my surprise, the code runs in 5 minutes on my work laptop, while it requires 10 minutes on the Ryzen desktop!
The latest Ryzen 2700x is supposed to be much faster than a high-end 3-year-old laptop Intel processor, then why would it be 2x slower?

*

*Is it due to Ubuntu being sub-optimal in some way as opposed to Windows 10 for the Ryzen?

*Is it due to Intel being more adequate to Python simulations than AMD?

*Anything else?
Thanks for your help in understanding what is going on.

A:
numpy matrix operations

Intel Skylake has significantly better FMA throughput (2 per clock 256-bit vector) than Ryzen (2 per clock 128-bit vector or 1 per clock 256-bit vector).  See https://agner.org/optimize/ for x86 microarch details.  And FLOPS per cycle for sandy-bridge and haswell SSE2/AVX/AVX2 for a summary including Ryzen.
With data hot in cache, which a well-optimized matmul can achieve with cache-blocking, a good matmul can bottleneck on FMA execution unit throughput.
Or L1d SIMD load/store bandwidth, where Skylake > 2x Ryzen, being able to sustain close to 2x 256-bit load + 1x 256-bit store, while Ryzen can sustain 2x 128-bit cache accesses, up to one of which can be a store.
So it's totally reasonable for the single-threaded or per-core throughput for Intel to be twice that of a Ryzen core, for matmul / FMA throughput.

Are you multi-threading to take advantage of all cores in each machine?  2700x is an 8-core CPU, while 6820HQ is a 4-core chip.
If your workload can / is taking advantage of multiple cores, then maybe it's an L3 cache bandwidth limitation that's making the difference, assuming they're both configured correctly and actually running at 3.6 / 3.7 GHz.  Or maybe there's something creating a 4x per-core perf difference.

A: It's a software issue: by default, anaconda comes with intel's MKL as the backend for BLAS, which will purposefully cripple AMD speed. You can also install the non-MKL version, which uses openBLAS instead, and you'll see a huge performance boost. You don't need to reinstall it, just uninstall numpy and mkl, then install a numpy built with openBLAS.


text:
Q: Unable to modify a slider height I recently bought a parallax template, and I am trying to make a website by modifying the code to my needs. The template I use have a full screen slider at the top of the one page parallax theme, marked as id="home". For some reason, this section is set to 100% height, but I want to change this.
In the template, the original code is as follows:
#home.home-fullscreenslider {
    background: url(../images/pattern.png);
    position: relative;
    overflow: hidden;
    height: 100%;
}

And this initiates the slider:
<div id="home" class="home-fullscreenslider">
</div>

I deleted the height of the slider, so now I can fit the images to the screen properly. But the whole section is still at 100% height. I couldn't find any portion of the css code that dictates the height of #home. What do I need to do?


text:
Q: How do I make trillian forget my password? I use trillian at work and cannot find a way for it to forget my password. It just autologs me. I guess I checked remember me the first time but I would very much like to make it forget.
I guess I could uninstall and whipe everything but I would hope there is a "normal" way.

A: Oh well. Not 5 seconds after asking I find it.
Select 'Switch User' from the menu, then hover over your name and select the small pencil which appears.


text:
Q: Flash Player 13.0 debugger for Windows 7 64 bit I'm trying to add Flash Player 13.0 to the target list on Flash Professional CC (Windows 7, 64 bit). Tried to follow https://forums.adobe.com/message/6338142, but can't find a download for Flash Player 13.0 debugger version for Windows 7. The Windows 8 file named Windows8.1-KB2867622-x64.msu won't install.
I guess I'm either missing something obvious or there's no such thing as Flash Player 13.0 debugger for Windows 7 64 bit.

A: This is from http://www.adobe.com/support/flashplayer/downloads.html:

Adobe Flash Player 14 (Win and Mac) and 11.2 (Linux) - 32 bit and 64
  bit debugger (aka debug player or content debuggers) and standalone
  (aka projectors) players for Flex and Flash developers.

So, now that we're on 14 and not 13 I guess you want to click on the 'Projector' link http://download.macromedia.com/pub/flashplayer/updaters/14/flashplayer_14_sa.exe or http://download.macromedia.com/pub/flashplayer/updaters/14/flashplayer_14_sa_debug.exe for the debug version.
I don't know where you need to put this file or in fact how you get Flash Builder 4.7 or Flash CC to use the updated player.
/* EDIT */
On windows for Flash Builder 4.7 (I know you asked for Flash CC, but it seems from your question that getting it to work after downloading wasn't the problem you were facing; others using Flash Builder will find it tricky to update the player)... change directory to:

C:\Program Files\Adobe\Adobe Flash Builder 4.7 (64 Bit)\player\win

Add a directory with the same name as the version you're adding:

14.0

Place the newly downloaded file, renaming it like so:

FlashPlayerDebugger.exe

i esta!


text:
Q: Quickblox linker error: operator delete(void*)", referenced from I'm creating a simple chat app with Quickblox.
So I added the project to XCode exactly like in this tutorial: http://quickblox.com/developers/IOS-how-to-connect-Quickblox-framework
QBUsers class worked just fine, but when I used QBChat I started to get linker errors:

Undefined symbols for architecture i386:
    "operator delete(void*)", referenced from:
        -[QBVideoChat initAudioCapture] in Quickblox(QBVideoChat.o)
    "operator new(unsigned long)", referenced from:
        -[QBVideoChat initAudioCapture] in Quickblox(QBVideoChat.o)
    "___gxx_personality_v0", referenced from:
        Dwarf Exception Unwind Info (__eh_frame) in Quickblox(QBVideoChat.o)
  ld: symbol(s) not found for architecture i386
  clang: error: linker command failed with exit code 1 (use -v to see invocation)

Here's the line that causes the problem (if I comment it out, linker errors go away):
[[QBChat instance] setDelegate:self];

The class in which the problem occurs implements the following protocols:
<QBActionStatusDelegate, QBChatDelegate>

Here's the list of frameworks I imported to the project:

-lxml2 -lresolv -lz -framework AVFoundation -framework CoreVideo -framework Accelerate -framework CoreMedia -framework AudioToolbox -framework CoreData -framework CoreLocation -framework CoreGraphics -framework MobileCoreServices -framework SystemConfiguration -framework CFNetwork -framework Quickblox -framework UIKit -framework Foundation

A: As it was suggested in comments by Greg Parker, I added libc++.dylib to the project and everything worked.

A: I had the same problem, I added the libc++ and resolved

A: For iOS9 do following in your application's target:
in build phases->Link Binary With Libraries ->search and add 'libstdc++.tbd'
In case you're trying to add this in a library target this won't work. the 'libstdc++.tbd' is not an object file so it can't be added into an objective-c library's target, it needs to be added in an application that wants to use the library.


text:
Q: fitting a model for time series data Folks, I am working on time series traffic data where the waiting times are indexed over time, with 288 observations for 24 hour time period (interval of 5 minutes). I am trying to cleanse the data, identify the patterns and create a forecasting model. (30 days of data)
Trouble is, 80% of the observations are marked as "No Delay", which means waiting time is 0 minutes and 20% of observations are continuous data where waiting time ranging from 3 minutes to 87 minutes.
I looked at multinomial probit regression and multinomial logistic regression and not sure if this is the right way forward. Logistic regression, because I am thinking in the lines of treating "No delay" as categorical variable but waiting times are actually continuous.
I am unable to look at ARIMA and the likes because, after I cleansed the data (removing duplicates and missing values) the intervals are not equally placed. I have data for 12:00 AM, 12:05 AM, 12:10 AM, 12:25 AM (15 minutes interval -- missing values found for 12:15 AM and no record exist for 12:20 AM) .
How to treat missing values here ?
Is logistic regression the right approach? or Time Series models? if time series, how to work with unequal intervals?
Thanks for your effort in helping, grateful for feedback in constructing my question properly.


text:
Q: How to sketch this quadric surface I figured out that this quadric surface is one sheeted hyperboloid but I am unable to plot it in the $xy, xz,$ and the $yz$- planes. I have used the approach where we can put the one axis zero and find the points at that plane, but it's not working out for me. I would really appreciate it if someone could please share a detailed solution. Thank you!

A: It can be tricky to visualize three-dimensional surfaces from the equation alone, but plotting in the plane isn't so bad when remember that (e.g.) the XY plane is the set of all points $(x,y,z)$ where $z=0$. This means that on the XY plane, our equation
$$
z^2 = 4x^2 + y^2 + 8x − 2y + 4z
$$
simplifies by setting $z=0$ to
$$
0 = 4x^2 + y^2 + 8x - 2y.
$$
If you have a hard time seeing what shape this should make, you may wish follow the advice in the comments by completing the square and factoring:
$$
0 = 4(x^2 + 2x + 1 - 1) + (y^2 - 2y + 1 - 1)
= 4(x + 1)^2 + (y - 1)^2 - 5.
$$
Rearrange a teeny bit, and we get
$$
5 = 4(x + 1)^2 + (y - 1)^2.
$$
Does this look familiar?
Similarly, the XZ plane is the set of all points $(x,y,z)$ where $y=0$, so we want to plot
$$
z^2 = 4x^2 + 8x + 4z.
$$
Do you see where to go from here? And the same for the YZ plane?
If you get stuck, might I recommend https://www.desmos.com/calculator for checking your two-dimensional graphs. You can also, for example, input the complete three-dimensional equation and show XY slices as a function of $z$.

A: Here's how I would attack the problem, but you must check my computations:
\begin{align}
z^2&=4x^2 + y^2 + 8x -2y + 4z\\
z^2-4z&=4(x^2+2x)\quad+\quad(y^2-2y)\\
(z-2)^2-4&=4(x+1)^2-4\quad+\quad(y-1)^2-1\\
\zeta^2&=4\xi^2+\eta^2-1\,,
\end{align}
and I guess that says that you have a hyperboloid of one sheet, center at $(-1,1,2)$.
(I notice belatedly that the first commenter, @Gio, has given you this answer already.)


text:
Q: Typescript: spread operator not working unless using keyword "as" I am new to Typescript but understand the keyword as is type assertion.  I have a Promise that is supported to return a type of an interface CodeWork.
I had 2 constant that I was combining in the shape of that interface like this:
  const part1 = Object.entries(grabData)[1][1] ?? null;
  const part2 = Object.entries(grabData)[1][1] ?? null;

  const allData = {...part1, ...part2};
  return allData;

but my code editor shows an editor of the spread operators saying "Spread types may only be created from object types".  When debugging, the data is the correct shape so I assume it's solely a type issue.
When I change it to:
  const part1 = Object.entries(grabData)[1][1] ?? null;
  const part2 = Object.entries(grabData)[1][1] ?? null;

  const allData = {...part1 as CodeWork, ...part2 as CodeWork};
  return allData;

that doesn't show the error in the editor anymore.  Even though the data is the same shape, I still need to use type assertion?


text:
Q: No module named PIL after installing Pillow (v5.2.0) with pip v18.0 As the title says, after I installed Pillow with pip install Pillow, when I'm trying to import it "No module named 'PIL' " error appears.
I'm trying to import it with this code: from PIL import ImageTk, Image.
I have pip 18.0 installed, and Pillow 5.2.0.
I'm using just python 3.7.
I have to mention that I don't have PIL installed.
After trying with easy_install and python -m pip install, still don't work.
python -m pip install returns: Collecting pillow Downloading files.pythonhosted.org/packages/72/22/… (1.4MB) 100% |████████████████████████████████| 1.4MB 2.6MB/s Installing collected packages: pillow Successfully installed pillow-5.2.0
Command python -c "import sys; print(sys.path)" returns: ['', 'c:\\users\\lenovo b590\\appdata\\local\\programs\\python\\python37-32\\python37.zip', 'c:\\users\\lenovo b590\\appdata\\local\\programs\\python\\python37-32\\DLLs', 'c:\\users\\lenovo b590\\appdata\\local\\programs\\python\\python37-32\\lib', 'c:\\users\\lenovo b590\\appdata\\local\\programs\\python\\python37-32', 'c:\\users\\lenovo b590\\appdata\\local\\programs\\python\\python37-32\\lib\\site-packages', 'c:\\users\\lenovo b590\\appdata\\local\\programs\\python\\python37-32\\lib\\site-packages\\win32', 'c:\\users\\lenovo b590\\appdata\\local\\programs\\python\\python37-32\\lib\\site-packages\\win32\\lib', 'c:\\users\\lenovo b590\\appdata\\local\\programs\\python\\python37-32\\lib\\site-packages\\Pythonwin']

Maybe helps: I have VS 2017 installed with C++ and Python. I'v tryed to install python-pptx and got error: Command ""c:\users\lenovo b590\appdata\local\programs\python\python37-32\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\LENOVO~1\\AppData\\Local\\Temp\\pip-install-_o4pnv9h\\lxml\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\LENOVO~1\AppData\Local\Temp\pip-record-08vt5tx4\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\LENOVO~1\AppData\Local\Temp\pip-install-_o4pnv9h\lxml\

A: I was running the code through IDLE 3.6 (64-Bit), running it through IDLE 3.7 (32-Bit) solved the problem, thanks to FlyingTeller !


text:
Q: Vim syntax Highlighting I have installed vim in Debian 6. I am trying to change color scheme and enable syntax highlighting. But it's not working. I added set background=dark in .vimrc file. But white background is displaying. I wonder what went wrong?
Here is my .vimrc file: http://pastebin.com/8k2gpWDh
I installed robokai colorscheme which has dark background. But the background looks white instead dark. Other colors of colorscheme working.

A: robokai seem to be written for a 16 color terminal, a linux console probably, but i am guessing here. To make it work if you are using a terminal emulator (like xterm, gnome-terminal, konsole, etc) you may use set t_Co=16 before loading the color scheme or force your terminal type to linux when running vim (TERM=linux vim ...), and manually set a dark background in your terminal emulator,
Also run dpkg --get-selections | grep vim. For vim to work in full you need to see one of: vim-gnome, vim-gtk, vim-lesstiff or vim-nox (for systems without a graphical desktop).

A: If you are using a terminal emulator like konsole or gnome-terminal, install vim-gtk or vim-gnome, get CSApprox, and add set t_Co=256 to your .vimrc. This will give you support for any color scheme, in the terminal, even those which supposedly only support gvim.

A: Make sure you have
syntax on

And then call
color[scheme] {name}

To set your desired colorscheme. These contain the set background=dark you
refered, so it should be a matter of choosing the right one. Vim comes with some
color schemes, but you may want to install new ones.
This page and this one provide tips on color schemes, and there is a
test page very helpful when choosing colorschemes.


text:
Q: How to iterate over an array in bash Using bash, i'm calling an API using curl and storing the result in a variable. That result is an array. An example of the structure of the response is below.
[
{"id":1,"name":"this is the name","description":"this is the description"},
{"id":2,"name":"this is the name","description":"this is the description"},
{"id":3,"name":"this is the name","description":"this is the description"}
]

I want to be able to iterate through and get the value of "id". Then use that id as part of another curl call. How could I achieve this using bash?

A: You can use jq to extract the id values and readarray to store them in a bash array for later processing:
#!/usr/bin/env bash

json='
[
{"id":1,"name":"this is the name","description":"this is the description"},
{"id":2,"name":"this is the name","description":"this is the description"},
{"id":3,"name":"this is the name","description":"this is the description"}
]
'

readarray -t ids < <(jq '.[] | .id' <<<"$json")

for id in "${ids[@]}"; do
    printf "Id %d\n" "$id"
done

A: Try sed
curl $YOUR_URL | sed -n 's/.*"id":\(.*\),"name".*/\1/p'
1
2
3


text:
Q: How to split a (569 ,31 ) DataFrame into two with shapes (569 ,30) and (569, ) How to split a (569 ,31 ) dataframe into two with shapes (569 ,30) and (569, )
The dataFrame has 31 columns-
df.columns yields this -
Index([u'mean radius', u'mean texture', u'mean perimeter', u'mean area',
       u'mean smoothness', u'mean compactness', u'mean concavity',
       u'mean concave points', u'mean symmetry', u'mean fractal dimension',
       u'radius error', u'texture error', u'perimeter error', u'area error',
       u'smoothness error', u'compactness error', u'concavity error',
       u'concave points error', u'symmetry error', u'fractal dimension error',
       u'worst radius', u'worst texture', u'worst perimeter', u'worst area',
       u'worst smoothness', u'worst compactness', u'worst concavity',
       u'worst concave points', u'worst symmetry', u'worst fractal dimension',
       u'target'],
      dtype='object')

I need to split it into two.
I did something like this -
X = df.ix[:,'mean radius': 'worst fractal dimension']

y = df.ix[:,'target': ]

X.shape gives (569, 30) which is as expected, but y.shape gives (569,1).
I dont really understand the difference between (569,) ans (569, 1). BUt he answer required is shape of (569,)

A: y.shape gives you (569, 1)  because calling y = df.ix[:,'target': ] returns you a DataFrame type.
Difference between shapes (569,) and (569, 1) is that (569,) is a Series type and it has only one dimension, while (569, 1) is a DataFrame with two dimensions ('569' - for 569 rows and  '1' for 1 column).
Calling
y = df['target'] should return you a Series type.
Also, note, that the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers:
http://pandas.pydata.org/
Nevertheless, it still works
You can also convert 'one-column' DataFrame into Series manually
as discussed for example here
To check the type of your variable you can find type(y) very usefull and it helps solve similar issues

A: X = df[df.columns.drop('target')]
y = df['target']

alternatively you can change:
y = df.ix[:,'target': ]

to:
y = df.ix[:,'target']

PS .ix[] indexer is deprecated in modern Pandas versions, so it's advised to use .loc[] instead


text:
Q: How do I get rid of the white space between my tabs and the table in react.js? Below is the image of the page:
Below is the image of my code, the issue is something to do with the tabs tag, I don't know how to make the white space change into matching the background color, (the backgroundColor:'#EEEEEE' does not work.
<Box sx={{ bgcolor: 'background.paper', width: '25%' }}>
      <AppBar position="static">
        <Tabs
          value={tabValue}
          onChange={handleTabChange}
          indicatorColor="secondary"
          textColor="inherit"
          variant="fullWidth"
          aria-label="full width tabs example"
          TabIndicatorProps={{
            style: {
              backgroundColor: '#EEEEEE',
              height: '3px',
            },
          }}
        >
          <Tab label="Active" {...a11yProps(0)} />
          <Tab label="Inactive" {...a11yProps(1)} />
          <Tab label="Applicants" {...a11yProps(2)} />
        </Tabs>
      </AppBar>
    </Box>


text:
Q: How could I rename the first 5 files in a folder with a different extension while keeping the old ones the same? I have about 20 files in a folder. I want to rename the extension of the first 5 from .txt to .html. I want to keep the first 5 files with the .txt extension though. Here is what I have so far. It is a bash script
cp 'ls | head -5 "files would go here I think"

A: files=(*.txt)
for ((i=0; i<5; i++)); do
    cp -v "${files[i]}" "${files[i]%.txt}.html"
done

A: You should be able to pipe these commands to get what you need.
ls *.txt | head -5 | sed -e 's/.txt$//' | xargs -n1 -I% cp %.txt %.html


text:
Q: Appending value to a list based on dictionary key I started writing Python scripts for my research this past summer, and have been picking up the language as I go.  For my current work, I have a dictionary of lists, sample_range_dict, that is initialized with descriptor_cols as the keys and empty lists for values.  Sample code is below:
import numpy as np
import pandas as pd

def rangeFunc(arr):
    return (np.max(arr) - np.min(arr))

df_sample = pd.DataFrame(np.random.rand(2000, 4), columns=list("ABCD")) #random dataframe for testing
col_list = df_sample.columns

sample_range_dict = dict.fromkeys(col_list, []) #creates dictionary where each key pairs with an empty list
rand_df = df_sample.sample(n=20) #make a new dataframe with 20 random rows of df_sample

I want to go through each column from rand_df and calculate the range of values, putting each range in the list with the specified column name (e.g. sample_range_dict["A"] = [range in column A]).  The following is the code I initially thought to use for this:
for d in col_list:
    sample_range_dict[d].append(rangeFunc(rand_df[d].tolist()))

However, instead of each key having one item in the list, printing sample_range_dict shows each key having an identical list of 4 values:
{'A': [0.8404352070810013,
  0.9766398946246098,
  0.9364714925930782,
  0.9801082480908744],
 'B': [0.8404352070810013,
  0.9766398946246098,
  0.9364714925930782,
  0.9801082480908744],
 'C': [0.8404352070810013,
  0.9766398946246098,
  0.9364714925930782,
  0.9801082480908744],
 'D': [0.8404352070810013,
  0.9766398946246098,
  0.9364714925930782,
  0.9801082480908744]}

I've determined that the first value is the range for "A", second value is the range for "B", and so on.  My question is about why this is happening, and how I could rewrite the code in order to get one item in the list for each key.
P.S. I'm looking to make this an iterative process, hence using lists instead of single numbers.

A: The issue is this line:
sample_range_dict = dict.fromkeys(col_list, [])

You only created one list. You don't have four lists with the same elements; you have one list, and four references to it. When you add to it via one reference, the element is visible through the other references, because it's the same list:
>>> a = dict.fromkeys(['x', 'y', 'z'], [])
>>> a['x'] is a['y']
True
>>> a['x'].append(5)
>>> a['y']
[5]

If you want each key to have a different list, either create a new list for each key:
>>> a = { k: [] for k in ['x', 'y', 'z'] }
>>> a['x'] is a['y']
False
>>> a['x'].append(5)
>>> a['y']
[]

Or use a defaultdict which will do it for you:
>>> from collections import defaultdict
>>> a = defaultdict(list)
>>> a['x'] is a['y']
False
>>> a['x'].append(5)
>>> a['y']
[]


text:
Q: Send OpenCV image in JSON from Python to Android I have a Python server which operates on an image drawing something on it with OpenCV. After that I want to send the resultant image through a previously opened socketserver to an Android device. With the image I would also like to send a string, so I build a JSON object to be sent. The object received by the Android app contains both elements but the image is the string representation of an OpenCV Mat object.
I couldn't find any method on how to convert that kind of representation of the image in byte array so that I could rebuild in the Android app the image and display it.
How can I send the image correctly and then converted in the Android app?
Here is my Python script for build the image, the JSON and send it:
imgou = numpy.zeros((numpy.size(mat_image, 0), numpy.size(mat_image, 1), 3), numpy.uint8)
cv2.drawContours(imgou, cont, idx, (0,255,0), 3)

print "build json"
outjson = {}
outjson['img'] = numpy.array_str(imgou)
outjson['leaf'] = leaf
json_data = json.dumps(outjson)

self.request.sendall(json_data)

Here is the code of the Android app to process the JSON:
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
...
JSONObject json = new JSONObject(sb.toString());
String leaf_name = json.getString("leaf");
String mat_string = json.getString("img");

byte[] raw_data = mat_string.getBytes("utf-8");
Mat mat_img = new Mat();
mat_img.put(0, 0, raw_data);

At this point I should have in mat_img the Mat object ready to be written in a file and then displayed.

A: Based on the answer of Avinash, I managed to pack the image in a JSON object and then retrive it from the Android application. Since OpenCV provides a method for Bitmap to Mat conversion, sending the image instead of the Mat object si more handy.
Here the working code of the Python server:
img_file = open("image1.png", "r")

# read the image file
data = img_file.read()

# build JSON object
outjson = {}
outjson['img'] = data.encode('base64')   # data has to be encoded base64 and decode back in the Android app base64 as well
outjson['leaf'] = "leaf"
json_data = json.dumps(outjson)

# close file pointer and send data
img_file.close()
self.request.sendall(json_data)

Here the working code of the Android app:
// Read JSON from socket inputstream and rebuild the string
InputStream in = so.getInputStream();
if (in == null) return false;
BufferedReader br = new BufferedReader(new InputStreamReader(in));
sb = new StringBuilder();

String line;
while ((line = br.readLine()) != null) {
   sb.append(line);
}

...
// Convert string in JSON and retrieve raw data
JSONObject json = new JSONObject(sb.toString());
String leaf_name = json.getString("leaf");
String mat_string = json.getString("img");

// Convert raw byte data of image into Bitmap image
FileOutputStream byteBuffer = new FileOutputStream();

byte[] raw_data = Base64.decode(mat_string, Base64.DEFAULT);
Bitmap img = BitmapFactory.decodeByteArray(raw_data, 0, raw_data.length);
img.compress(Bitmap.CompressFormat.PNG, 100, byteBuffer);

Cheers!

A: form your server you can send the image into a byte array
now in your android app you can recive the byte array and convert it into bitmap and then into Mat
byte[] bitmapdata = Base64.decode("your byte string", Base64.DEFAULT);
//here the data coming from server is assumed in Base64
//if you are sending bytes in plain string you can directly convert it to byte array
    Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0,        bitmapdata.length);

//android OpenCv function
org.opencv.android.Utils.bitmapToMat(bitmap,mat);


text:
Q: Bounding exceedance probabilities for correlated normal variables Suppose $y\sim N(0,\Sigma)$ is an $n-$dimensional vector. I'm interested in an upper bound for $\Pr(\max_{1\leq i\leq n} y_i > k)$ for $k$ large. I know a little about $\Sigma$: $\sigma_{ii}=\sigma_{jj}$ for any $i, j$ and $\sigma_{ij}\geq 0$. I can also bound the pairwise correlations from above, but it's rather uninformative (something like $(m-1)/m$ where $m$ is large in my application). But that's about it.
There are all kinds of results about similar probabilities for smooth Gaussian processes, but I can't find much about regular old random vectors. Any pointers?

A: Slepian's inequality allows you to dominate the probability for the case you ask about by the same with $\Sigma=\sigma_{11} I$.