text:
Q: Laravel running migrations on "app/database/migrations" folder recursively So my migrations folder looks like this since I have dozens of tables it keeps things organized and clean:
migrations/
  create_user_table.php
  relations/
  translations/

I'm trying to do a refresh all migrations and seed but it seems like I've run into a slight hiccup where I don't know the artisan command to run migrations recursively (i.e. run migrations in the relations and translations folders as well).
I've tried adding --path="app/database/migrations/*" however it spat out an error. Does anyone know the solution to this?

A: The only way to do it right now is to manually go through all the migrations. That is, you have to run the migration command on each of your subfolders:
php artisan migrate --path=/app/database/migrations/relations
php artisan migrate --path=/app/database/migrations/translations

However, what you can do is easily extend the artisan system to write your own migrate command that will iterate through all folders under the migrations folder, create these commands for you and run them.
You can also simply write a shell script if you don't want to get into doing this via artisan
Edit: for Laravel >= 5.0, the correct commands to migrate migration files in sub directories would be:
php artisan migrate --path=/database/migrations/relations
php artisan migrate --path=/database/migrations/translations

A: This add to boot method in AppServiceProvider
$mainPath = database_path('migrations');
$directories = glob($mainPath . '/*' , GLOB_ONLYDIR);
$paths = array_merge([$mainPath], $directories);

$this->loadMigrationsFrom($paths);

Now you use can php artisan migrate and also php artisan migrate:back

A: You can use the following command to do this recursively:
php artisan migrate --path=/database/migrations/**/*

**/* is also known as the globstar
Before this works you must check if your bash supports the globstar.
You can do this by executing shopt and checking for globstar.
Globstar is supported by default by most server distributions but might not work on MAC.
For more on globstar see: https://www.linuxjournal.com/content/globstar-new-bash-globbing-option

A: In Laravel 5 the database folder sits alongside the app folder by default. So you could run this to migrate a single folders migrations:
php artisan migrate --path=/database/migrations/users

A: You can try this package nscreed/laravel-migration-paths. By default all sub directories inside the migrations folder will be autoloaded. Even you can add any directories very easily.
'paths' => [
    database_path('migrations'),
    'path/to/custom_migrations', // Your Custom Migration Directory
],

Don't need any special command just the generic: php artisan migrate will do your tasks.

A: You can also use a wildcard, like so:
php artisan migrate --path=/database/migrations/*

A: I rewrote the MigrationServiceProvider:
- registerResetCommand()
- registerStatusCommand()
- registerMigrateCommand()

There you can register your own commands:
class MigrateCommand extends Illuminate\Database\Console\Migrations\MigrateCommand

After that you just need to extend youd directories:
protected function getMigrationPaths()

Or you just register the paths on application boot.
I've already done my solution before I knwewd about '$this->loadMigrationsFrom'.

A: A Simple solution is to create an Artisan Command for example (migrate:all),
then inside handle function define migrate command for each sub directories as mentioned bellow.
Artisan::call('migrate', [
   '--path' => '/database/migrations/employee'
]);

A: Only relative path works for me (in Laravel 5.7):
php artisan migrate --path=database/migrations/your-folder-with-migrations

A: This works at laravel 8
php artisan migrate --path=database/migrations/tenant

A: It is a not a "direct" solution but i suggest you to look at Modularity into your laravel project.
Modules can segment your application in several smaller "folders" and bring migration, seeds, classes, routes, controllers, commands together in easily maintainable folders.
This package is a good start : https://github.com/pingpong-labs/modules

A: No changes are necessary, whenever you need it, use this command:
php artisan migrate --path=database/migrations/*

If you want a shortcut, you can include that in your composer.json:
"scripts": {

    "migrate": [
        "@php artisan migrate --force --path=database/migrations/*"
    ]
}

Then just use composer migrate in the terminal.

A: add in app/Providers/AppServiceProvider.php the path of your migration folder, you can add a string or an array
    public function register()
    {
        $this->registerMigrations();
    }

    protected function registerMigrations()
    {
        return $this->loadMigrationsFrom(__DIR__ . '/../../database/migrations/**/*');
    }

A: A Simple Laravel solution is to create a gulp task (say migrate-others).
var elixir = require('laravel-elixir');
var gulp = require('gulp');
var shell = require('gulp-shell')

/*
 |--------------------------------------------------------------------------
 | Elixir Asset Management
 |--------------------------------------------------------------------------
 |
 | Elixir provides a clean, fluent API for defining some basic Gulp tasks
 | for your Laravel application. By default, we are compiling the Sass
 | file for our application, as well as publishing vendor resources.
 |
 */

elixir(function(mix) {
    mix.sass('app.scss');
});

// Our Task
gulp.task('migrate-others', shell.task([
    'php artisan migrate --path=/app/database/migrations/relations',
    'php artisan migrate --path=/app/database/migrations/translations',
]));

Now you can simply call
gulp migrate-others

A: Here you go!
 function rei($folder)
    {
        $iterator = new DirectoryIterator($folder);
        system("php artisan migrate --path=" . $folder);
        foreach ($iterator as $fileinfo) {
            if ($fileinfo->isDir() && !$fileinfo->isDot()) {
                echo $fileinfo->getFilename() . "\n";
                rei($folder . $fileinfo->getFilename() . '/');
            }
        }
    }

 rei('./database/');


text:
Q: Difference between "Have Thought", "Have Just Thought" and "Just Thought"? I was told that use of present perfect is incorrect in the context below as thinking action is discrete event and there isn't any relevance with the current situation. (Context is a situation where I've been looking for my keys for the last couple of minutes and my friend informs me where the keys are. Just a minute ago my friend informs me the same information comes to my mind)
My friend: The keys are on the desk.
Me: I have thought the same thing.
I was told that instead of "I have thought the same thing" it is correct to use "I thought the same thing" or "I was thinking the same thing."
My questions then concern the two examples below:
Example 1
My friend: The keys are on the desk.
Me: I have just thought the same thing
Example 2
My friend: The keys are on the desk.
Me: I just thought the same thing
Similar to the use of "I have thought the same thing" is Example 1 incorrect to use (present perfect + Just)? Does present perfect fit semantically in this context with or without time adverb "just"?
Can I use Example 2 (simple past +just)? Because several resources indicate that present perfect + just and simple past +just essentially mean the same thing. Is there any semantical difference between Example 1 & Example 2?

A: There are various parts to this; I'm focusing on only the overall meaning of each (as opposed to, say, the nuance introduced by "just"). So, I can construct a scenario where Example 1 is perfectly correct, but it means something different from Example 2. I'll use a slightly different example to illustrate:
Example 3

My friend: I am going to draw various things. For each drawing, I'll tell you I have done it and I want you to draw the same and then tell me when you're done.
Me: OK
My friend: [scribble scribble scribble] I have drawn a set of keys sitting on a desk
Me: [scribble scribble scribble] OK, I have just drawn the same thing
My friend: [continues onto next drawing]

Example 4

My friend: [Out of the blue holds up a picture he's drawn] Look! I have drawn a set of keys sitting on a desk
Me: Holy crap, that's amazing! I just drew the same thing!
My friend: [stares at my drawing, then me, then back at my drawing, terrified, as if I might be some kind of witch]

It wouldn't be too hard to morph that into something to do with thoughts rather than drawings -- maybe a scenario with a stage magician/mind-reader asking people to think of things and then tell him when they've done it. Doxastic involuntarism aside, I think the comparison works.
But, ignoring that contrived example, with the meaning implied in your context I would not use Example 1. Example 2 is better/idiomatic.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Debugging programmatic autolayout constraints I've created my view controller's view entirely in code by adding subviews and constraints (using the CocoaPod PureLayout). It actually looks/ functions exactly how I want it to, but xcode yells at me saying one of the constraints is wrong and it removes it. How can I tell which UIViews the bad constraints are attached to? I have a lot of subviews and I can't figure it out from context. When working with constraints in interface builder, you can name the UIView and that's what gets printed to the debug console- but I can't find a way to accomplish this through code.
Looking at the apple docs: https://developer.apple.com/library/ios/documentation/userexperience/conceptual/AutolayoutPG/ResolvingIssues/ResolvingIssues.html#//apple_ref/doc/uid/TP40010853-CH17-SW14
They say:
"It may be obvious which view has the problem; if it is not, you may find it helpful to use the NSView method _subtreeDescription to create a textual description of the view hierarchy.
Important: The _subtreeDescription method is not public API; it is, however, permissible to use for debugging purposes"
Is this what I'm looking for? How do I make use of a private API?

A: UIWindow also has a private instance method _autolayoutTrace to dump a string that shows the overall view hierarchy, including views that are ambiguous.  Just use it from the console after setting a breakpoint after you see the constraint exception.  You can also trap any autolayout exceptions using a symbolic breakpoint "UIViewAlertForUnsatisfiableConstraints".
Check out Facebook's Chisel too: https://github.com/facebook/chisel

A: Starting with the iOS 8 SDK, there is now an identifier property on NSLayoutConstraint. Note that this property has existed privately (Apple-only) since iOS 7, but now that it is public in iOS 8, you are allowed to make use of it even when running on iOS 7.
Using this property, you can easily set a unique short description to your constraints to aid in debugging. For example, using PureLayout:
NSLayoutConstraint *constraint = [label autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:imageView];
constraint.identifier = @"Label Left Padding";

// ...or using PureLayout v2.0+:
[[label autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:imageView] autoIdentify:@"Label Left Padding"];

// PureLayout v2.0+ also supports a block-based version to set an identifier to many constraints at once:
[UIView autoSetIdentifer:@"Constraints to position image view" forConstraints:^{
    // ...a bunch of PureLayout API calls here that create constraints...
}];

Then, you will see this identifier printed next to the constraint in the console if there is a constraint exception.
One other handy debug tool:
Apple has a very handy category on UIView (declared in UIView.h) named UIConstraintBasedLayoutDebugging that includes a method:
- (NSArray *)constraintsAffectingLayoutForAxis:(UILayoutConstraintAxis)axis;

You can call this method on any view, passing either Horizontal or Vertical axis (since constraints in each axis are independent), and get a list of all the constraints that affect the position and size along that axis. Note that Apple says this should be used for debugging only - never ship code that uses this API!


text:
Q: Python 2.7 Verify Directory Return False While I Not Use Something Not String Directly Firstly, this is my first post on the website if i did any mistake during topic sorry about that.
My problem is I am currently trying to retrive home location of user with that way i am planning to git clone to that directory but I tried to many way to find out location of user home.
p = subprocess.Popen("cd && pwd", stdout=subprocess.PIPE, shell=True)
result = p.communicate()[0]

def getusername():
    username = subprocess.check_output(["echo $HOME"],shell=True)
    return username

and etc but when i get the value from them and use it like this
print os.access(result, os.F_OK) // returning false

I already check the value and try to type value as string to there for examp lets say that /home/user/ is returning value, result is holding same value but return false but when i type print os.access("/home/user", os.F_OK),  I am getting true but i didn't understand why i tried too many different way also i tried os.path.exist or os.path.directory and etc all them is working when i typed as manual. But  if i write  the variable name into there its not working
I almost spend night to find out it but with no luck i was not able to figure out. and also i trying to add some manual string to if i solve this problem next step is going to be like os.access(result + "/Veil", os.F_OK) but when I do like:
n  = result + "/Veil"
print n

Result is appearing something like:
/home/user
/Veil

Its showing them separate line I also think that maybe thats problem but even if a remove it still not working. If someone tell me whats the problem i will be soo happy from now thank you so much !

A: If your need is to find the user directory, just us os.path.expanduser method like this :
os.path.expanduser("~")
>> /home/user


text:
Q: Caesar Cipher for CS50 I've been staring at this problem for weeks and I have nothing! It doesn't work, I know that much, but I don't know why or what's wrong. I do know that the developer spits out "error: expected expression" regarding the line I highlighted, but really that's just the tip of the iceberg. If anyone at all knows how to fix any small piece of this I would greatly appreciate it!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cs50.h>
#include <ctype.h>

int main(int argc, char *argv[])
{

    //Get the key
    if (argc != 2 || atoi(argv[1]) < 0)
    {
        printf("Usage: ./caesar k");
        return 1;
    }

    int key = atoi(argv[1]);
    string plaintex;
    string plaintext = GetString();

    for (int i = 0, n = strlen(plaintext); n < i; i++)
    {
        if (plaintext[i] > 'A' && plaintext[i] <= 'Z')
        {
            plaintext[i] = (plaintext[i] - 'A' + key) % 26 + 'A';
        }
    }
    for (int i = 0, n = strlen(plaintext); n < i; i++)
    {
        if (plaintext[i] >= 'A' && plaintext[i] >= 'Z')  // Highlighted line
        {
            plaintext[i] = (plaintext[i] - 'A' + key) % 26 + 'A';
        }
        else if (plaintext[i] >= 'a' && plaintext[i] < 'z')
        {
            plaintext[i] = (plaintext[i] - 'a' + key) % 26 + 'a';
        }
        else
        {
            printf("%c\n", plaintext[i]);
        }
    }
    return 0;
}

A: if (plaintext[i] >= 'A' && plaintext[i] >= 'Z')

should be
if (plaintext[i] >= 'A' && plaintext[i] <= 'Z')

A: A has a less significant symbol table index than Z. Most likely A == 65 and Z == 90.
if (plaintext[i] >= 'A' && plaintext[i] >= 'Z')

You are saying "if something is larger than 65 and also larger than 90". The logic doesn't make any sense, it is the very same thing as saying "if something is larger than 90".
You probably meant
if (plaintext[i] >= 'A' && plaintext[i] <= 'Z')


text:
Q: Top of View Hidden by NavigatorIOS in TabBarIOS I have a TabBarIOS as a main container, and each tab loads a NavigatorIOS component which holds (for example) a View. My problem is that the top of the View is hidden behind the NavigatorIOS. No styles on anything - this project is brand new.
Am I missing something that would allow the View to automatically adjust its top to fit inside the NavigatorIOS (which would automatically adjust its bottom to fit inside the TabBarIOS) like in native/Xcode?
Or, do I need to calculate the heights and drop in padding? Thanks!

A: I figured it out. If you set translucent to false, it will adjust the spacing as I desired. But with translucent equal to true, it goes full height behind.


text:
Q: Git filter tag is not working for multiple pattern As per the document,
Running "git tag" without arguments also lists all tags. The pattern is a shell wildcard (i.e., matched using fnmatch(3)). Multiple patterns may be given; if any of them matches, the tag is shown.

there are multiple tags in the repository and I want to list out only two sets of pattern in Jenkins git params.
Jenkins Git Parameter plugins are used to filter the "git tag -l {pattern}" and the pattern is based on fnmatch.
Example tag
DEV2.3.4
ST2.4.6
SIT2.1.6
I just to filter out the DEV and ST tag. I tried a few different patterns.
git tag -l '(?:ST|DEV)\*'$/
git tag -l '/^DEV[0-9]+(\.[0-9]+)*$/'
git tag -l '@(DEV*|ST*)'
Could you help me out?

A: The crucial part of your quote above is:

The pattern is a shell wildcard (i.e., matched using fnmatch(3)).

Shell wildcards match with *, ?, and [...] only.1  They are implicitly rooted at both ends.  For instance, the pattern a*z matches abcz, axyz, and az but not azy (doesn't end with z) nor baz (doesn't start with a).  In shell wildcard patterns, question marks match any character, asterisks match zero or more of any character, and bracketed expressions match those characters.  You can get all the DEVs with DEV*, and all the STs with ST*, but there is no syntax to match both.

1The C library fnmatch function takes flags that modify its behavior, and on systems with a GNU fnmatch, you can get some extended forms including the @(pattern1|pattern2) you were attempting.  But Git doesn't set the flag that enables this.

A: As @torek already notes: A 'regex' is not a 'pattern' (aka. 'glob'). But you can emulate the OR (|) of a regex using multiple pattern because

[...] Multiple patterns may be given; if any of them matches, the tag is shown.

So this would select both DEV* and ST* tags:
git tag --list 'DEV*' 'ST*'


text:
Q: OpenCV Face Recognition - Distance from Camera Affects Performance I am using Python 3.7 and ran a simple face recognition program with OpenCV and Haar cascades.
I noticed the recognition is much better when I am farther from the camera (one arm length) than when my face takes up most of the screen (6 inches away from camera). Why is it better at recognizing smaller faces?
I read this article on non-face regions and the parameters you can pass in to faceCascade.detectMultiScale function.

In an image, most of the image is a non-face region. Giving equal
  importance to each region of the image makes no sense, since we should
  mainly focus on the regions that are most likely to contain a picture.
  Viola and Jones achieved an increased detection rate while reducing
  computation time using Cascading Classifiers.
The key idea is to reject sub-windows that do not contain faces while
  identifying regions that do.

Parameters:
scaleFactor : Parameter specifying how much the image size is reduced at each image scale.
minNeighbors : Parameter specifying how many neighbors each candidate rectangle should have to retain it.
minSize : Minimum possible object size. Objects smaller than that are ignored.
maxSize : Maximum possible object size. Objects larger than that are ignored.

I referred to this SO post on the recommended parameter values, which I am already using. Is there anything else I can try to get around this? I want to be able to recognize the face even when I am close to the screen.


text:
Q: Round currency/number (jqGrid) I have grid, where I input a number, ex. 15.32.
How can I round this number up to 16.00?
If I have 16.01, I want to round it up to 17.00. The number will always round up.
{
    label:'Summ',
    name:'f4',
    index:'f4',
    width:120,
    search: false,
    formatter:'currency',
    formatoptions:{defaulValue:0,thousandsSeparator:' ',decimalPlaces:2,suffix:'$'}
},

A: You can use a custom formatter for that, that both ceils the number value and suffixes.
For example:
// Custom formatter that ceils all number values and suffixes .00$
function myCurrencyFormatter (cellvalue, options, rowObject)
{
    if(cellvalue == undefined) return "0.00$";
    else return Math.ceil(cellvalue) + ".00$";
}

{
    label: "Sunm",
    name:'f4',
    index:'f4',
    width:120,
    search: false,
    // Uses the custom formatter
    formatter: myCurrencyFormatter,
}

You can try it out here:
http://jsfiddle.net/Mowday/NH498/


text:
Q: Openstack Horizon Fetch Instances I would like to fetch all instances and calculate the uptime of the vcpu ram etc.
upon checking out the existing horizon code which sits at openstack_dashboard/dashboard/usage
usage = api.nova.usage_get(self.request, self.tenant_id, start, end)

I have searched the internet for a documentation for it but i am so unlucky to find one. ,
I would like to know what will be in the arguments start and end.
Thanks, I hope someone who could lead me into this.

A: You can debug your horzion with ./manage.py shell


text:
Q: VPN WIFI Device to SonicWall TZ500 I want to know if it is possible to purchase some kind of device that acts as a wifi router, but connects to the SonicWall via VPN?   The Wifi device will have to be inside the DMZ of another network, so site to site will not work, but I am hoping that somehow some sort of device can be configured to connect to the VPN as a VPN Client to the SonicWall, and what would I need to do to do so?  I tried OpenVPN, but was not having any luck.
Bottom line, I want to be able to go travel somewhere, plug this device in a hotel room eithernet port, and then automatically have WIFI that is part of my SonicWall's subnet.

A: Thanks you for your help, I was able to figure it out this way: https://www.sonicwall.com/en-us/support/knowledge-base/170505253857071


text:
Q: Rearrange layout with flex I have following html.

With css flex, I have the following layout in desktop mode:
++++++++++++++++++++++++++++++++++++++++++
+            +             +             +
+     A      +      B      +      C      +
+            +             +             +
++++++++++++++++++++++++++++++++++++++++++

I would like to rearrange divs so that in mobile mode it looks like:
++++++++++++++++++++++++++++++++++++++++++
+                                        +
+                   B                    +
+                                        +
++++++++++++++++++++++++++++++++++++++++++
+                   +                    +
+        A          +          C         +
+                   +                    +
++++++++++++++++++++++++++++++++++++++++++

Is it possible with flex trick?

A: You can achive this using flex order

#wrapper {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

#a, #b,#c{
  flex: 0 0 33.33%;
  text-align:center;
  min-height: 100px;
}
#a{
  background: red;
}
#c {
  background: blue;
}

@media (max-width:767px){
  #a {
    order: 2;
    flex: 0 0 50%;
  }
  #b {
    order: 1;
    flex: 0 0 100%;
  }
  #c {
    order: 3;
    flex: 0 0 50%;
  }
}

a

b

c

A: Yes you can surely do this layout using flexbox.
Below CSS might help you.

#wrapper{
  display:-webkit-box;
  display:-ms-flexbox;
  display:flex;
  -ms-flex-wrap:wrap;
  flex-wrap:wrap;
}
#wrapper>div{
  border:1px solid #ccc;
  padding:15px;
  -webkit-box-flex:1;
  -ms-flex:1;flex:1;
  text-align:center;
}

@media(max-width:767px) {
  #wrapper>#b{
    min-width:100%;
    -webkit-box-ordinal-group:0;
    -ms-flex-order:-1;
    order:-1;
  }
}

a

b

c


text:
Q: Posting MultipartFormData with the WSClient using java I am currently trying to post a file to a end point using the WSClient, with the following code
public Result uploadBankingFile(){
    logger.info("Uploading file to cold fusion");
    MultipartFormData<File> body = request().body().asMultipartFormData();
    MultipartFormData.FilePart<File> bankingFile = body.getFile("bankingFile");

    if (bankingFile != null) {
       String fileName = bankingFile.getFilename();
       String contentType = bankingFile.getContentType();

       //field needs to be called import
        Source<ByteString, ?> file = FileIO.fromFile(bankingFile.getFile());
        MultipartFormData.FilePart<Source<ByteString, ?>> fp = new MultipartFormData.FilePart<>("import", fileName, "text/plain", file);
        MultipartFormData.DataPart dp = new MultipartFormData.DataPart("key", "value");

        Future<WSResponse> post = ws.url(coldFusionPath + coldFusionUploadPath).post(Source.from(Arrays.asList(fp,dp)));

        return new JsonResult("ok");
    } else {
        flash("error", "Missing file");
        return badRequest();
    }

}

I am using the framework version 2.5.15 and with java 8. The issue I am getting is
/ImportBankingData.java:58: no suitable method found for post(akka.stream.javadsl.Source<play.mvc.Http.MultipartFormData.Part<akka.stream.javadsl.Source<akka.util.ByteString,?>>,akka.NotUsed>)
[error]     method play.api.libs.ws.WSRequest.<T>post(T,play.api.http.Writeable<T>) is not applicable
[error]       (cannot infer type-variable(s) T
[error]         (actual and formal argument lists differ in length))
[error]     method play.api.libs.ws.WSRequest.post(java.io.File) is not applicable
[error]       (argument mismatch; no instance(s) of type variable(s) O,T exist so that akka.stream.javadsl.Source<O,akka.NotUsed> conforms to java.io.File)
[error]     method play.api.libs.ws.WSRequest.post(akka.stream.scaladsl.Source<play.api.mvc.MultipartFormData.Part<akka.stream.scaladsl.Source<akka.util.ByteString,?>>,?>) is not applicable
[error]       (argument mismatch; no instance(s) of type variable(s) O,T exist so that akka.stream.javadsl.Source<O,akka.NotUsed> conforms to akka.stream.scaladsl.Source<play.api.mvc.MultipartFormData.Part<akka.stream.scaladsl.Source<akka.util.ByteString,?>>,?>)
[error] ws.url(coldFusionPath + coldFusionUploadPath).post
[error] (compile:compileIncremental) javac returned nonzero exit code
[info] Compiling 1 Java source to /Users/ergun/Documents/projects/brightbook/web/target/scala-2.11/classes...
[error] /Users/ergun/Documents/projects/brightbook/web/app/co/brightbook/web/controllers/ImportBankingData.java:58: no suitable method found for post(akka.stream.javadsl.Source<play.mvc.Http.MultipartFormData.Part<akka.stream.javadsl.Source<akka.util.ByteString,?>>,akka.NotUsed>)
[error]     method play.api.libs.ws.WSRequest.<T>post(T,play.api.http.Writeable<T>) is not applicable
[error]       (cannot infer type-variable(s) T
[error]         (actual and formal argument lists differ in length))
[error]     method play.api.libs.ws.WSRequest.post(java.io.File) is not applicable
[error]       (argument mismatch; no instance(s) of type variable(s) O,T exist so that akka.stream.javadsl.Source<O,akka.NotUsed> conforms to java.io.File)
[error]     method play.api.libs.ws.WSRequest.post(akka.stream.scaladsl.Source<play.api.mvc.MultipartFormData.Part<akka.stream.scaladsl.Source<akka.util.ByteString,?>>,?>) is not applicable
[error]       (argument mismatch; no instance(s) of type variable(s) O,T exist so that akka.stream.javadsl.Source<O,akka.NotUsed> conforms to akka.stream.scaladsl.Source<play.api.mvc.MultipartFormData.Part<akka.stream.scaladsl.Source<akka.util.ByteString,?>>,?>)
[error] ws.url(coldFusionPath + coldFusionUploadPath).post
[error] (compile:compileIncremental) javac returned nonzero exit code
[error] application -

I am not sure how to resolve this issue. If anyone could point me in the right direction that would be much appreciated. Thanks

A: I'm not sure, but looking at the stack trace I think you might have imported the wrong WSClient, the one from Scala instead of the one from Java.
In general, everything with api like here in play.api.libs.ws.WSRequest.<T>post is Scala stuff. Change your import, it might solve your issue.

A: I tried below approach in latest play version and it worked for me.
I created a method getMultipartBody which returns the object in format required for wsClient post call taking multiPartData from current request as input.
public CompletionStage<Result> thirdPartyAttachment(){
    Http.MultipartFormData multipartFormData = request().body().asMultipartFormData();
    Source<? super Http.MultipartFormData.Part<Source<ByteString, ?>>, ?> multipartBody = getMultipartBody(multipartFormData.asFormUrlEncoded(),multipartFormData.getFiles());

    String url = "url_to_call";
    return wsClient.url(url)
            .post(multipartBody)
            .thenApplyAsync(response -> {
                new JsonResult("ok");
            })
            .exceptionally(e -> {
                return Results.internalServerError(prepareError());
            });
}

private Source<? super Http.MultipartFormData.Part<Source<ByteString, ?>>, ?> getMultipartBody(Map<String, String[]> dataSet, List<Http.MultipartFormData.FilePart<File>> filePartsList) {
        List<Http.MultipartFormData.Part> partList = new ArrayList<>();
        if (dataSet != null) {
            for (String field : dataSet.keySet()) {
                Http.MultipartFormData.DataPart dataPart = new Http.MultipartFormData.DataPart(field, dataSet.get(field)[0]);
                partList.add(dataPart);
            }
        }
        if (filePartsList != null) {
            for(Http.MultipartFormData.FilePart<File> filePart:filePartsList){
                Source<ByteString, ?> file = FileIO.fromFile(filePart.getFile());
                Http.MultipartFormData.FilePart<Source<ByteString, ?>> fp = new Http.MultipartFormData.FilePart<>(filePart.getKey(), filePart.getFilename(), filePart.getContentType(), file);
                partList.add(fp);
            }
        }
        return Source.from(Collections.unmodifiableList(partList));
    }


text:
Q: Counterexample for $L^p$-convergence Let $\Omega \subseteq \mathbb{R}^n$ be bounded and $p \in [1, \infty)$. Now let $(f_n)_{n \in \mathbb{N}} \subseteq L^p(\Omega)$ be a sequence and $f \in L^p(\Omega)$. Clearly,
$$
\lVert f_n - f \rVert_{L^p(\Omega)} \overset{n \rightarrow \infty}{\longrightarrow} 0 \quad \implies \quad \int_\Omega \lvert f_n \rvert^p~\mathrm{d}x \overset{n \rightarrow \infty}{\longrightarrow} \int_\Omega \lvert f \rvert^p~\mathrm{d}x.
$$
But I see no reason why
$$
\lVert f_n - f \rVert_{L^p(\Omega)} \overset{n \rightarrow \infty}{\longrightarrow} 0 \quad \impliedby \quad \int_\Omega \lvert f_n \rvert^p~\mathrm{d}x \overset{n \rightarrow \infty}{\longrightarrow} \int_\Omega \lvert f \rvert^p~\mathrm{d}x
$$
should hold. Unfortunately, I can't find a counterexample to disprove the latter. Can someone help me out and show me a counterexample for at least one combination of $\Omega$, $p$?

A: Note that integrals of non-negative functions are just non-negative numbers. Pick any non-negative convergent sequence $\{x_n\}_{n\in \mathbb N}$ and associate to each $x_n$ a function $f_n$ such that $\int_{\Omega }|f_n|^p\mathop{}\!d \mu=x_n$. Then there is no reason to be a relation between the $f_n$.
A simple counterexample could be setting $f_n:=\mathbf{1}_{[0,1+1/n]}$ for even $n$, $f_n:=\mathbf{1}_{[1,2+1/n]}$ for odd $n$ and $f:=\mathbf{1}_{[5,6]}$, then $$\int_{\mathbb{R}}|f_n|^p\mathop{}\!d \lambda =1+1/n\to 1=\int_{\mathbb{R}}|f|^p \mathop{}\!d \lambda,\quad  \text{ as }n\to \infty  $$ for any chosen $p\in [1,\infty )$ but $\|f_n-f\|_p^p=2+1/n$ for all $n$.


text:
Q: Magento 2 Migrate from Google Universal Analytics to GA4 Google Universal Analytics will be going away in July 2023 to be replaced with Google Analytics 4.

On July 1, 2023, standard Universal Analytics properties will stop
processing new hits. If you still rely on Universal Analytics, we
recommend that you prepare to use Google Analytics 4 going forward.

What is the best way to migrate from Google Universal Analytics to GA4 in older Magento 2.4 versions whilst still retaining all the eCommerce analysis provided by the current Universal Analytics module?
I am not interested in links to commercial modules.

A: Which Magento version you are using? If you using Magento version >=2.4.5, Magento already released a new module called GoogleGtag to support GA4 and also keeps the old ** GoogleAnalytics** module to support Google Universal Analytics
If you using Magento version < 2.4.5, you can create a custom module based on GoogleGtag module from Magento core version 2.4.5. I'm going to do that and then share it as an open source (free) module to help the community who use Magento versions < 2.4.5 (includes support 2.3.x). Once I have done that, I'll share it and update this answer.

A: You can setup the Google Analytics 4 tracking alongside Universal Analytics and run both trackings parallelly until the UA expires. I have across a blog that contains the detailed GA4 setup mentioning every step required. You can use this guide to complete the GA4 setup by yourself. https://www.scommerce-mage.com/blog/how-to-setup-magento-2-ga4google-analytics-4.html

A: Instruction on how to configure GA4 with GTM for Magento 2 Store. Easy Step by Step guide configures GA4 Extension in your Magento 2. https://www.magedelight.com/resources/how-to-configure-ga4-with-gtm-in-magento-2-store/


text:
Q: Can't install PuLP in Anaconda, unsatisfiableError Hi im trying to install PulP in Anaconda and obviously i googled it so I know that you should just write:
conda install -c primer pulp

writing this in the Anaconda i get:
Fetching package metadata.......
Solving packackage specifications: .

and then the Error pops up:
unsatisfiableError: The following specificantios were found to be in
conflict:
- pulp -> python 2.7*
- python 3.6*

whats the problem doesnt pulp work for python 3?

A: It does work with python 3 perhaps just install it with pip
pip install pulp
Make sure you are running the right pip for your anaconda install


text:
Q: Flutter build split doesn't creating x86 apk? Flutter doesn't create x86 apk but the other three apk's created.
Recently released Android application firebase crashes heads up with x86 couldn't find "libflutter.so". So I thought we have released a bundled app in that x86 lib folder or lib releated may not created so crash happened. And I tried to create a split apk in the local machine using flutter build apk --split-per-abi its created three files "arm64-v8a", "armeabi-v7a", "x86_64" but x86 apk not created I have no idea or any configuration I missed to do it?
Help me out. Thanks in advance!
maclap@root flutter-app-v3 % flutter build apk --split-per-abi

Building without sound null safety
For more information see https://dart.dev/null-safety/unsound-null-safety

Removed unused resources: Binary resource data reduced from 1109KB to 1052KB: Removed 5%
Removed unused resources: Binary resource data reduced from 1109KB to 1052KB: Removed 5%
Removed unused resources: Binary resource data reduced from 1109KB to 1052KB: Removed 5%
Running Gradle task 'assembleRelease'...                           68.0s
✓  Built build/app/outputs/flutter-apk/app-armeabi-v7a-release.apk (18.1MB).

In, android/app/build.gradle
defaultConfig {
    ...
    ndk {
        abiFilters "arm64-v8a", "armeabi-v7a", "x86", "x86_64"
    }
}

A: flutter build apk --split-per-abi only generate three apk files source
1 - app-armeabi-v7a-release.apk (ARM 32-bit)
2 - app-arm64-v8a-release.apk (ARM 64-bit)
3 - app-x86_64-release.apk (x86 64-bit)

Flutter does not currently support building for x86 Android Source
Solution: You can run flutter build apk command to generate app-release.apk fat APK that is single APK runs on multiple architectures


text:
Q: What does the ls ????? command do? I was trying to learn more about Linux and came across the command ls ????? and it displayed a few files in the directory but I am not really sure what it is specifically displaying. I tried to use the man to explain it further but I couldn't find anything. Could someone please explain?

A: ls is a command on its own - try man ls for an explanation.
ls ? may give a help summary in some Linux versions.
ls with multiple ? is pointless as far as I know unless all the files listed have just five characters?.


text:
Q: How to suppress transparency of PDF using \includegraphics I have multiple PDF floats in my document using \includegraphics. It turns out the PDFs have transparent background, and one overlaps the page number which looks bad.
(I was initially hoping to suppress the page number, but that turned out to be surprisingly difficult and the solutions here did not help.)
Instead, is there an option to suppress the PDF transparency (so that it blocks the page number from view)? Equivalently, is there an option to add a white background colour to the image?
MWE:
\documentclass[11pt]{article}
\usepackage[a4paper]{geometry}
\usepackage[]{garamondx}
\usepackage[scaled=.84]{beramono}
\usepackage{amsmath,amsthm,amssymb}
\usepackage[garamondx,cmbraces]{newtxmath}
\useosfI
\usepackage[utf8x]{inputenx}
\usepackage{microtype}
\usepackage{subfig}
\usepackage{graphicx}

\begin{document}

Lorem ipsum dolor sit amet.

\begin{figure}
\centering
\subfloat[\label{fig:disttime1}A specific solution with no attempt at generality.]{\includegraphics[scale=0.7, trim={4cm 7cm 1cm 0}, clip]{disttime1.pdf}}\\
\caption{Students' responses to a challenging proof problem.}
\label{fig:disttime}
\end{figure}

\begin{figure}
\ContinuedFloat%
\centering%
\vspace{-1.5cm}%
\subfloat[\label{fig:disttime2}This student has hit on the idea of the lines crossing, but strictly speaking at the point he has identified the person would be $6\ \mathrm{km}$ \emph{up} the hill one day and $6\ \mathrm{km}$ \emph{down} the hill the other.]{\includegraphics[scale=0.7, trim={5.5cm 16cm 0cm 2cm}, clip]{disttime2.pdf}}\\
\subfloat[\label{fig:disttime3}This student has understood the generality required, but has not attempted to justify the universal claim.]{\includegraphics[scale=0.7, trim={3cm 7.5cm 0.5cm 3cm}, clip]{disttime3.pdf}}
\caption{(con't) Students' responses to a challenging proof problem.}
\end{figure}

\end{document}

On the below screenshots, there is no issue with pages 1 and 2, but on page 3 the figure is taller than the text height and overlaps the page number.
Note: I am aware that having such a large float is probably bad style; I am not interested in splitting these figures across to a third page, or making them smaller (as they would become unreadable).
I have also added a screenshot of page 3 with \fbox added around each \includeimage, as requested by @daleif.

A: For you first question: No, there is no option to suppress the transparency of PDFs which use that feature when including these PDFs whith pdftex/xetex/luatex.
What you are asking for is called PDF transparency flattening and that can be done by other tools.


text:
Q: Relationship between a diagonalisable matrix and the change of basis matrix With reference to I.N. Herstein Topics in Algebra theorem 6.3.2, it states that if $V$ a n-dimensional vector space over field $F$, and the linear transformation $T$ has the matrix $m_1(T)$ has the basis $v_1, ..., v_n$ and the matrix $m_2(T)$ in the basis of $w_1,...,w_n$, then there is a matrix C such that $m_2(T)=Cm_1(T)C^{-1}$. This is oddly similar to the diagonalisation of a matrix where $A=PDP^{-1}$. In this case, I know that the matrix $D$ is the matrix of eigenvalues of $A$, which is in the basis of $v_1, v_2, v_3$, the corresponding eigenvectors of $A$, and this is identical to the definition of $m_1(T)$ in the theorem.
I would like to show that $P$, the matrix of eigenvectors, satisfy the matrix $C$ in the theorem, that maps $v_1, ..., v_n$ to  $w_1,...,w_n$ which I am not sure how, since I do not know which basis $A$ is in.


text:
Q: How to style a chart to omit the excess chart area surround the chart I am using Silverlight Toolkit from http://silverlight.codeplex.com/ and am having an issue with the styling. Based off microsoft's documents I see the chart is made up of 4 basic components.

*

*ChartAreaStyle ==>  Grid

*LegendStyle    ==>  Legend (a control similar to an ItemsControl with a Title)

*PlotAreaStyle  ==>  Grid

*TitleStyle     ==>  Title (a ContentControl)

ref http://msdn.microsoft.com/en-us/expression/dd433476.aspx
My Question Is
How can I fill the chart container with the chart itself instead of having an empty surrounding area and if possible omit the legend?
I am still trying to wrap my head around xaml and control templates etc. I know it probably can be done using that, I just don't know how.
Here is an example of what I am trying to achieve:

Here is what it looks like now:

A: So I copied the style of the Chart control from the Toolkit source code and removed redundant elements from the template.

The styles definitions look so:
<UserControl.Resources>
    <Style x:Key="ChartWithoutPaddings" TargetType="chart:Chart">
        <Setter Property="Padding" Value="0" />
        <Setter Property="BorderThickness" Value="0" />
        <Setter Property="ChartAreaStyle">
            <Setter.Value>
                <Style TargetType="Panel">
                    <Setter Property="MinWidth" Value="100" />
                    <Setter Property="MinHeight" Value="20" />
                </Style>
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="chart:Chart">
                    <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}">
                        <chartingprimitives:EdgePanel x:Name="ChartArea" Style="{TemplateBinding ChartAreaStyle}">
                            <Grid Canvas.ZIndex="-1" Style="{TemplateBinding PlotAreaStyle}" />
                        </chartingprimitives:EdgePanel>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Style x:Key="EmptyDataPoint" TargetType="Control">
        <Setter Property="Background" Value="Black" />
        <Setter Property="Template" Value="{x:Null}" />
    </Style>

    <Style x:Key="OnePixelLine" TargetType="Polyline">
        <Setter Property="StrokeThickness" Value="1" />
    </Style>
</UserControl.Resources>

You should also hide axes and specify height and width of the chart:
<chart:Chart Style="{StaticResource ChartWithoutPaddings}"
             VerticalAlignment="Center" HorizontalAlignment="Center"
             Width="200" Height="30">
    <chart:LineSeries ItemsSource="{Binding Items}" IndependentValuePath="Title" DependentValuePath="Value"
                      DataPointStyle="{StaticResource EmptyDataPoint}" PolylineStyle="{StaticResource OnePixelLine}"  />

    <chart:Chart.Axes>
        <chart:CategoryAxis Orientation="X" Height="0" Opacity="0" />
        <chart:LinearAxis Orientation="Y" Width="0" Opacity="0" />
    </chart:Chart.Axes>
</chart:Chart>


text:
Q: Wear OS (Android Wear) wrong timestamps I am trying to use the sensors in a few smartwatches running Wear OS. After sampling for a few seconds (it usually runs for 45 seconds but also up to a few minutes) the timestamps are wrong.
The timestamps jump several seconds or minutes in to the future, and then all the timestamps come at more or less the same time before or after this "break". So it ends up being a break with no timestamps and then many timestamps before returning to normal, and then it usually happens again.
The other values from the sensors (X,Y,Z) seem to be sampled at the correct time when I look at the data in a graph, but only if the X axis does not have the timestamps. It can happen after just a couple of seconds and can happen up to 6-7 times in that 45 second window.
Some info about the code:

*

*Sampling from Accelerometer, Gyro and Magnetometer (if available).

*Sampling is done in a service (foreground service).

*Partial wake lock is set when starting the sampling (Log.d shows that the wakelock is held throughout the 45 seconds).

*maxReportLatencyUs = 0 (tested with other numbers up to ten seconds)

*Sensor delay = Fastest (tested with Game)

*Same listener used for all sensors

There are usually 200 samples between the "breaks/jumps", but it can vary. They usually last for 2000, 4000 or 14000 ms.
I have only tested the app on 3 watches.
The watches with this problem are:

*

*Huawei Watch 2 Classic (This is the worst one)

*Tag Heuer

The watch it does not happen on:

*

*Fossil Q Explorist Gen 3

This does not mean it would never happen on the Fossil watch, but I have not seen this happen there.
Here you can see the timestamps jumping so the data looks strange (accelerometer (X) on Y axis and timestamps on the X axis). When showing the data without the timestamps, it looks pretty much like it is supposed to and can be seen here.
This (timestamps on the Y axis (blue line). It was sampling for 6 min (360,000 ms)) shows how the timestamps change over time. It seems to end at the right spot(almost.. (365,153 ms)), but on the way there, it seems to be a little bit slow and then catch up by jumping 14000 ms every 200 samples..? This is a 3 min sampling with a Fossil Q Explorist Gen 3. This is what it should look like, the blue line is straight and laying behind the orange line.
This graph shows the difference between each timestamp (a[n+1] - a[n]). You can see exactly when it happens and how far the "jump" was.
Does anybody know what I am doing wrong here?


text:
Q: Angular 5 and slide up animation I'm creating an animation that changes(slides up) element height to 0 and returns it to initial height. Why element returns to initial height after 'hide' animation. does anyone know how to fix this? Also element height is changing by media queries. Link to project:
https://stackblitz.com/edit/angular-zzbwnc
Animation:
animations: [
    trigger("myAnimationTrigger", [
     transition('hide => show', [
      style({ height: '0', opacity: 0 }),
      animate('1500ms', style({ height: '*', opacity: 1 })),
      ]),
      transition('show => hide', [
        style({ height: '*', opacity: 1 }),
        animate('1500ms', style({ height: '0px', opacity: 0 })),
      ]),
    ])
  ]

https://stackblitz.com/edit/angular-zzbwnc

A: I was able to get your StackBlitz work by changing your animation code to the following:
trigger("myAnimationTrigger", [
  state('show', style({
      'max-height': '300px', 'opacity': '1'
  })),
  state('hide', style({
      'max-height': '0px', 'opacity': '0'
  })),
  transition('hide => show', [
    animate('1500ms', style({ 'max-height': '300px', 'opacity': '1' })),
  ]),
  transition('show => hide', [
    animate('1500ms', style({ 'max-height': '0px', 'opacity': '0' })),
  ])
])


text:
Q: How to fork & patch npm modules for angular2 I have read this fork and patch npm modules for set npm dependency to modules hosted in github, but it seems this doesn't work for angular2 type script module.
How to solve it, actually here is my fork module


text:
Q: How can I show that $\mathbb{E}(Y|\sigma(X))$ satisfies the abstract definition of conditional expectation? More precisely let $(X,Y)$ is a pair of continuous random variables with joint density function $f(x,y)$ and we assume $\mathbb{E}(|Y|) < +\infty$. Define
$$H(X) = \int\limits_{-\infty}^\infty \frac{f(x,y)}{f_X(x)}y dy,$$
where $f_X(x) = \int\limits_{-\infty}^\infty f(x,y) dy$.
For $H(X)$ to satisfy the definition we have to show that

*

*$\mathbb{E}(|H(X)|) < +\infty$,

*$H(X)$ is $\sigma(X)$-measurable and

*$\mathbb{E}(Y \cdot I_A) = \mathbb{E}(H(X) \cdot I_A)$, for every $A \in \sigma(X)$, where $I_A$ is the indicator of $A$.

This is a homework assignment for me, so I only need some hints, not a full solution.

A: Hint on third bullet:
On base of $H\left(x\right)f_{X}\left(x\right)=\int f\left(x,y\right)ydy$
we find for suitable functions $g$:
$$\mathbb{E}\left[H\left(X\right)g\left(X\right)\right]=\int H\left(x\right)g\left(x\right)f_{X}\left(x\right)dx=\int\int f\left(x,y\right)yg\left(x\right)dydx=\mathbb{E}\left[Yg\left(X\right)\right]$$


text:
Q: Visual Studio 2015 doesn't compile with @ symbols in folder names "4>CSC : error CS2011: Error opening response file '\xxSomePathxxx\yyMyProjectyy\Framework\@Core\Controllers-BackEnd\AdminCartController.Orders.cs'"
The actual path is "@Framework\@Core", however it seems to be trying to remove the first @ and look for just "Framework\@Core".  I don't know why.
If I remove the @ from the beginning of the @Framework folder name (which is a first level folder in the project), it will compile.  I also tried renaming the @Framework to @SomeFolder thinking maybe framework was reserved.  Its the leading @ symbol.  If I remove it, it compiles.  If I put it back, again with errors for EVERY file in that folder.
Its perfectly happy with @ in folder names below the first tier.  But not happy with them at all in the first tier.
The reason for putting the @ in there is so these specific folders will sort to the top of the solution explorer.  Its perfectly happy with folders beginning with underscore characters (_) which I used for other folders because I wanted them under the @ named folders.  Not @ though.
Is the @ a reserved character and are there others?  Where is this documented if they are?

A: All Credit to @jessehouwing - this is his answer. I just am posting to help the next guy...
The @ sign is a special character in MsBuild, it is used to pass a reference to the items in an ItemGroup.
You can escape the @ with %40 in the .csproj file to see if that fixes it. (msdn.microsoft.com/en-us/library/bb383819.aspx) –
jessehouwing
So the current bootstrap link for the Bootstrap Popper (which is what brought me here as they have decided to start a folder with an @ sign) becomes:
<script src="https://cdn.jsdelivr.net/npm/%40@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script>


text:
Q: How to use Tensorflow with a GTX 1050 mobile edition? I recently started programming with Tensorflow on python. I wanted to improve the calculation-power using my GTX 1050 in my laptop but i didn't success...
After installing all the required libraries and softwares (CUDA 9.0, CuDNN for CUDA 9.0, imported : tensorflow and tensorflow-gpu...), I tryed basic example from the Tensorflow website :
import tensorflow as tf
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
print(sess.run(c))`

but this return the following answer (I translate it right after) :
2018-05-03 19:15:59.540038: I T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
Device mapping: no known devices.
2018-05-03 19:15:59.543664: I T:\src\github\tensorflow\tensorflow\core\common_runtime\direct_session.cc:284] Device mapping:

MatMul: (MatMul): /job:localhost/replica:0/task:0/device:CPU:0
2018-05-03 19:15:59.546930: I T:\src\github\tensorflow\tensorflow\core\common_runtime\placer.cc:886] MatMul: (MatMul)/job:localhost/replica:0/task:0/device:CPU:0
b: (Const): /job:localhost/replica:0/task:0/device:CPU:0
2018-05-03 19:15:59.547254: I T:\src\github\tensorflow\tensorflow\core\common_runtime\placer.cc:886] b: (Const)/job:localhost/replica:0/task:0/device:CPU:0
a: (Const): /job:localhost/replica:0/task:0/device:CPU:0
2018-05-03 19:15:59.547597: I T:\src\github\tensorflow\tensorflow\core\common_runtime\placer.cc:886] a: (Const)/job:localhost/replica:0/task:0/device:CPU:0
[[22. 28.]
[49. 64.]]

This heavy message mean that the only device available on my laptop is my CPU but I have a GTX 1050.
I tried to add this line at the begining :
with tf.device("/device:gpu:0"):
I spare you all the insult of the command line but it return me this :
Operation was explicitly assigned to /device:gpu:0 but available devices are
[ /job:localhost/replica:0/task:0/device:CPU:0 ].
Make sure the device specification refers to a valid device.

Is anyone have an idea of the origin of my issue ? Or someone have ever overcome this issue and could help me ?

A: If it could help anyone i delete tensorflow-gpu and installed it again via the pip command (pip install tensorflow-gpu==1.8), I specify the version 1.8 and it magically worked.


text:
Q: How can I convert from a class with a 2D vector of chars to a 2D vector of another obj with a char variable? I'm still new to this so my apologies in advance if I provide too much or not enough information for my problem.

The Run Down
This question isn't a rogue like game related question, but for a little background of what my program does.. is to be similar to a rogue like game.
Ok, so I had a class that had a member 2D char vector (the chars were manipulated to represent a "dungeon"). Everything worked seamlessly. I wanted to expand what my program could do so I decided to create a new class to replace the 2D vector of chars so that the char is just the visual representation of the new class and other variables can be stored along with that char.
For simplistic sake, I tried to remove what isn't necessary for this question. This new class is called Tile - which represents a space being used for the dungeon level. Tile has:

*

*a char variable called displayChar.. defaults to ' ' changes to represent what it contains

*(other variables..)

The Problems / My Poor guesses
I'm not the best at completely understanding some concepts of programming syntax/implementation, so please don't judge.

*

*The way I filled the vector of chars, I resized it to the width of the game board, and set everything to ' ' since all the values were chars

*I think I need to fill it with new, Tile objects and push them to the
2D Tile vector?

*My other methods that manipulated the char values are giving errors.

*I think I should change the methods to take a pointer to the Tile
object and use the setDisplayChar(' ') method to change its
value?

*My at(int, int) method used to return the char at that location

*I thought I could change it to "return m_vvTiles[y][x].getDisplayChar()" but I get an error

I'm bad at changing how something works and I usually end up making a mess out of my code. I'll post the code that is relevant for this. I'd greatly appreciate any help you can offer. And please let me know if I need to add more. (I'll try to keep the code minimized to only related methods). Thanks!

DungeonLevel.h
#include "Tile.h"
#include <vector>
#include <random>

class DungeonLevel {
public:
    DungeonLevel(int iWidth, int iHeight, std::mt19937 & mt);
    ~DungeonLevel(void);

    void dump();
    char at(int x, int y);

    int getWidth();
    int getHeight();

private:
    std::vector<std::vector<Tile>> m_vvTiles; //Tile was char

};

DungeonLevel.cpp
#include <iostream>
#include <random>
#include "DungeonLevel.h"

using namespace std;

DungeonLevel::DungeonLevel(int iWidth, int iHeight, std::mt19937 & mt){
    // Initialize the blank vector
    m_vvTiles.resize(iHeight);

    for(auto it = m_vvTiles.begin(); it != m_vvTiles.end(); it++ ){
    //      Tile tempTile = new;?
            (*it).resize(iWidth,' ');
    }

    // divide the level into 4x2 chunks
    int iChunkWidth = iWidth / 4;
    int iChunkHeight = iHeight / 2;

    // Taking the easy way out, and generating
    // a loop of tunnels first to drop rooms on to
    for( int x = (iChunkWidth/2); x <= ((3 * iChunkWidth) + (iChunkWidth/2)$
            m_vvTiles[iChunkHeight/2][x] = '#';
            m_vvTiles[iChunkHeight + (iChunkHeight/2)][x] = '#';
    }

    for( int y = (iChunkHeight/2); y <= (iChunkHeight + (iChunkHeight/2)); $
            m_vvTiles[y][iChunkWidth/2] = '#';
            m_vvTiles[y][(3 * iChunkWidth) + (iChunkWidth/2)] = '#';
    }

 void DungeonLevel::dump(){
    for( auto itOuter = m_vvTiles.begin(); itOuter != m_vvTiles.end(); itOu$
            for( auto itInner = (*itOuter).begin(); itInner != (*itOuter).e$
                    cout << *itInner.getDisplayChar(); ///Updated:: CAUSING ERROR//
            }

            cout << endl;
    }
}

//SEVERAL IRRELEVANT LINES FOR THIS PROBLEM..

}

char DungeonLevel::at(int x, int y){
    return m_vvTiles[y][x].getDisplayChar();
    //return m_vvTiles[y][x]; WORKED BEFORE
}

Tile.h
#include "Entity.h"
#include <vector>

class Tile : public Entity {
public:
    Tile(void);
    virtual ~Tile(void);
    //void setEntity(Entity * entityToSet); BOTH IRRELEVANT
    //Entity * getEntity();
    void setDisplayChar(char displayCharToSet);
    char getDisplayChar();
    //virtual void dumpObjectData(); IRRELEVANT AT THIS TIME

private:
    char displayChar;
    //Entity * theEntity; IRRELEVANT AT THIS TIME
};

Tile.cpp
#include "Tile.h"
#include "Entity.h"

using namespace std;

Tile::Tile(void){
    displayChar = '.';
    //theEntity = NULL;
}

Tile::~Tile(void){

}

void Tile::setDisplayChar(char displayCharToSet){
    displayChar = displayCharToSet;
}

char Tile::getDisplayChar(){
    return displayChar;
}

*Heres my existing error: *
For the method dump() in DungeonLevel.cpp,

A: Some of your questions with my answers
I think I need to fill it with new, Tile objects and push them to the 2D Tile vector?
No you need to resize it and fill it with Tile objects. Pretty much like you did when it was a char array. new doesn't come into it.
I think I should change the methods to take a pointer to the Tile object and use the setDisplayChar(' ') method to change its value?
I would use a reference.
I thought I could change it to return m_vvTiles[y][x].getDisplayChar() but I get an error.
That sounds right to me, what error did you get?
Everything about your redesign sounds well motivated to me. Good idea to make a back up before going on a major reorganization however.


text:
Q: ModuleNotFoundError: No module named 'networkx' 9 in spyder IDE. I want to import networkx for my project.
So I installed it using  pip install networkx. It got successfully installed. But when I try to import it it shows ModuleNotFoundError: No module named 'networkx'.
I searched many posts. All I gone through advices to use pip install networkx.
Can anyone help with this?


text:
Q: I need to find the 9th positive integer that is a multiple of 4, 13, 14, 26, and 50 using python: Why doesn't this code work? I am getting a continuous loop...
solution = 0
multiple = 0
max_bound = 100000
i = 1

while i < max_bound:
    if (i % 4 == 0) and (i % 13 == 0) and (i % 14) and (i % 26 == 0) and (i % 50 == 0):
        multiple += 1
        if multiple == 9:
            solution = i
            break
    i += 1

if multiple == 9:
  print("#1 : 9th Multiple ::", "Correct." if solution == 81900 else ("Wrong: " + str(solution)))

A: You just missed the 14 verification you used (1 % 14) instead of (i % 14 == 0) which returns 0(False) when the number is divisible by 14 instead of True and with the and operator it doesn't enter the if statement.
solution = 0
multiple = 0
max_bound = 100000
i = 1

while i < max_bound:
    if (i % 4 == 0) and (i % 13 == 0) and (i % 14 == 0) and (i % 26 == 0) and (i % 50 == 0):
        multiple += 1
        if multiple == 9:
            solution = i
            break
    i += 1

if multiple == 9:
    print("#1 : 9th Multiple ::", "Correct." if solution == 81900 else ("Wrong: " + str(solution)))


text:
Q: FLASK - You have an error in your SQL syntax near '%(site_id)s' at line 1 I' like to have a small explanation about Flask, Something I don't understand. I'm looking to get DATA from Database by an ID. The ID is my route parameter.
I've create my route, but I'm having an error, And I don't understand What they are requesting in fact ? An element from Database ?

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%(site_id)s' at line 1

My route code :
    #Construct app
app = Flask(__name__)
app.config.from_object('config')
app.config.from_object('secret_config')

#Database functions
def connect_db () :
    g.mysql_connection = mysql.connector.connect(
        host = app.config['DATABASE_HOST'],
        user = app.config['DATABASE_USER'],
        password = app.config['DATABASE_PASSWORD'],
        database = app.config['DATABASE_NAME']
    )

    g.mysql_cursor = g.mysql_connection.cursor()
    return g.mysql_cursor

    def get_db () :
        if not hasattr(g, 'db') :
            g.db = connect_db()
        return g.db

@app.teardown_appcontext
def close_db (error) :
    if hasattr(g, 'db') :
        g.db.close()

@app.route('/historique/<int:site_id>')
def historique(site_id):

db = get_db()

db.execute('SELECT * FROM sites s JOIN historique h ON h.site_id WHERE `s.site_id = %(site_id)s', {'id': site_id})

entries = db.fetchall()
return render_template('historique.html',  entries = entries)

And Here is my HTML Code
{% extends 'layout.html' %}

{% block titre %}
    Acceuil
{% endblock %}

{% block body %}

Historique d'activité pour  {{ entrie.0 }}

{% for entrie in entries %}
{% endfor %}
{% endblock %}

I only like to understand. Thanks a lot for your help.

A: I think, you have a mistake when you are formatting your string with sql query.
Try this
@app.route('/historique/<int:site_id>')
def historique(site_id):
    db = get_db()
    query = 'SELECT * FROM sites s JOIN historique h ON h.site_id WHERE `s.site_id = {site_id}'.format(site_id=site_id)
    db.execute(query)
    # ... rest of the code ...

And yes, this backtick before s.site_id is very suspicious.


text:
Q: MySQL join to two tables for different summaries I'm trying to join a Clients table to a Timesheets table twice, to get two summaries.
    select * from Clients;
    +-----------+-------+
    | Unique ID | Name  |
    +-----------+-------+
    |         1 | James |
    |         2 | Jill  |
    +-----------+-------+
    2 rows in set (0.00 sec)

    select * from Timesheets;
    +-----------+-------+----------+
    | Client ID | Hours | Category |
    +-----------+-------+----------+
    |         1 |   1.5 | Onsite   |
    |         1 |   1.5 | Onsite   |
    |         1 |     1 | Remote   |
    |         2 |   1.5 | Remote   |
    +-----------+-------+----------+
    4 rows in set (0.00 sec)

I want to join from Clients to Timesheets twice, once to get the total Onsite Hours, and once to get the Remote hours.
If I do them separately, they work fine.
E.G. This:
    SELECT Clients.`Unique ID`, Clients.Name, sum(onsite.`Hours`) as `Onsite Total Hours`
    FROM Clients
    LEFT JOIN Timesheets AS onsite
         ON Clients.`Unique ID`=onsite.`Client ID` AND onsite.Category='Onsite'
    GROUP BY Clients.`Unique ID`;

Returns:
    +-----------+-------+--------------------+
    | Unique ID | Name  | Onsite Total Hours |
    +-----------+-------+--------------------+
    |         1 | James |                  3 |
    |         2 | Jill  |               NULL |
    +-----------+-------+--------------------+

And this:
    SELECT Clients.`Unique ID`, Clients.Name, sum(remote.`Hours`) as `Remote Total Hours`
    FROM Clients
    LEFT JOIN Timesheets AS remote
         ON Clients.`Unique ID`=remote.`Client ID` AND remote.Category='Remote'
    GROUP BY Clients.`Unique ID`;

Returns:
    +-----------+-------+--------------------+
    | Unique ID | Name  | Remote Total Hours |
    +-----------+-------+--------------------+
    |         1 | James |                  1 |
    |         2 | Jill  |                1.5 |
    +-----------+-------+--------------------+

BUT, when I run this:
    SELECT Clients.`Unique ID`, Clients.Name, sum(onsite.`Hours`) as `Onsite Total Hours`, sum(remote.`Hours`) as `Remote Total Hours`
    FROM Clients
    LEFT JOIN Timesheets AS onsite
         ON Clients.`Unique ID`=onsite.`Client ID` AND onsite.Category='Onsite'
    LEFT JOIN Timesheets AS remote
         ON Clients.`Unique ID`=remote.`Client ID` AND remote.Category='Remote'
    GROUP BY Clients.`Unique ID`;

    +-----------+-------+--------------------+--------------------+
    | Unique ID | Name  | Onsite Total Hours | Remote Total Hours |
    +-----------+-------+--------------------+--------------------+
    |         1 | James |                  3 |                  2 |
    |         2 | Jill  |               NULL |                1.5 |
    +-----------+-------+--------------------+--------------------+

As you can see from above, the total shown for James Onsite is correct, but Remote isn't. The '1' has been counted twice...

A: Try using case when then like:
SELECT c.uniqueId, c.name, SUM(CASE WHEN t.category='Onsite' THEN t.Hours ELSE 0 END) AS 'Onsite', SUM(CASE WHEN t.category='Remote' THEN t.Hours ELSE 0 END) AS 'Remote'
FROM clients c INNER JOIN Timesheets t ON c.uniqueId = t.clientId
GROUP BY c.uniqueId

A: You can do it like this:
SELECT DISTINCT a.`UniqueID`, a.Name, sum(case when b.Category='Remote' then b.`Hours` end) as `Remote Total Hours`, sum(case when b.Category='Onsite' then b.`Hours` end) as `Onsite Total Hours`
    FROM Clients a, Timesheets b
    WHERE a.`UniqueID`=b.`ClientID`
    GROUP BY a.`UniqueID`;

Take a look at this SQL Fiddle where you can also do tests.


text:
Q: Changes in code does not appear after making pull from git repository I'm working with Git in Eclipse, so every time when I tried to pull my repository the changes from my last commit does not appear in project's code. What have I missed?

A: Ok, I solved it with merging the remote and local branch with reducing conflicts by remote side.


text:
Q: Android clear activity from memory In my app I have a SIP calling feature.When the app is not opened and it is cleared from the system memory and it receives incoming call it opens the call activity from a SIP service. When the call is disconnected, I finish the activity.But the issue is, the activity is still in the memory (when home button is pressed).I want that activity to not be in the memory.Like whats app call behavior that don't keep activity in the memory when the app was killed i.e., not in the memory.
From SIP service I call it like this.
Intent intentIncomingCall = new Intent(getApplicationContext(), CallActivity.class);
intentIncomingCall.putExtra("DisplayName", callerDisplayName);
intentIncomingCall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentIncomingCall);

and on call disconnect, I just simple stop the service and call finish() on activity.
I have tried adding flags and exit(), things but nothing works.

A:  android:allowTaskReparenting="false"
        android:excludeFromRecents="true"
        android:launchMode="singleTask"
        android:permission="android.permission.USE_SIP"
        android:screenOrientation="portrait"
        android:taskAffinity=""

Try adding above properties to activity in manifest

A: Add line below finish() method :
finish();
System.exit(0);

A: when callClosed callback,
 System.exit(0);
 or
 android.os.Process.killProcess(android.os.Process.myPid());


text:
Q: Percent difference of time series list with empty element I want to take the percent difference of a time series list, but I'm running into an error when the list contains an empty list() element.
For example, given a list myList that looks like:
set.seed(230)
zoo.Date <- as.Date("2003-02-01") + c(1, 3, 7, 9, 14) - 1
myList <- list(zoo(c(NA,rnorm(4)), zoo.Date),
           zoo(c(rnorm(4), NA), zoo.Date),
           list(),
           zoo(c(rnorm(2), NA, rnorm(2)), zoo.Date))

I can take the difference of each element with myList %>% lapply(function(x) diff(x))
But as soon as I try to divide by the previous element myList %>% lapply(function(x) diff(x) / lag(x, -1)), I get the error Error in attr(x, "tsp") <- c(1, NROW(x), 1) : cannot assign 'tsp' to zero-length vector.
The problem is the list() element. I could get rid of it, but I want to make sure that the fourth object in myList corresponds to the fourth object of the resulting (lagged) list. In other words, I want the output to look like:
[[1]]
2003-02-03 2003-02-07 2003-02-09 2003-02-14
        NA  -1.431227   2.245691   0.100597

[[2]]
2003-02-03 2003-02-07 2003-02-09 2003-02-14
-0.9078077 12.8523189 -1.2523403         NA

[[3]]
NA

[[4]]
2003-02-03 2003-02-07 2003-02-09 2003-02-14
 -1.177138         NA         NA  -2.203719

Or with [[3]] as list() or NULL or something else empty.
I've tried using things like myList %>% unlist(recursive=F) ... and myList %>% lapply(function(x) ifelse(length(x) == 0, NA, x)) %>% lapply(function(x) diff(x) / lag(x, -1)) but neither work.

A: One way around this is to use tryCatch to catch the error raised by the empty list element and return NA (or whatever else):
lapply(myList, function(x) tryCatch(
  { diff(x) / lag(x, -1) },
  error=function(e){ NA }
  ))

# [[1]]
# 2003-02-03 2003-02-07 2003-02-09 2003-02-14
#         NA  -1.431227   2.245691   0.100597
#
# [[2]]
# 2003-02-03 2003-02-07 2003-02-09 2003-02-14
# -0.9078077 12.8523189 -1.2523403         NA
#
# [[3]]
# [1] NA
#
# [[4]]
# 2003-02-03 2003-02-07 2003-02-09 2003-02-14
#  -1.177138         NA         NA  -2.203719


text:
Q: Range filters - accept each date I am using range filters in elasticsearch with different options like
"date" : { "gte" : "now-1d" }
"date" : { "gte" : "now-1y" }

(it depends on the value of an variable)
Is it possible to define a keyword to accept all kinds of date, even if there is no field date?
Maybe something like:
"date" : { "gte" : _all }

A: Have you tried using "exists"?
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html
You should be able to combine two filters with bool - should /should not and filter on date gte nnnn OR not exists field: date
(I'm assuming you want to filter on date range if you have a date, and include results where the date is missing as well)


text:
Q: expecting high traffic ..no time to change dns I am expecting high traffic ..no time to change dns. My existing shared godaddy server may fail. i have less than few hours in hand. i have a another dedicated server ...can i transfer traffic /bandwith /load to dedicated server. what are possible solutions.
thanks.
sk

A: Reduce bandwidth - You may want to use a free CDN such as CoralCDN or SimpleCDN and temporarily redirect visitors to the CDN domain. That's what people normally do for the slashdot effect.
Reduce CPU load - You could also present a static cache of your site made using httrack or similar tool instead of a full dynamic one.
Spread the load - Varnish can cache some content and if correctly configured, can do a lot more, including load balancing over multiple servers.

A: You can change your DNS now and it will have an impact, most definitely. However, if you are storing information server-side (I don't mean session state stuff, I mean taking orders, user input, content whatever...) then this might not be practical.
It takes a full 24 hours for propagation to occur, but if you've got a static-ish site, you can definitely change now and if you are a small to medium site expecting a large traffic spike then the majority of users will be redirected to the new site.
What else you can do depends on your situation. If you are allowing users to login, post to forums, take input etc. then you're going to have a bit of trouble. You can do stuff on the application side, but it's a lot of work, probably not much you can do in a couple of hours.  Again, we need more information here to be specific.
However, if you have relatively static content. Like for example, if you were posted up on slashdot then you can have a look at overriding some of the dynamically generated pages with static pages.

*

*grab the full HTML of the page from your browser

*copy and paste it into a file

*re-upload it back to your webserver

*use mod_rewrite in a .htaccess file to serve that file for any requests to the original URL

You need to be far more specific with what you're running on the site to give any more specific information. In general, you would be recommended running a caching proxy, but that presumably isn't possible on a shared server.


text:
Q: Section-wise numbering in Word I have a document divided into the following sections:

*

*Cover Page

*TOC

*Main Content

*Appendices

*

*Appendix A

*Appendix B

*Appendix C

I have inserted section breaks to have four sections in the document.
Now, in the Appendix section, I wish to have the numbering in the following format in the footer: 'Appendix A-1... Appendix A-2.... Appendix A-n',  'Appendix B-1... Appendix B-n'.
I have been able to get the numbering restarted once I get to the Appendix section. But how do I insert the title of the appendix, that is, Appendix A or B, before the number?
Can you please help me how I can achieve this functionality in MS Word?

A: If you have the sections split and the page numbering working correctly, you should just be able to write Appendix before the page number on Page 1 of each Appendix footer and it should replicate the writing on each page of the section but still allow the page numbers to be incremental (that is count upwards).
Hope this helps.
For automated, it's a little bit trickier and requires the use of field codes (and also requires the use of Microsoft Word Styles).
So if you are only focusing on the Appendix sections, start on the first page of Appendix A and edit the footer. If you already have a footer set highlight it, right-click and select Edit Field....
In Field names select StyleRef and then to the right select the Style that you have used for your Appendix headings, in my case it was Heading 1 as seen in the picture below:

This should give you the name of your heading (which will hopefully be Appendix A). Then just copy that and paste it right next to it which will give you something that looks like below:

These two are completely different entities so you can put spaces, hypens, random writing, etc between them and it will all be replicated. Highlight all of the writing, right-click and select Toggle Field Codes. Highlight all of the writing in the the second lot of curly brackets {} and just replace it with PAGE. Then add your spaces and hypens to get the look you are after as below (then toggle the field codes back to get your final product):

This should update all of your Appendix A footers to match this look with the page number being continuous. Finally go to your Appendix B page 1 footer and select Link to Previous confirming when it asks you to remove existing data:

This should give you an identical looking footer starting with Appendix B - 1. Do the same thing for Appendix C, Appendix D, etc and hopefully it does exactly what you are after.


text:
Q: How to reset Python in macOS Currently, I feel like my Python ecosystem is out of whack. Several years ago, I had shared my computer with someone else, and now I am discovering that my machine has many versions of Python scattered about. From what I could find, starting from Macintosh HD:

*

*anaconda

*Applications/Python 3.6

*

*Contains IDLE, Python Launcher, etc...

*Library/Python/2.7/site-packages

*

*This contains things like pip and wheel (I am unsure what this is)

*Library/Frameworks/Python.framework/Versions

*

*This contains two folders, 3.5 and 3.6.

*System/Library/Frameworks/Python.framework/Versions

*

*Inside here there are many alias folders, all which point to 2.7

Is all of this supposed to be normal? I am trying to run Python from the terminal, yet I have been getting messages such as ImportError: No module named site. pip has also not been working.
Is there a way for me to reset the Python on my machine to just that which comes with macOS? I feel like starting over from a blank slate would be helpful, since I want to get things setup in some type of comprehendible way (e.g. a way in which I've set things up so I know what is on my machine instead of many random things put on it by another).

A: This is very normal. you have a preinstalled python2.7 which comes with macOS and another one "Anaconda" which has installed manually. You first need to check what is your default python path (version) on your macOS, I mean if you are using anaconda or the default pre-installed python2.x. To remind you can check like below:
python --version
output (for me): Python 3.7.6

then if you want to change it to another version/or use another version under conda you can check these two answeres of mine.
How to add anaconda to PATH?
and here:
How to set the default python3 to python3.7?
It is normal that when you install a package for your default python version you don't expect it to be installed on the other one too. Normally it is better to install python2.x as an environment of conda and switch between two environments with "conda activate py2" and "conda deactivate" to go back to your default version. for each of them, you need to be in the environment and then use pip.
if pip is not working, it may need to be installed. On macOS, as you remember, you can use
brew update
brew install pip

or "easy-install" instead of brew (or whatever you use for installation).


text:
Q: Is EPS or PDF the preferred figure format when typesetting in LaTeX? What is the best file format for figures to use when typesetting in LaTeX? I prefer eps for my MATLAB figures; however, I found this question ( Which figure type to use: pdf or eps? ) where the recommendation is pdf.
I like converting with LaTeX to get a real-time preview of my document in DVI. Unfortunately, problems arise when I have raster graphics to include.  Since it is not possible to make DVIs with rasters, I currently encapsulate them in eps, but the results are poor: if I do not enter any sizing options the image appears enlarged and smudgy. The same problem occurs with eps produced with MATLAB, although scaling them down does not make them smudgy since it is a real vector diagram.  What causes this enlargement?

A: For photos, screenshots and such bitmap graphics, you could use their native format (to preserve quality) if it's jpeg or png. Otherwise convert those pictures to png or at least to lossless jpg.
For drawings, plots and diagrams you better use a vector image format, because it can be scaled without quality loss. Possible vector formats are pdf and ps.
It also depends on which compiler you use: latex or pdflatex. The latter has some benefits like better justification because of microtypographic enhancements and it natively supports jpg, png and pdf, and you can use ps if converted to pdf.
My usage order with pdflatex is

*

*pdf - for example output of other programs

*ps  - PSTricks or program output, then I use ps2pdf to go to 1.

*png - screenshots, bitmap graphics (if necessary convert to png)

*jpg - only if it's already the source format because jpg often uses lossy compression

Without pdflatex the question is not very interesting, latex supports only eps, conversion of bitmap images to eps is often not satisfying.

A: Using pdf files will improve compilation speed, according to Overleaf FAQ


text:
Q: Making a text appear under a button for half a second I want to make a button to perform some action and THEN let user know it was done. I tried making a label ander a button, then pause, then making it disappear.
private void button1_Click(object sender, EventArgs e)
        {

            // some action
            label1.Text = "Done!";
            System.Threading.Thread.Sleep(500);
            label1.Text = "";
        }

But it doesn't work. What is my mistake?

A: As Grant says in his answer, you're blocking the UI thread. The simplest solution is to spawn a new Task which will do the update for you, thus releasing the UI thread.
The Task can simply use Invoke to push the update back to the UI thread after a Sleep.
In your case, this translates to something like this:
private void button1_Click(object sender, EventArgs e)
{
    // some action
    label1.Text = "Done!";
    new TaskFactory().StartNew(() =>
    {
        Thread.Sleep(5000);
        Invoke((Action)(() => label1.Text = string.Empty));
    });
}

A: The call to Thread.Sleep() freezes the UI thread for a half-second, so that no updates to the UI can happen (including your update to the Label's text).
Here's a couple options:

*

*You could use a BackgroundWorker, which has built-in mechanisms for executing long-running code in a separate thread, and then updating the UI (such as your Label) when it's done.

*You could add a Windows.Forms.Timer to your Form, to perform the action and update the Label. Give it an interval of 500 (ms), and it'll wait roughly a half-second before firing.


text:
Q: Problemas para conectar con base de datos de SQL Server Tengo el siguiente código:
public static int Guardar(string codigo, string nombre, string apellido)
{
    Clase_Conexion conexion = new Clase_Conexion();

    int retorno = 0;//existe codigo. Producto repetido
    String sql="INSERT into Table (codigo, nombre, apellido) VALUES (@codigo, @nombre, @apellido)";
    //String cstring = ConfigurationManager.ConnectionStrings["conecta"].ConnectionString;
    //using (SqlConnection connection = new SqlConnection(cstring))
    //{
        using (SqlCommand command = new SqlCommand())
        {
            command.Connection = conexion.con;            // <== lacking
            command.CommandType = CommandType.Text;
            command.CommandText = "INSERT into Table (codigo, nombre, apellido) VALUES (@codigo, @nombre, @apellido)";
            command.Parameters.AddWithValue("@codigo", codigo);
            command.Parameters.AddWithValue("@nombre", nombre);
            command.Parameters.AddWithValue("@apellido", apellido);

            try
            {
                conexion.conectar();
                int recordsAffected = command.ExecuteNonQuery();
                retorno = 1;
            }
            catch (SqlException)
            {
                // error here
            }
            finally
            {
                conexion.cerrar();
            }
        }
    //}
    return retorno;
}

Y tengo la siguiente clase de conexión:
public class Clase_Conexion
{
    public SqlConnection con;
    public void conectar()
    {
        con = new SqlConnection("data source = localhost; initial catalog = BD_ejemplo"); // LOCALHOST
        con.Open();
    }
    //metodo para cerrar
    public void cerrar()
    {
        con.Close();
    }
}

Tengo una base de datos llamada BD_ejemplo.mdf en App_Data
Y en al web.config tengo la siguiente conectionString de la siguiente forma:
 <add name="conecta" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-ejemplo_ajax_webform-20170317135041;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-ejemplo_ajax_webform-20170317135041.mdf" />

Primeramente estaba usando la conexión mediante el web.config, pero no me resultó, ya que decía que no encontraba la ruta de la base de datos. Posteriormente decidí hacerlo mediante una clase de conexión, pero tampoco puedo, ya que me sale el siguiente error:

Error relacionado con la red o específico de la instancia mientras se establecía una conexión con el servidor SQL Server. No se encontró el servidor o éste no estaba accesible. Compruebe que el nombre de la instancia es correcto y que SQL Server está configurado para admitir conexiones remotas. (provider: Named Pipes Provider, error: 40 - No se pudo abrir una conexión con SQL Server)

Quisiera saber cómo hago la conexión tanto por el web.config y en especial con el archivo de conexión (clase). Sé que algo está mal escrito, o algún parámetro me falta ingresar en:
con = new SqlConnection("data source = localhost; initial catalog = BD_ejemplo") //(para el caso de la clase de conexion)

Espero poder encontrar la solución.
Observacion: Por ahora estoy sin contraseña a la base de datos. Ya que agregue desde el mismo Visual Studio.

He comprobado la conección y esta correcto. Aquí muestro los siguiente:

El nombre del archivo de la base de datos es visual studio 2013\Projects\ejemplo_ajax_webform\ejemplo_ajax_webform\App_Data\BD_ejemplo.dmdf
Y en Advance, hay una parte que dice :
Data Source=(LocalDB)\v11.0;AttachDbFilename="C:\Users\Usuario_X\Documents\visual studio 2013\Projects\ejemplo_ajax_webform\ejemplo_ajax_webform\App_Data\BD_ejemplo.dmdf.mdf";Integrated Security=True
___EDICION 2:___________________
He probado de esta otra forma:
he creado una clase coneccion:
public class Conexion
{
    public SqlCommand cmd;
    public SqlConnection Conn;
    public string Conexion_uno= "Data Source=localhost;" +
        "Initial Catalog=BD_ejemplo;" +
        "Integrated Security=SSPI;";// { get; set; }

    public void Abrir_Conexion()
    {
        try
        {
            this.cmd = new SqlCommand();
            this.Conn = new SqlConnection();
            this.Conn.ConnectionString = Conexion_uno;
            this.Conn.Open();

            this.cmd.CommandTimeout = 10000;
            this.cmd.Connection = Conn;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message.ToString().Trim());
            CerrarConexion();
        }
    }
    public void CerrarConexion()
    {
        Conn.Close();
    }
}

Y en el metodo guardar pruebo así:
 public static int Guardar(int codigo, string nombre, string apellido)
    {
        Conexion conexion = new Conexion();

        int retorno = 0;//existe codigo. Producto repetido
        //String cstring = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        //using (SqlConnection connection = new SqlConnection(cstring))
        //{
            using (SqlCommand command = new SqlCommand())
            {
                command.Connection = conexion.Conn;            // <== lacking
                //command.Connection = connection;            // <== lacking
                command.CommandType = CommandType.Text;
                command.CommandText = "INSERT INTO Usuario(codigo, nombre, apellido) VALUES(@codigo, @nombre, @apellido)";
                command.Parameters.AddWithValue("@codigo", codigo);
                command.Parameters.AddWithValue("@nombre", nombre);
                command.Parameters.AddWithValue("@apellido", apellido);
                //command.Parameters.Add("@codigo", SqlDbType.Int).value = codigo
                //command.Parameters.Add("@nombre", SqlDbType.Varchar, 50).value = nombre;
                //command.Parameters.Add("@apellido", SqlDbType.Varchar, 50).value = apellido;

                try
                {
                    conexion.Abrir_Conexion();
                    //connection.Open();
                    int recordsAffected = command.ExecuteNonQuery();
                    retorno = 1;
                }
                catch (SqlException)
                {
                    // error here
                }
                finally
                {
                    //connection.Close();
                    conexion.CerrarConexion();
                }
            //}
        }
        return retorno;

    }

pero me dice el siguiente error:
ExecuteNonQuery: la propiedad Connection no se ha inicializado.

A: Le recomiendo que verifique lo obvio:
Lo primero que te sugiero es que hagas la conexión desde el visual studio por el explorador de servidores y lo copies y pegues en le WebConfig, obviamente luego de confirmar la conexión.
También Verifica que el servicio si se este ejecutando.
Verifica que no sea un problema con el firewall ( puerto 1433).
La mayoría de las veces que me presenta ese error es un error en la cadena de conexion en el webconfig.

A: Mira yo te recomiendo mejor este método, me ha sacado de apuros. Crea un método en una clase llamada "Conexion" y agrega esto:
public class clsConexioncs
{

    private SqlCommand cmd;
    private SqlConnection Conn;
    public string Conexion;// { get; set; }

    public void AbrirConexion()
    {
        try
        {
            this.cmd = new SqlCommand();
            this.Conn = new SqlConnection();
            this.Conn.ConnectionString = Conexion;
            this.Conn.Open();

                                                                                this.cmd.CommandTimeout = 10000;
            this.cmd.Connection = Conn;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message.ToString().Trim());
            CerrarConexion();
        }
    }
}

Dentro del webConfig, agrega esto:
<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Dash_Femsa-20170215043808.mdf;Initial Catalog=aspnet-Dash_Femsa-20170215043808;Integrated Security=True" providerName="System.Data.SqlClient"/>
    <add name="DefaultDW" connectionString="Data Source=10.12.14.6;Initial Catalog=PRM; User ID= CorrelatorUser; Password= CorrelatorUser01" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Solo configuralo con tus variables y veras que te funciona, es mas seguro y concreto.
Mandala a llamar desde tu main y veras que te sirve para todo tu programa.


text:
Q: TCP error code 10048: Only one usage of each socket address (protocol/network address/port) is normally permitted We are getting below error only from one client machine while all the other client machines are not throwing any errors. Why is this error only coming from one client machine and what is the fix for it.
Could not connect to net.tcp://XXXXXX:809/YYYYYY.svc. The connection attempt lasted for a time span of 00:00:00. TCP error code 10048: Only one usage of each socket address (protocol/network address/port) is normally permitted XX.XX.XX.XXX:809. .  This message has been processed.
Thanks in advance.


text:
Q: Remove a specific previous activity from stack In my app have some Activities, but in a particular point 've the stack
otherActivities -> A -> B -> newA
Now, i've some weird things to do:
-if I'm in B and I press the back button i will return in A.
-if I'm in newA and press back I don't want to see neither A and B, but return to the activity stack (already Achieved to skip B)


text:
Q: Paralellized execution in nested for using Cilk I'm trying to implement a 2D-stencil algorithm that manipulates a matrix. For each field in the matrix, the fields above, below, left and right of it are to be added and divided by 4 in order to calculate the new value. This process may be iterated multiple times for a given matrix.
The program is written in C and compiles with the cilkplus gcc binary.
**Edit: I figured you might interested in the compiler flags:
~/cilkplus/bin/gcc -fcilkplus -lcilkrts -pedantic-errors -g -Wall -std=gnu11 -O3  `pkg-config --cflags glib-2.0 gsl`   -c -o sal_cilk_tst.o sal_cilk_tst.c

Please note that the real code involves some pointer arithmetic to keep everything consistent. The sequential implementation works. I'm omitting these steps here to enhance understandability.
A pseudocode would look something like this (No edge case handling):
for(int i = 0; i < iterations; i++){
   for(int j = 0; j < matrix.width; j++){
      for(int k = 0; k < matrix.height; k++){
         result_ matrix[j][k] = (matrix[j-1][k] +
                                 matrix[j+1][k] +
                                 matrix[j]  [k+1] +
                                 matrix[j]  [k-1]) / 4;
      }
   }
   matrix = result_matrix;
}

The stencil calculation itself is then moved to the function apply_stencil(...)
for(int i = 0; i < iterations; i++){
   for(int j = 0; j < matrix.width; j++){
      for(int k = 0; k < matrix.height; k++){
         apply_stencil(matrix, result_matrix, j, k);
      }
   }
   matrix = result_matrix;
}

and parallelization is attempted:
for(int i = 0; i < iterations; i++){
   for(int j = 0; j < matrix.width; j++){
      cilk_for(int k = 0; k < matrix.height; k++){ /* <--- */
         apply_stencil(matrix, result_matrix, j, k);
      }
   }
   matrix = result_matrix;
}

This version compiles without errors/warning, but just straight out produces a Floating point exception when executed. In case you are wondering: It does not matter which of the for loops are made into cilk_for loops. All configurations (except no cilk_for) produce the same error.
the possible other method:
for(int i = 0; i < iterations; i++){
   for(int j = 0; j < matrix.width; j++){
      for(int k = 0; k < matrix.height; k++){
         cilk_spawn apply_stencil(matrix, result_matrix, j, k); /* <--- */
      }
   }
   cilk_sync; /* <--- */
   matrix = result_matrix;
}

This produces 3 warnings when compiled: i, j and k appear to be uninitialized.
When trying to execute, the function which executes the matrix = result_matrix; step appears to be undefined.
Now for the actual question: Why and how does Cilk break my sequential code; or rather how can I prevent it from doing so?
The actual code is of course available too, should you be interested. However, this project is for an university class and therefore subject to plagiarism from other students who find this thread which is why I would prefer not to share it publicly.
**UPDATE:
As suggested I attempted to run the algorithm with only 1 worker thread, effectively making the cilk implementation sequential. This did, surprisingly enough, work out fine. However as soon as I change the number of workers to two, the familiar errors return.
I don't think this behavior is caused by race-conditions though. Since the working matrix is changed after each iteration and cilk_sync is called, there is effectively no critical section. All threads do not depend on data written by others in the same iteration.
The next steps I will attempt is to try out other versions of the cilkplus compiler, to see if its maybe an error on their side.

A: With regards to the floating point exception in a cilk_for, there are some issues that have been fixed in some versions of the Cilk Plus runtime.   Is it possible that you are using an outdated version?
https://software.intel.com/en-us/forums/intel-cilk-plus/topic/558825
Also, what were the specific warning messages that are produced?  There are some "uninitialized variable" warnings that occur with older versions of Cilk Plus GCC, which I thought were spurious warnings.

A: The Cilk runtime uses a recursive divide and conquer algorithm to parallelize your loop. Essentially, it breaks the range in half, and recursively calls itself twice, spawning half and calling half.
As part of the initialization, it calculates a "grain size" which is the size of the minimum size it will break your range into. By default, that's loopRange/8P, where P is the number of cores.
One interesting experiment would be to set the number of Cilk workers to 1. When you do this, all of the cilk_for mechanism is excersized, but because there's only 1 worker, nothing gets stolen.
Another possibility is to try running your code under Cilkscreen - the Cilk race detector. Unfortunately only the cilkplus branch of GCC generates the annotations that Cilkscreen needs. Your choices are to use the Intel commpiler, or try using the cilkplus branch of GCC 4.9. Directions on how to pull down the code and build it are at the cilkplus.org website.


text:
Q: Why is it not possible to have a set as an element of a set? It gives me error while creating {{2}, 3, 4} set element inside a set.
Error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'

Is there any alternative way to do that?
Thanks in advance.

A: Sets can only contain hashable objects.  But sets themselves are not hashable.  So a set can't contain another set.
(Aside from that, your code has a syntax error because {2}.3 is invalid syntax.  But if you change it to {{2}, 3, 4} it still won't work, for the reason I mentioned above.)

A: In Python, in general, mutable types like set are not hashable. It's not just a coincidence that they can't be used as set elements or dict keys—that's actually the whole point:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare equal must have the same hash value.
Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.
All of Python's immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is derived from their id().

The frozenset type exists for pretty much this purpose:

There are currently two built-in set types, set and frozenset. The set type is mutable — the contents can be changed using methods like add() and remove(). Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. The frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.

A: Even though their items must all be immutable/hashable types, sets themselves are a mutable/nonhashable type.  You can either add or remove items from a set using methods such as set.add, set.pop, or set.remove.  Thus, you cannot put a set inside another set because the item might be changed at any time.
Instead, you can use a frozenset, which is an immutable/hashable set:
>>> {frozenset({2}), 3,4}
set([frozenset([2]), 3, 4])
>>>

Keep in mind however that this only works because frozensets cannot be changed after they are created (there is no way to add or remove items).