text:
Q: Cannot resolve all parameters - Angular DI issue when exporting shared services I want to avoid having to import every service into all my Angular 4 components, so I created something like this
import * as UtilityService from '../../services/utility.service';

Instead of doing this
import { AppStateService, InternalStateType } from '../services/appstate.service';
import { Logging } from '../services/utility.service';
import { AuthenticationService } from '../services/authentication.service';
import { DataService } from '../services/data.service';
import { Utils } from '../services/utility.service';
import { RouteProtectionService } from '../services/route-protection.service';
import { UrlManagementService } from '../services/url-managing.service';

So now I can accesss all the classes from any component by referencing UtilityService.Classname i.e. UtilityService.AppState, UtilityService.Authentication, etc.
 constructor(
  public appState: UtilityService.AppState,
  public utilities: UtilityService.Utils,
  public dataService: UtilityService.Data,
  private appInsightsService: UtilityService.AppInsights,
  private titleService: UtilityService.Titles) {
 }

Then inside utility.service.ts, I have this
export { AppState, InternalStateType } from './appstate.service';
export { Authentication } from './authentication.service';
export { Data } from './data.service';
export { RouteProtection } from './route-protection.service';
export { UrlManagement } from './url-managing.service';
export { AppInsightsService } from '@markpieszak/ng-application-insights';
export { Title } from '@angular/platform-browser';

It compiles fine in typescript, but when running the app, angular complains
 Error: Can't resolve all parameters for Authentication: ([object Object], [object Object], ?, ?, ?).

I already specified the provider for each of them in the AppModule, and it works when I import the classes normally. So why can't I import a barrel of classes and use them in Angular dependency injection?

A: Normally this error is coming because of Circular Dependency. Without all source code information it's very difficult to identify the service ,  which are actually causing the circular dependency issue.
I would suggest add the service one by one in to the constructor and identify which service making this error and resolve it.
If you couldn't identify the issue or you need circular dependency , Resolve the dependency manually like below
import { Injector } from '@angular/core';
constructor( private injector: Injector) {
    this.myService = this.injector.get(MyService);
  }

or
import { ReflectiveInjector } from '@angular/core';
 constructor() {

       var injector= ReflectiveInjector.resolveAndCreate([MyService]);
       let myservice=injector.get(MyService);
     }

You can understand about these injectors from the below link. Use Injector or Reflective Injector based on your need.
Difference between Reflective Injector and Injector in Angular

A: If you open the developer console in your web browser, you will probably see an error like this:

(SystemJS) Encountered undefined provider! Usually this means you have a circular dependencies (might be caused by using 'barrel' index.ts files.)

The Angular glossary calls this type of re-exporting a 'barrel`.

A way to roll up exports from several ES2015 modules into a single convenient ES2015 module.

That 'barrel' is the technique that you are using to re-export your modules. Unfortunately, it can lead to circular dependencies.
The solution: remove the circular dependencies, as the associated GitHub issue here says.


text:
Q: How to make youtube-viewer zip package installable for 18.04 I've recently upgraded to 18.04 and miss youtube-viewer which is not in the repo (yet??). This thread has an answer in which the poster says they got it working by downloading youtube-viewer-master.zip from github (https://github.com/trizen/youtube-viewer) "followed by a few installation steps to finish it up."
I'm relatively new to Ubuntu and Perl but I want to see if I can get it working.  So far I have run perl Build.PL, and satisfied several dependencies + changed folder permissions to allow the scripts to complete further.
The last terminal lines were:
    Configuring H/HA/HAYASHI/Term-ReadLine-Gnu-1.35.tar.gz with Makefile.PL
    Could not find neither libtermcap.a, libncurses.a, or libcurses.
    Warning: No success on command[/usr/bin/perl Makefile.PL INSTALLDIRS=site]
      HAYASHI/Term-ReadLine-Gnu-1.35.tar.gz
  /usr/bin/perl Makefile.PL INSTALLDIRS=site -- NOT OK

I installed libcurses-perl with Synaptic + re-ran it, but got the same result. I could not find libtermcap.a or libncurses.a in Synaptic.
What am I missing?

A: Difficult way (you chose it)
It seems that you need to install the following packages

*

*for libtermcap.a
sudo apt-get install libtinfo-dev

*for libncurses.a
sudo apt-get install libncurses5-dev

*the it may need readline/readdline.h, installable with
sudo apt-get install libreadline-dev

Do not forget to install Unicode::GCString with sudo apt-get install libunicode-linebreak-perl.
Complete method is as follows:
cd ~/Downloads
git clone https://github.com/trizen/youtube-viewer
cd youtube-viewer

sudo apt-get install libmodule-build-perl libtinfo-dev \
libncurses5-dev libreadline-dev libunicode-linebreak-perl

perl Build.PL --gtk
sudo ./Build installdeps  # hit <Enter> everywhere
sudo ./Build install

gtk-youtube-viewer # run it

It will be installed in /usr/local: executables are placed in /usr/local/bin - /usr/local/bin/gtk-youtube-viewer and /usr/local/bin/youtube-viewer.

Correct way
Wait for deb-package.
Update 2018-10-06: I sent packaging request to the ppa:nilarimogard/webupd8 owner - Alin Andrei via launchpad.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why RCS thruster moved my ship while rotating When I attempted docking I have annoying issue of RCS changing the ship speed. Once when I tried to rotate next to fuel station I got 10 m/s just by rotation.
I place RCS near COM when designing the ship - before adding spare booster/thrusters - just final module COM (well second to last if we count landing pod as stage).

A: The only difference between RCS thrusters and ordinary thrusters is the control scheme, the forces they apply work the same way:

*

*Any time a thruster is fired, it applies linear momentum to the ship (which is the same as translation or changing the ship speed). The amount is independent of where the thruster is placed.

*If the center of thrust does not align perfectly with the center of mass, it will also apply angular momentum (which is the same as rotation or applying torque) to the ship. The further away it is from the center of mass (CoM), the more angular momentum will be produced.
So, in the case of RCS, what you generally want is for it to be far away from the CoM, but balanced around it (placed symmetrically around the CoM). This makes both RCS modes work well:

*

*If you use RCS to rotate, the thrusters on the opposite ends of the ship will fire in different directions, cancelling out the linear momentum, and adding up the angular momentum, resulting in rotation but unchanged speed.

*If you use RCS to translate, the thrusters will fire in the same direction, adding up the linear momentum and cancelling out the angular momentum, resulting in no rotation, but changed speed.
Side note: If all you need is rotation, using reaction wheels is a reasonable alternative - reaction wheels never change the speed of the ship, only rotate it, and do not use any fuel, only electricity. They are more effective if you place them near the CoM, but will work anywhere, too. The trade-off is that they are bulkier and, for short missions, heavier (for similar power) than RCS, and cannot be used to translate (which is usually needed for docking).
Summary: Place RCS symmetrically around the CoM, but far away from it, for best results.

A: Do you place RCS in symmetric pairs/groups relative to COM?
To imagine the issue, let's take a very simple craft that has only one RCS block, somewhere off to the side.
When you want to turn this craft any way using the RCS, there is nothing to offset the thrust. The craft will begin turning as requested, but it will also be accelerated in the direction opposite to the one RCS fires.
Also, KSP tends to fire all RCS at full thrust, so - say, you placed three thrusters in a 3x symmetry.

You want to pitch the craft's nose up. The one top thruster fires retrograde, the two bottom thrusters fire prograde. Net torque makes the craft pitch up. Net thrust - accelerates it forward; two thrusters forward, just one back.
Small asymmetries result in smaller errors, but they do result in errors nevertheless.
First, the closer it is to COM, the lower the torque it can exert; the more thrust it must put into rotating the ship.
And the more thrust it uses, the more all errors accumulate.
To find the optimal placement, you can use the RCS Build Aid mod, or just 'eyeball' it with help of the editor's symmetry.
Also, try to place the thrusters meant for rotation as far from CoM as you can without sacrificing symmetry. Or just disable RCS pitch/yaw/roll actuation controls and use only the reaction wheels for that.
One more thing: completely regardless of RCS, two crafts WILL drift relative to each other in orbit. After all, if they have exactly the same speed but are not in exactly the same spot, they are in two different orbits. If craft A is in a perfectly circular orbit, and craft B is moving at the same speed, but 50 meters farther from the planet, it's currently exceeding the speed proper for circular orbit proper for its altitude; it's at the periapsis of an elliptical orbit which will take it a good bit away from craft A - out towards the apoapsis and backwards as climbing, it loses orbital speed. This is completely regardless of RCS, and while unnoticeable in a short time period, in the 10 minutes it takes to move to the opposite side of Kerbin it can easily accumulate to 10m/s.


text:
Q: "Couldn't add widget" when imageview clicked I was testing my app in a phone with android n. There was no problems with the widget in that phone. But when i tried on other phones it is making weird things when i clicked the ImageView refreshes and transfors to watch widget and then shows error message. And there is nothing in the logcat.
public class RadioWidget extends AppWidgetProvider {
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                            int appWidgetId) {

    // Construct the RemoteViews object
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.radio_widget);
    //Go to radio/track info fragment
    Intent radiointent = new Intent(context, MainActivity.class);
    radiointent.setAction("**********.play");
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, radiointent, 0);
    views.setOnClickPendingIntent(R.id.wlastp, pendingIntent);
    radiointent.setAction("*********.track.info.last");
    pendingIntent = PendingIntent.getActivity(context , 0, radiointent, 0);
    views.setOnClickPendingIntent(R.id.artwork, pendingIntent);
    //Play/Stop radio
    Intent controls = new Intent(context, NotificationControls.class);
    controls.setAction("********.widget.play");
    PendingIntent play = PendingIntent.getBroadcast(context.getApplicationContext(),1,controls,0);
    views.setOnClickPendingIntent(R.id.wplay, play);
    controls.setAction("********.widget.stop");
    PendingIntent stop = PendingIntent.getBroadcast(context.getApplicationContext(),2,controls,0);
    views.setOnClickPendingIntent(R.id.wstop, stop);
    views.setTextViewText(R.id.trackname, "now playing"));
    //Load image
    Glide.with(context.getApplicationContext())
            .load(/* artwork url*/)
            .asBitmap()
            .error(R.mipmap.album_placeholder)
            .into(new AppWidgetTarget(context.getApplicationContext(),views,R.id.artwork,appWidgetId));
    else views.setImageViewResource(R.id.artwork, R.mipmap.album_placeholder);
    int button_state = R.drawable.ic_play_arrow_black_24dp;
    if(/* checking if radio is playing */) button_state = R.drawable.ic_pause_black_24dp;
    views.setImageViewResource(R.id.wplay, button_state);
    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // There may be multiple widgets active, so update all of them
    for (int appWidgetId : appWidgetIds) {
        updateAppWidget(context, appWidgetManager, appWidgetId);
    }
}

}
xml
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/BG"
    android:padding="@dimen/widget_margin">
    <ImageView
        android:layout_width="80dp"
        android:layout_height="match_parent"
        android:src="@mipmap/album_placeholder"
        android:contentDescription="@string/cd_artwork"
        android:id="@+id/artwork"
        android:layout_alignParentLeft="true"
        android:scaleType="centerCrop"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="@string/media_play_now"
        android:id="@+id/trackname"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/artwork"
        android:layout_toEndOf="@+id/artwork"
        android:textSize="16sp"
        android:minLines="2"
        android:layout_marginTop="4dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"/>
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/trackname"
    android:layout_alignLeft="@+id/trackname"
    android:layout_alignStart="@+id/trackname"
    >
    <ImageView
        android:id="@+id/wplay"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_play_arrow_black_24dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        />

    <ImageView
        android:id="@+id/wstop"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_stop_black_24dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        />

    <ImageView
        android:id="@+id/wlastp"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_last_played_black_24dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        />
</LinearLayout>

</RelativeLayout>

manifest
<receiver android:name=".RadioWidget">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/radio_widget_info" />
        </receiver>

and here is my method updates widget from Service
public void updateRadioWidget(Context context) {
        AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);
        ComponentName widgetComponent = new ComponentName(context, RadioWidget.class);
        int[] widgetIds = widgetManager.getAppWidgetIds(widgetComponent);
        Intent update = new Intent();
        update.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIds);
        update.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        context.sendBroadcast(update);
    }

I tried the other post but no luck. It is working android N but not in others.

A: I edited my update method, it seems to be working right now
public void updateRadioWidget() {
    int[] ids = AppWidgetManager.getInstance(context.getApplicationContext()).getAppWidgetIds(new ComponentName(context.getApplicationContext(), RadioWidget.class));
    RadioWidget radioWidget = new RadioWidget();
    radioWidget.onUpdate(context.getApplicationContext(), AppWidgetManager.getInstance(context.getApplicationContext()),ids);

}


text:
Q: Syntax for specifying list in csv file I want to specify a list as the values of a property in csv file so that it can be loaded through load_csv as list.
Currently, I am specifying it as string and using split to add it in to list as below. Is there a better way?
WITH n, split(n.lab, \",\") as labels limit {limit}
call apoc.create.addLabels(id(n), labels)

Is there a way to avoid using split by reading it as list while doing load_csv. what's the syntax of list in csv file?

A: With LOAD CSV, each line in a CSV file without headers is accessed as a list, so you can just leave each label as a separate item in the line and generate a new list from those items.
For example, if each line starts with a node ID and ends with 1 or more labels:
LOAD CSV FROM '...' AS line
CALL apoc.create.addLabels(TOINTEGER(line[0]), line[1..]);


text:
Q: How to add or remove a js file in head Suppose I have 3 language: en, tc, sc, I want to achieve the below condition
1) When the current is en, add en.js to head and remove js file tc.js and sc.js in head
2) When the current is tc, add tc.js to head and remove js file sc.js and en.js in head
3) When the current is sc, add sc.js to head and remove js file tc.js and en.js in head
Can someone advise how to do that in jQuery?
Thanks

A: Once the document is loaded, you cannot do it dynamically. But there's a script require.js, which is a JavaScript file and module loader.

It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

It has a good support to use it with jQuery. You may also want to load code on the fly, after page load. Check out the above link and it would surely target your issue.

A: Why removing files in first place? If they were in page head it means they were already executed.
With Yesnope JS-module loader the solution will be like:
yepnope({
  test : lang=="en",
  yep : ['en.js']
});

http://yepnopejs.com/
BTW, this module-loader is used in Modernizr.

A: Here's a quick function that would load a script dynamically based on a language parameter.
addLanguageScript = function(lang) {
    var head = document.getElementsByTagName("head")[0],
        script = document.createElement('script');

    script.type = 'text/javascript'
    script.src = lang + '.js'
    head.appendChild(script);
};

addLanguageScript('en');

To remove the files you can do something like in jQuery, but keep in mind if the scripts
where loaded they probably would have already had some effect.
$("script[src='en.js']").remove()

A: add and remove dynamically files in head section
function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

Call Function:
loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

for remove:
 $('head script[src*="en.js"]').remove();  // for removing dynamically
  $('head script[src*="en.js"]').append();   // for append dynamically


text:
Q: Show that $f(x, y)=(x+a \sin y, y+b \sin x)$ is a $C^1 $-diffeomorphism if $|ab| < 1$ I've already proven that for any real $v$ the following function is continuous and strictly increasing :
$g(x) = x + a \sin(v - b \sin x)$
Therefore, it's bijective $\star$.
apparently it's supposed to help prove that $f(x, y)=(x+a \sin y, y+b \sin x)$ is bijective, one would then use the inverse function theorem to prove that it's a $C^1$-diffeomorphism but I can't seem to find a way to show the bijectivity of $f$ with or without using $\star$
any help would be appreciated.


text:
Q: How to send the body in wp_remote_post as "raw"? I'm not sure if I'm asking the right question, so here is the context.
I'm making a POST to an API (The api is to a Google Sheets Script - so there are some unusual limitations). When I use postman the data is returned in a json file. In order to get it to work in postman I have to send the parameters via the body and I have to select the raw option. Selecting any other option(i.e. x-www-form-urlencoded or form-data) results in an html error page.
I've followed the steps for wp_remote_post($api_url , $body ); in the WordPress documentation - but I'm getting the html error instead of the expected data.
How do I send the body as "raw" just like it's being sent in Postman?
UPDATE - To add code.
$api_url = 'https://script.google.com/macros/s/UNIQUE_KEYw/exec';
// $body = array(
//  "method"=>"GET",
//  "sheet"=>"date",
//  "key"=>"PASSWORD");

$body = ('{\n"method": "GET",\n"sheet": "date",\n"key": "PASSWORD"\n}');

$request =  wp_remote_post($api_url , array(
    'method'      => 'POST',
    'headers'     => ["Content-Type" => "raw"],
    'body'        => $body,
    'data_format' => 'body'
    )
                          );

The HTTP_Request2 snippet from postman that I'm trying to recreate.
<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('https://script.google.com/macros/s/UNIQUE_KEY/exec');
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->setConfig(array(
  'follow_redirects' => TRUE
));
$request->setHeader(array(
  'Content-Type' => 'text/plain'
));
$request->setBody('{\n"method": "GET",\n"sheet": "date",\n"key": "PASSWORD"\n}');
try {
  $response = $request->send();
  if ($response->getStatus() == 200) {
    echo $response->getBody();
  }
  else {
    echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
    $response->getReasonPhrase();
  }
}
catch(HTTP_Request2_Exception $e) {
  echo 'Error: ' . $e->getMessage();
}

A: I got this one working, you have to pass the json_encoded array on the body parameter of the request.
 $customer_details = [
            'first_name' => $first_name,
            'last_name' => $last_name,
            'email' => $email,
        ];

        $customer_details['body'] = json_encode($customer_details);

        $customer = $api->createUpdateCustomer($customer_details);

public function createUpdateCustomer($customer_details) {
        $response = $this->apiCall( "2.0/customers", 'POST', $customer_details);
        $result = json_decode($response);
        return $result;
    }

public function apiCall($baseUrl = null, $method = 'GET', $args = array()) {
        if ( !is_null( $baseUrl ) ) {
            $url = $this->baseUrl . $baseUrl;
        }
        else {
            $url = $this->baseUrl;
        }

        // Populate the args for use in the wp_remote_request call
        $wp_args = array_merge($args, $this->args);
        $wp_args['method']  = $method;
        $wp_args['timeout'] = 30;

        // Make the call and store the response in $res
        $res = wp_remote_request( $url, $wp_args );

        // Check for success
        if ( ! is_wp_error( $res ) && ( 200 == $res['response']['code'] || 201 == $res['response']['code'] ) ) {
            return $res['body'];
        } else {
            throw new Exception( "API call didn't go well :(. Either VendHQ Connect Settings are incorrect or VendHQ server is not responding as expected." );
        }
    }

A: You should be able to set headers to use content-type: application/json:
$api_url = 'https://script.google.com/macros/s/UNIQUE_KEYw/exec';
$body = wp_json_encode( array(
    "method" => "GET",
    "sheet" => "date",
    "key" => "PASSWORD"
) );

wp_remote_post( $api_url, [
    'headers'   => [ 'Content-Type' => 'application/json' ],
    'body'       => $body,
    'data_format' => 'body'
] );


text:
Q: Unable to get the ARN for AWS SQS and its dead letter queue I am creating a sqs with a dead letter queue. The creation of the queue is success but I need to store the ARN value of the queue in systems manager at parameter store. Is there any way to pass the value to parameter store? Please provide inputs.
I tried like this, but it is not deploying in the parameter store.. I am deploying through cdk using python.
    dead_letter_queue: sqs.Queue = sqs.Queue(
        self,
        id="DeadLetterQueue",
        queue_name="dlqueue",
        retention_period=Duration.days(14)
    )
    self.sqs_queue: sqs.Queue = sqs.Queue(
        self,
        id="SqsQueue",
        queue_name="queue",
        retention_period=Duration.days(4),
        visibility_timeout=Duration.hours(6),
        delivery_delay=Duration.seconds(0),
        receive_message_wait_time=Duration.seconds(0),
        max_message_size_bytes=262144,  # 256 KiB
        #encryption=sqs.QueueEncryption.SQS_MANAGED,
        dead_letter_queue=sqs.DeadLetterQueue(
            max_receive_count=1,
            queue=dead_letter_queue

        )

    )

    ssm.StringParameter(self, "arn value of queue",
                        parameter_name="test",
                        string_value=self.sqs_queue.queue_arn)


text: Q: configure cuckoo guest machine for dynamic malware analysis I've configured Cuckoo on my host machine, now trying to setup the guest machine where the malware suppose to be executed. The guest machine will be Ubuntu not Windows, but I don't know what should be done on the Ubuntu machine to mkae it Cuckoo guest machine. Where the guidance of Cuckoo shows the steps for configuring Windows 7 machine as guest machine, but nothing mentioned about Ubuntu, though Cuckoo supports linux malware analysis.


text:
Q: php_user_filter subclass filter method gets called twice I am totally befuddled as to why the filter function is entered twice: once over the contents of the memory stream, and a second time over nothing (thus while loop never entered). It causes a bug when you actually want to use the stream construct to prepend and append a quoting character.
Program:
<?php
class Trivial extends php_user_filter {
    function filter($in, $out, &$consumed, $closing) {
        print("entering filter:\n");

        while ($bucket = stream_bucket_make_writeable($in)) {
            print("in the loop\n");
            $consumed += $bucket->datalen;
            stream_bucket_append($out, $bucket);
        }

        print("returning from filter\n\n");
        return PSFS_PASS_ON;
    }
}

$stream = @fopen("php://temp", 'r+');
fwrite($stream, "Hello", 5);
rewind($stream);
stream_filter_register('trivial', 'Trivial');
stream_filter_append($stream, 'trivial', STREAM_FILTER_READ);
$result = fread($stream, 8192);
print("stream: '" . $result . "'\n");
?>

Output:
entering filter:
in the loop
returning from filter

entering filter:
returning from filter

stream: 'Hello'

Edit Checked on PHP7.02 and on my PHP 5.6 on my Mac laptop and Ubuntu 16.04 Linux; this is not a bug or version quirk.
Edit 2 I think I'm already pretty close to the answer (by very unsatisfying inference though): $closing is false the first time and true the second time.


text:
Q: How to interpret heat kernel at unit time on a Riemann surface? Let $M$ be a compact Riemann Surface. Let $P$ be a fixed point on $M$ and let $\delta_{P}$ be the Dirac point distribution at $M$. Consider the fundamental solution of the heat equation
$$
(\partial_{t}-\Delta)K(x,y,t)=0, K(x,y,0)=\delta_{x}(y)
$$
and its solution
$$
f(x)=e^{\Delta}\delta_{P}(x)=\int K(x,y,1)\delta_{P}(y)dy=K(x,P,1)
$$
I am wondering if there is any special meaning attached to the case when $t=1$ and $M$ is taken as a homogeneous space. The idea seems natural that one start Brownian motion with a pointed probability distribution and let time flows, then $f(x)$ can be used as a measure of the "distance" between $x$ and $P$. In the case $M=\mathbb{S}^{1}$ via its universal cover $\mathbb{R}^{1}$ we recovered a sum of Gaussians that resembles theta function.
However when I look up online, the explicit formulas we have are rather difficult to interpret. For $g\ge2$ they are quotients of $\mathbb{H}$, and thanks to Mckeans' work we know
$$
K(x,y,t)=\frac{\sqrt{2}}{(4\pi t)^{3/2}}e^{-t/4 }\int^{\infty}_{p}\frac{se^{-s^2/4t}}{(\cosh(s)-\cosh(p))^{1/2}}ds,p=d_{\mathbb{H}}(x,y)
$$
I do not really know any good interpretation of this when we fix $y=P,t=1$ and let $x$ vary then add up the copies corresponding to $\pi_{1}(M)$. In particular, I am curious what does this say related to the spectrum of the Laplacian in $M$. It should relate to analytic torsion of the Laplacian on the manifold, but so far I have not found any way to relate the two objects.

This coming from the following observation in Arakelov theory: In the arithemetic surface setting to obtain a Riemann-Roch formula for a line bundle $L$ is the same thing as giving a metric for the determinant line bundle $\lambda(L)=\lambda(H^{0}(L))\otimes \lambda(H^{1}(L)^{*})$. I am wondering if there is anyway to define $H^{1}$ directly which satisfies Serre duality. In one dimensional case, the regularized $h^{1}$ proposed by Van Der Geer and Rene Schoof is essentially a weighted sum of Gaussian functions, which may be interpreted as the probability density of standard Brownian motion on the real line covering the interval $[0,1]$. However in two dimensional situation it is not entirely self-evident that analgous methods give us a self-dual object. A standard choice in the community is to work with the Quillen metric, but it is not clear to me how this may relate to Quillen metric either. The question at here is really about how to understand this probability density better, as the original problem seems still totally out of reach.

There is nothing "special" about $t=1$. Indeed if we rescale $M$ or change $t=1$ with $t=s$, then the corresponding heat kernel would also change. For me the most direct reason may be in $\mathbb{R}^{1}$ case for $t=1$ the Fourier transform of the heat kernel is itself. I am not sure what the Fourier transform of the heat kernel on the hyperbolic space is for fixed $t$ with respect to $p$, for example. And in general this self-duality should stem from some form of Poincare duality, as Serre duality can be viewed as Poincare duality for Riemann surfaces.
The reason I viewed it as a sort of "distance" is again motivated by Arakelov theory. In the Vander Geer-Schoof paper they used an effectivity function of the form (see page 6)
$$
e((f)+D)=e^{-\pi |f|^{2}_{D}}
$$
So to mimic the behavior of effectivity function in $\mathbb{R}$ it seems natural to consider its counterpart on the Riemann surface, such that for points "closer" to $P$ the value $f(x)$ should be greater as it got hitted more often. Some numerical computation showed the function $f_{P}(x), P=0$ indeed decays very fast with respect to $p=d(x,0)$. However I am unable even to plot it with respect to $p$.


text:
Q: Image from Google Drive Android Studio API gets rotated I am using the Java Google Drive API in Android Studio to download an image from the drive:
OutputStream outputStream = new FileOutputStream(mContext.getFilesDir() + "/" + destPath);
mDriveService.files().get(id).executeMediaAndDownloadTo(outputStream);

Most images get saved normally on the device (like the original on drive). But some images get saved rotated.
What I mean is, for example, I have a photo on google drive which is orientated in portrait mode. But after the code above downloads it on the device, the photo on the device is in landscape mode.

A: I found out the problem was actually not saving the image, but the way I was looking at the image (because I was displaying it in an ImageView as a Bitmap).
While doing decodeFile, the image was getting rotated.
For that, the solution I used is here:
Android: Bitmaps loaded from gallery are rotated in ImageView


text:
Q: jQuery Autocomplete enter keypress action in Firefox not working properly I made a jQuery autocomplete search to search through pages in my CI application, the returned JSON data includes 2 elements, "slug" of the page and "name" of the page, so im using the "name" to show on autocomplete list, and when someone selects a result or press enter key it redirects him to that page using the slug:
$(function() {
    $( "#search" ).autocomplete({
        source: "index.php/pages/get_pages",
        minLength: 2,
        select: function(event, ui) {
            $(event.target).val(ui.item.value);
            window.location.href = "index.php/pages/" + ui.item.slug;
            return false;
        }
    });

    $("#search").keypress(function(e){
        if (e.which == 13) {
            window.location.href = "index.php/pages/no-results";
            return false;
        }
    });
});

now i added another option when someone types a keyword and no results were found then he press enter it should go to the "pages" with no-results parameter.
This code worked fine on all browsers except for Firefox, it goes to no-results page in all cases.
I need it to go to no-results page only if no results were found and the user entered a random page name then pressed enter.

A: I think it's about forwarding issues. When you press "Enter" button, keypress' and autocomplete select's functions are called both. We should insert an if logic in order to execute only one of them.
By the way I think it's quite logical to do forwarding operations in server side.
$(function() {
    var isSelected = false;
    $("#search" ).autocomplete({
        source: "index.php/pages/get_pages",
        minLength: 2,
        select: function(event, ui) {
            isSelected = true;
            $(event.target).val(ui.item.value);
            window.location.href = "index.php/pages/" + ui.item.slug;
            return false;
        }
    });

    $("#search").keypress(function(e){
        if (e.which == 13) {
            if(!isSelected)
            {
                 window.location.href = "index.php/pages/no-results";
            }
            return false;
        }
    });
});


text:
Q: Chaining output of an async method as input of another async method c# I have the following code section in which SavePersonAsync method were calling 3 external methods and could anyone tell me the implementation of async/await methods were implemented correctly. Does any of the call chains in which async/await was not implemented correctly?
    public PersonService(IPersonDbService personDbService,
        IPersonEntityToPersonModelMapper personEntityToPersonModelMapper,
        IPersonModelToPersonEntityMapper personModelToPersonEntityMapper)
    {
        _personDbService = personDbService;
        _personEntityToPersonModelMapper = personEntityToPersonModelMapper;
        _personModelToPersonEntityMapper = personModelToPersonEntityMapper;
    }

    public async Task<IEnumerable<PersonModel>> SavePersonAsync(IEnumerable<PersonModel> personsModel)
    {
        var personsEntity = await _personModelToPersonEntityMapper.MapPersonModelToPersonEntityAsync(personsModel);

       var savedPersons = await _personDbService.SavePersonAsync(personsEntity.First()); // Currently only alow one person at a time, later it will allow to save a collection of persons

        return await _personEntityToPersonModelMapper.MapPersonEntityToPersonModelyAsync(new List<PersonEntity>
        {
            savedPersons
        });
    }
}

public class PersonEntityToPersonModelMapper : IPersonEntityToPersonModelMapper
{
    public async Task<IEnumerable<PersonModel>> MapPersonEntityToPersonModelyAsync(
        IEnumerable<PersonEntity> personsEntity)
    {
        if (personsEntity.NullOrEmpty())
            return await Task.FromResult(Enumerable.Empty<PersonModel>());

        return await Task.FromResult(personsEntity.Select(personEntity => new PersonModel
        {
            FirstName = personEntity.FirstName,
            LastName = personEntity.LastName
        }));
    }
}

public class PersonModelToPersonEntityMapper : IPersonModelToPersonEntityMapper
{
    public async Task<IEnumerable<PersonEntity>> MapPersonModelToPersonEntityAsync(IEnumerable<PersonModel> personsModel)
    {
        if (personsModel.NullOrEmpty())
            return await Task.FromResult(Enumerable.Empty<PersonEntity>());

        return await Task.FromResult(personsModel.Select(personModel => new PersonEntity
        {
            FirstName = personModel.FirstName,
            LastName = personModel.LastName
        }));
    }
}

A: From the definition of async await when you have written await the flow will start sequential, As you need the output to be used in the next statement then there is not much use of async await in your case
To breief about how it works
Suppose you have to method call which can work async in that can your code would be like:
Var a = GetMethodA();
Var b = GetMethodB();
await a;
await b;
In this case your method will work asynchronous


text:
Q: Fancybox3 Youtube video onload and autostart I have an little site with a video. Its a YouTube Video.
But if fancybox show up, the video it will not autostart.
Here is my code:

Videoteaser

      Videoteaser

To open up automatically I have this little JS on the bottom of the site:
$('[data-fancybox]').eq(0).trigger('click');

The Problem ist that the video do not autostart. No matter if I click on the button or if I use the little JS to autoopen the fancybox.
Only after klicken the Play-Button the Video do start.
How can I make ist autostart?

A: You are using Chrome, right? Then the answer is simple - it will not start due to Autoplay Policy Changes, see https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
Other then that - it works fine https://codepen.io/anon/pen/pqyzEM?editors=1000


text:
Q: $\lim _{x\to 0}\left(\frac{\tan\left(x\right)-x}{x-\sin\left(x\right)}\right)$ without L'Hopital's Rule Here are the functions:
a) $\displaystyle\lim _{x\to 0}\left(\frac{\tan\left(x\right)-x}{x-\sin\left(x\right)}\right)$
If I used L'Hopital's rule the limit is $2$
b) $\displaystyle\lim _{x\to 0}\:\frac{e^x\cdot \:\sin\left(x\right)-x\cdot \left(1+x\right)}{x^3}$
here $\dfrac{1}{3}$
c) $\displaystyle\lim _{x\to 0}\left(\frac{\ln\left(\sin\left(3 x\right)\right)}{\ln\left(\sin\left(7x\right)\right)}\right)$
and here $1$
but the problem is that I am not allowed to use L'Hopital's rule, can you give me ideas for another type of approaches?
UPDATE:
I apologize, I see there is some discussion and confusion among people, which obviously goes beyond my functions, but still I wanted to explain that I have been missing a lots of lectures recently due to illness and last week I got $0$ points for using L'hopital because we have not learnt it, so my guess was that we are not allowed this time either, but  I just talked to my tutor and he told me that just in the last lecture, they introduced L'hopital rule to us so I am free to use it. I'm very sorry.

A: a) use the fact that $\tan{x}=x+x^3/3+o(x^3)$ and $\sin{x}=x-x^3/6+o(x^3)$ to get
$${\tan{x}-x\over x-\sin{x}}={{x^3\over 3}+o(x^3)\over {x^3\over 6}+o(x^3)}=2+o(1)$$
So the limit is $2$
b) for this one we need $e^x=1+x+x^2/2+o(x^2)$ to write
$${e^x\cdot\sin{x}-x(1+x)\over x^3}={x+x^2+{x^3\over 3}-x-x^2+o(x^3)\over x^3}={1\over 3}+o(1)$$
So the limit is $1/3$
c) the last one is even simpler
$${\ln{\sin{7x}}\over \ln{\sin{3x}}}={\ln{7x}+\ln{\sin{7x}\over 7x}\over \ln{3x}+\ln{\sin{3x}\over 3x}}$$
Now keeping in mind $\sin{x}/x\to 1$ the limit is equal to
$$\lim_{x\to 0}{\ln{7}+\ln{x}\over \ln{3}+\ln{x}}=\lim_{x\to 0}{{\ln{7}\over \ln{x}}+1\over {\ln{3}\over \ln{x}}+1}=1$$


text:
Q: SQL Server 2000 query that omits commas in resulting rows? Wondering if there is a way to query a SQL Server database and somehow format columns to omit commas in the data if there is any.
Reason for asking is I have 10000+ records and through out the data the varchar have data like 3,25% and other 1%.
I'd prefer not to alter the data in the original table thus asking if a select with other functions would do the trick.
I have thought about selecting all the data into a temp table and stripping the commas but that is a lot of work for every time I do the query.
Any info or if its is possible please reply.

A: Take a look at the REPLACE function:
SELECT REPLACE(YourColumn, ',', '')
    FROM YourTable

A: Use SQL REPLACE :
REPLACE(YourField,',','')


text:
Q: shell script : for loop on list of files I have a folder with lots of files and I want to perform an action with some of the files. I have files "BlaBla_01.mat", "BlaBla_02.mat" up to "BlaBla_11.mat"
{ time mpiexec -n 40 ./runex @alg.param BlaBla_01.mat; }

--> this generates 2 output files. I need to rename and move them...
mv FirstOut.log My/Folder/Results/FirstOut_BlaBla_01.log
mv NextOut.log My/Folder/Results/NextOut_BlaBla_01.log

How do I make this in a for loop so that the files are processed and renamed as they should?
I have tried:
NUMS='01 02 03 04 05 06 07 08 09 10 11'
for i in $NUMS;
do
FILENAME="BlaBla_"$i".mat"
{ time mpiexec -n 40 ./runex @alg.param $FILENAME; }
mv FirstOut.log "My/Folder/Results/FirstOut_BlaBla_"$i".log"
mv NextOut.log "My/Folder/Results/NextOut_BlaBla_"$i".log"
done;

and many variants of it, but it does not work.
I am sorry this must be a very easy question but I am not a programmer so this is my first week on shell scripts
Thank you in advance,
have a nice weekend
Seb

A: Try this:
NUMS='01 02 03 04 05 06 07 08 09 10 11'
for i in ${NUMS[@]};
do
FILENAME="BlaBla_"$i".mat"
{ time mpiexec -n 40 ./runex @alg.param $FILENAME; }
mv FirstOut.log "My/Folder/Results/FirstOut_BlaBla_"$i".log"
mv NextOut.log "My/Folder/Results/NextOut_BlaBla_"$i".log"
done;

A: I would write that as
for root in BlaBla_{01..11}; do
    time mpiexec -n 40 ./runex @alg.param "$root.mat"
    mv FirstOut.log "My/Folder/Results/FirstOut_$root.log"
    mv NextOut.log "My/Folder/Results/NextOut_$root.log"
done;

Requires bash for the brace expansion


text:
Q: Automatic Script to turn off and on I would like to know how to create a script that Automatically stop and start a Google Compute Engine instance. and how can I configure him to run every day and choose to run it only 5 days a week?
because we are not using the server it nights so i can save 9 hours a day.
can it be done?
thank you.

A: You can use gcloud command line tool for that (of course from another machine), it provides all controls, including starting and stopping instances. Setup cron on your local machine for:
gcloud compute instances stop INSTANCE_NAMES
gcloud compute instances start INSTANCE_NAMES

See more:

*

*https://cloud.google.com/sdk/gcloud/reference/compute/instances/stop

*https://cloud.google.com/sdk/gcloud/reference/compute/instances/start

A: As far as I know, GCE doesn't provide scheduled VM stop/start as a managed feature, it has to be triggered outside of the VM. For example, you can a GAE scheduled task which uses gcloud or GCE Python SDK to start and stop your VM.

A: You can use Google Cloud Scheduler in conjunction with Cloud Functions to run lightweight cronjobs which start/stop GCE VM instances based on a schedule that you control.
You can find a step-by-step tutorial in the official docs, but the general flow is:

*

*Use Cloud Scheduler to publish start/stop messages to a Cloud Pub/Sub topic at the desired times (ex: every weekday at 9am, write a start VM event, every weekday at 5pm, write a stop VM event)

*Create a Cloud Function which subscribes to the Pub/Sub topic, and makes the appropriate calls to the GCE APIs to trigger start/stop VM.


text:
Q: How to display  without creating a textbox in jquery? I have a comment box(textarea) in which the user types something and when he hits enter that thing is automatically displayed in 'comment section'. Now when the user hits submit I'm executing the following code,
var comment = $("#commentBox").val();
var commentSection = $("#commentSection");
comment.appendTo(commentSection);

By the above code the comment typed by user is dynamically displayed in the commentSection. This works fine but when user types something like,
<input type='text'>

in the comment box then a textbox is created within the comment section. So is there a way through which I could not let this happen?
Thanks in advance.

A: One way would be to just append the data as .text
Something like this:
var comment = $("#commentBox").val();
var commentSection = $("#commentSection");
commentSection.text(comment);

Edit: To append to an existing part of the comment, replace:
commentSection.text(comment);

with:
commentSection.text(commentSection.text() + comment);

A: You have to convert the string to entities. Define this function:
function htmlencode(str) {
    return str.replace(/[&<>"']/g, function($0) {
        return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
    });
}

Then run the following code when the user hits enter:
var comment = htmlencode($("#commentBox").val());
var commentSection = $("#commentSection");
comment.appendTo(commentSection);

A: Try this ,
div.insertAdjacentHTML( 'beforeend', comment);

A: You can use
var commentText = $("#commentBox").text();

but this do not clean html tags on your string, additionally you can use a function to do this
function RemoveHTMLTags(vals) {
            var regX = /(<([^>]+)>)/ig;
            var html = vals;
            return (html.replace(regX, ""));
        }

and then you use:
var finalComment = RemoveHTMLTags(commentText);


text:
Q: Google Api in Excel to calculate Driving Distance between places I have about 20 K pairs to calculate driving distance between them. I am using following VB script -
'Calculate Google Maps distance between two addresses
Public Function GetDistance(start As String, dest As String)
    Dim firstVal As String, secondVal As String, lastVal As String
    firstVal = "http://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins="
    secondVal = "&destinations="
    lastVal = "&mode=car&language=en&sensor=false&key=A***Bh*Eh-g***LvJ7bRirvjlr****OkUvs"
    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    Url = firstVal & Replace(start, " ", "+") & secondVal & Replace(dest, " ", "+") & lastVal
    objHTTP.Open "GET", Url, False
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    objHTTP.send ("")
    If InStr(objHTTP.responseText, """distance"" : {") = 0 Then GoTo ErrorHandl
    Set regex = CreateObject("VBScript.RegExp"): regex.Pattern = """value"".*?([0-9]+)": regex.Global = False
    Set matches = regex.Execute(objHTTP.responseText)
    tmpVal = Replace(matches(0).SubMatches(0), ".", Application.International(xlListSeparator))
    GetDistance = CDbl(tmpVal)
    Exit Function
ErrorHandl:
    GetDistance = -1
End Function

When I write =GetDistance("Atlanta", "Miami") it throws -1 (Error). However, when I paste the URL in browser, it works.

A: I've the same error but I found an other way (you need to activate the reference Microsoft XML, v6.0) :
Function G_DISTANCE(Origin As String, Destination As String) As Double
' Requires a reference to Microsoft XML, v6.0

Dim myRequest As XMLHTTP60
Dim myDomDoc As DOMDocument60
Dim distanceNode As IXMLDOMNode
    G_DISTANCE = 0
    ' Check and clean inputs
    On Error GoTo exitRoute
    Origin = WorksheetFunction.EncodeURL(Origin)
    Destination = WorksheetFunction.EncodeURL(Destination)
    ' Read the XML data from the Google Maps API
    Set myRequest = New XMLHTTP60
    myRequest.Open "GET", "http://maps.googleapis.com/maps/api/directions/xml?origin=" _
        & Origin & "&destination=" & Destination & "&sensor=false", False
    myRequest.send
    ' Make the XML readable usign XPath
    Set myDomDoc = New DOMDocument60
    myDomDoc.LoadXML myRequest.responseText
    ' Get the distance node value
    Set distanceNode = myDomDoc.SelectSingleNode("//leg/distance/value")
    If Not distanceNode Is Nothing Then G_DISTANCE = distanceNode.Text / 1000
exitRoute:
    ' Tidy up
    Set distanceNode = Nothing
    Set myDomDoc = Nothing
    Set myRequest = Nothing
End Function

source : http://oco-carbon.com/coding/distance-function-google-excel/
Result with your code :

Result with the second function :

A: In your code, you are using http where the API is only accepting https now, all you need to do is replace http with https
firstVal = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="


text:
Q: How do I get Charles Proxy to Accept traffic for sites that have invalid certs? I'm trying to test some changes from my iPhone for a website that I have running on a VM (which I access from my Macbook).  The website on the VM is HTTPS only, but the cert is invalid because it's a development machine.  My Macbook has a host file entry to the VM, so when I'm testing via the browser all I have to do is accept the invalid cert.  I'm using Charles proxy on the Macbook, and connect my Phone just fine - the only issue is I can't access the site that has the invalid cert:
SSLHandshake: Received fatal alert: certificate_unknown

Other sites I try to access via the iPhone that are HTTPS work fine. Is there a way to install or accept an invalid cert into the Charles Proxy itself?


text:
Q: Java: How to implement Word Break? I'm trying to understanding the following Java + Dynamic Programming implementation (https://pingzhblog.wordpress.com/2015/09/17/word-break/):
public class Solution {
    public boolean wordBreak(String s, Set<String> wordDict) {
        if(s == null) {
            return false;
        }

        boolean[] wordBreakDp = new boolean[s.length() + 1];
        wordBreakDp[0] = true;
        for(int i = 1; i <= s.length(); i++) {
            for(int j = 0; j < i; j++) {
                String word = s.substring(j, i);
                if(wordBreakDp[j] && wordDict.contains(word)) {
                    wordBreakDp[i] = true;
                    break;
                }
            }
        }//end for i
        return wordBreakDp[s.length()];
    }
}

But need some clarification with String s = "abcxyz" and Set <String> wordDict = ["z", "xy", "ab", "c"].
I'm still unclear as to what wordBreakDp[] represents, and setting one to true means.
So I made the attempt and got wordBreakDP[2,3,5,6]=true, but what do those indexes tell? Couldn't I have just checked for i=6 since all we are checking is if last index of wordBreakDp[] is true, wordBreakDp[s.length()];?
And say for example I got ab for s.substring(0, 2);, but then how can we just assume that next loop, s.substring(1, 2);, is not useful and just break; out of the loop?
Thank you

A: This isn't really an answer, but it might be helpful in understanding the loops.  It prints the value of substring(i,j) and also wordBreakDp[j] at each iteration.  It also prints the final solution (segmentation) at the end of the method.
public boolean wordBreak(String s, Set<String> wordDict) {
    if(s == null) {
        return false;
    }

    boolean[] wordBreakDp = new boolean[s.length() + 1];
    wordBreakDp[0] = true;
    for(int i = 1; i <= s.length(); i++) {
        for(int j = 0; j < i; j++) {

            String word = s.substring(j, i);
            System.out.println("["+j+","+i+"]="+s.substring(j,i)+", wordBreakDP["+j+"]="+wordBreakDp[j]);
            if(wordBreakDp[j] && wordDict.contains(word)) {
                wordBreakDp[i] = true;
                break;
            }
        }
    }//end for i
    for (int i = 1, start=0; i <= s.length(); i++) {
        if (wordBreakDp[i]) {
            System.out.println(s.substring(start,i));
            start = i;
        }
    }
    return wordBreakDp[s.length()];
}

A: I think I have the answer to your last question, which was:

And say for example I got ab for s.substring(0, 2);, but then how can
  we just assume that next loop, s.substring(1, 2);, is not useful and
  just break; out of the loop?

You are right that if you got "ab" for s.substring(0,2) and you break out of the loop, this doesn't necessarily mean that s.substring(1,2) is not useful.  Let's say that s.substring(1,2) is useful.  This means that "a" is also a valid word, and so is "b".  The solution found by this algorithm would start with "ab" whereas the solution found by not breaking would be "a" followed by "b".  Both these solutions are correct (assuming that the rest of the string can be broken into valid words as well).  The algorithm doesn't find all valid solutions.  It just returns true if the string can be broken into valid words, i.e., if there is one solution that satisfies the condition.  There may be more than one solution, of course, but that is not the purpose of this algorithm.

A: Note, f[i] means whether the first i characters of s is valid. An example,

String = catsand
Dict = [cat, cats, sand, and]

 s =     c a t s a n d
dp =   T F F T T F F ?
 i =   0 1 2 3 4 5 6 7
                     *

Note dp[0] is True, because empty string is valid. Say we have dp[0] through dp[6].
Let's calculate dp[7], which denotes whether catsand is valid.

For catsand to be valid, there must be a non-empty suffix that is in dict, AND the remaining prefix is valid.
"catsand" is a valid, if:

  If "" is valid, and "catsand" is inDict, or
  If "c" is valid, and "atsand" is inDict, or
  If "ca" is valid, and "tsand" is inDict, or
  If "cat" is valid, and "sand" is inDict, or
  If "cats" is valid, and "and" is inDict, or
  If "catsa" is valid, and "nd" is inDict, or
  If "catsan" is valid, and "d" is inDict

Translated to pesudo code:
dp[7] is True, if:
        j               j  i
  If dp[0] && inDict( s[0..7) ) or
  If dp[1] && inDict( s[1..7) ) or
  If dp[2] && inDict( s[2..7) ) or
  If dp[3] && inDict( s[3..7) ) or
  If dp[4] && inDict( s[4..7) ) or
  If dp[5] && inDict( s[5..7) ) or
  If dp[6] && inDict( s[6..7) )

A: public class Solution {
    public int wordBreak(String a, ArrayList<String> b) {
        int n = a.length();
        boolean dp[] = new boolean[n+1];
        dp[0] = true;
        for(int i = 0;i<n;i++){
            if(!dp[i])continue;
            for(String s : b){
                int len = s.length();
                int end = len + i;
                if(end > n || dp[end])continue;
                if(a.substring(i,end).equals(s)){
                    dp[end] = true;
                }

            }
        }
        if(dp[n])return 1;
        else return 0;
    }
}


text:
Q: It will be true that if $\theta_{n} \to \theta$, then $\cos {\theta_n} \to \cos {\theta}$. It will be true that if $\theta_{n} \to \theta$, then $\cos {\theta_n} \to \cos {\theta}$.
I have looked for some counterexample for this statement but I have not found it. So I tried to prove this statement using the definition directly, but I couldn't.
So I want to know some justification for the truth or falsity of this statement.

A: Since $\cos$ is a continuous function, whenever $\lim_{n\to\infty}\theta_n=\theta$, $\lim_{n\to\infty}\cos(\theta_n)=\cos(\theta)$.


text:
Q: How do I properly instal and import matplotlib? I'm facing an issue while trying to import matplotlib 3.3.1. I'm using PyCharm which give me the following error :
Traceback (most recent call last):

  File "<input>", line 1, in <module>

  File "Y:\7-Python\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs)

  File "C:\Users\MMK\Miniconda3\envs\env1\lib\site-packages\matplotlib\__init__.py", line 174, in <module> _check_versions()

  File "C:\Users\MMK\Miniconda3\envs\env1\lib\site-packages\matplotlib\__init__.py", line 159, in _check_versions from . import ft2font

  File "Y:\7-Python\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs)

ImportError: DLL load failed while importing ft2font: Le module spécifié est introuvable.

I've been looking on many topics with the same issue about ft2front but none of them gave me a solution that worked. None of them were exactly the same, line error were different. Does anyone already faced a similar error and management to solved it ?
Thanks for your help.
Nicolas
Edit:
I tried to install it in another way: I downloaded the wheel file and installed it. PyCharm is now showing me a different error message :

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "Y:\7-Python\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "C:\Users\MMK\Miniconda3\envs\env1\lib\site-packages\matplotlib\__init__.py", line 905, in <module>
    cbook._get_data_path("matplotlibrc"),
  File "C:\Users\MMK\Miniconda3\envs\env1\lib\site-packages\matplotlib\cbook\__init__.py", line 480, in _get_data_path
    return Path(matplotlib.get_data_path(), *args)
AttributeError: module 'matplotlib' has no attribute 'get_data_path'

I still don't have any idea what this means...

A: In PyCharm, go to File --> Settings --> Project --> Project Interpreter
You will see a list of packages, click on the "+" sign at your right and search for matplotlib. Once you find the package just click on "Install Package" Screenshot for your reference


text:
Q: Darcs dependency tree view Is there a tool that can show a tree view representing patches dependencies in darcs? I found DarcsDeps but it seems dead and I couldn't make it work.

A: Besides the tool you found, no. Your best bet may be to continue to try to get it to work.


text:
Q: Mobile number permutation problem Question: How many 8 digit mobile numbers can be formed if any digit can be repeated and 0 can also start the mobile number?
The answer is $10^{8}$. However, why couldn't $10\times10\times1\times1\times1\times1\times1\times1$ be correct. Numbers $1$-$10$ can still be repeated.

A: Because the number $10\times 10 \times 1 \times 1 \times 1 \times 1\times 1 \times 1$ represents how many mobile numbers there are with the condition that 2  of the figures can take any of the digits and the rest can only take one possible digit.


text:
Q: How to: On keypress get textarea1 height and set height to textarea2 I have 2 textareas (textarea1 and textarea2). On textarea1 im using an expander. As you type the textarea expands. Now, what ever you type on the textarea1 is written on textarea2 but the second textarea doesn't expand. I am looking something that would get the height from textarea1 as im typing and set it to textarea2.
I would image it would be something like:
$("#textarea1").bind("keyup keypress paste mouseup", function() {
    $('#textarea1').val().height== ('#textarea2').height??

or
$("#textarea1").bind("keyup keypress paste mouseup", function() {
    $('#textarea2').attr('height', $('#textarea1').val().height);

None of those work.
Thanks alot

A: $("#textarea2").css("height", $("#textarea1").height() + "px");

That should work.

A: $("#textarea1").bind("keyup keypress paste mouseup", function() {
    $('#textarea2').css('height', $('#textarea1').height());


text:
Q: How to get a list of users who shared a specific post (graph api) How to get a user list (just the Facebook user id's) from a specific post on a fanpage?
Searching since a fiew hours but just found FQL- or the deprecated sharer.php stuff.

A: You have to use the POST_ID to get the details of the shares, just like this-
$facebook->api('/POST_ID');


text:
Q: How can I Portably Catch and Handle UTF "EN DASH" Minuses During c++ STL File Reading? I'm maintaining a large open source project, so I'm running into an odd fringe case on the I/O front.
When my app parses a user parameter file containing a line of text like the following:
CH3 CH2 CH2 CH2     −68.189775    2    180.0              ! TraPPE 1

...at first it looks innocent because it is formatted as desired.  But then I see the minus is a UTF character (−) rather than (-).
I'm just using STL's >> with the ifstream object.
When it attempts to convert to a negative and fails on the UTF character STL apparently just sets the internal flag to "bad", which was triggering my logic that stops the reading process.  This is sort of good as without that logic I would have had an even harder time tracking it down.
But it's definitely not my desired error handling.  I want to catch common minus like characters when reading a double with >>, replace them and complete the conversion if the string is otherwise a properly formatted negative number.
This appears to be happening to my users relatively frequently as they're copying and pasting from programs (calculator or Excel perhaps in Windows?) to get their file values.
I was somewhat surprised not to find this problem on Stack Overflow, as it seems pretty ubiquitous.  I found some reference to this on this question:
c++ error cannot be used as a function, some stray error [closed]
...but that was a slightly different problem, in which the code contained that kind of similar, but noncompatible "minus-like" EN DASH UTF character.
Does anyone have a good solution (preferably compact, portable, and reusable) for catch such bad minuses when reading doubles or signed integers?
Note:
I don't want to use Boost or c++11 as believe it or not some of my users on certain supercomputers don't have access to those libraries.  I'm try to keep it as portable as possible.

A: May be using a custom std::num_get is for you. Other character to value aspects can be overwritten as well.
#include <iostream>
#include <string>
#include <sstream>

class num_get : public std::num_get<wchar_t>
{
public:
    iter_type do_get( iter_type begin, iter_type end, std::ios_base & str,
                      std::ios_base::iostate & error, float & value ) const
    {
        bool neg=false;
        if(*begin==8722) {
            begin++;
            neg=true;
        }

        iter_type i = std::num_get<wchar_t>::do_get(begin, end, str, error, value);

        if (!(error & std::ios_base::failbit))
        {
            if(neg)
                value=-value;
        }
        return i;
    }
};

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

    std::locale new_locale(std::cin.getloc(), new num_get);

    // Parsing wchar_t streams makes live easier but in principle
    // it should work with char (e.g. UTF8 as well)

    static const std::wstring ws(L"CH3 CH2 CH2 CH2     −68.189775    2    180.0              ! TraPPE 1");
    std::basic_stringstream<wchar_t> wss(ws);
    std::wstring a;
    std::wstring b;
    std::wstring c;
    float f=0;

    // Imbue this new locale into wss
    wss.imbue(new_locale);

    for(int i=0;i<4;i++) {
        std::wstring s;
        wss >> s >> std::ws;
        std::wcerr << s << std::endl;
    }

    wss >> f;

    std::wcerr << f << std::endl;
}

A: Not gonna happen except manually. There are many characters in Unicode, there's an Em Dash as well as an En Dash, and most likely quite a few more. For example, did you consider the possibility of an Em Dash and then a non-breaking-space and then some numbers? Or an RTL override? Unicode is legend because the possibilities are nearly endless, and double-legend in C++ because the Standard support for it could be charitably described as ISIS's support for sanity.
The only real way to do this is to find each situation as your users report it, and handle it manually- i.e., do not use operator>> for double.


text:
Q: Problem in the integration of the SDK with an application We need to solve a problem with the the intregration of the SDK with the Android application.
This is a scenario:
we're collaborating with a a development company in order to integrate Marketing Cloud's SDK in an app of a common client, but they've identified a problem with its implementation: - They noticed that many users experienced crashes within the app (on Android devices, version 8 and above), and due to their analysis, those crashes rely on Marketing Cloud's SDK library.
They're not able to identify the precise method which causes crashes because the problem comes up only in production, and they're not able to reproduce it in the development version.
They told us that there are not other SDKs or stacks that can interfere with the initialization of MC's SDK, and they ensure us that the implementation has been done correctly, so according to their analysis the problem is solvable only by you. Also, it seems that crashes come just after the MArketing Cloud's SDK initialization.
Here I paste the error stacktraces:
Fatal Exception: java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done
+ 353(AsyncTask.java:353) at java.util.concurrent.FutureTask.finishCompletion
+ 383(FutureTask.java:383) at java.util.concurrent.FutureTask.setException
+ 252(FutureTask.java:252) at java.util.concurrent.FutureTask.run
+ 271(FutureTask.java:271) at java.util.concurrent.ThreadPoolExecutor.runWorker
+ 1162(ThreadPoolExecutor.java:1162) at java.util.concurrent.ThreadPoolExecutor$Worker.run
+ 636(ThreadPoolExecutor.java:636) at java.lang.Thread.run
+ 764(Thread.java:764) Caused by java.lang.SecurityException: Caller no longer running, last stopped +863ms because: timed out while starting at android.os.Parcel.readException
+ 2013(Parcel.java:2013) at android.os.Parcel.readException
+ 1959(Parcel.java:1959) at android.app.job.IJobCallback$Stub$Proxy.dequeueWork
+ 191(IJobCallback.java:191) at android.app.job.JobParameters.dequeueWork
+ 208(JobParameters.java:208) at com.salesforce.marketingcloud.e$f.b
+ 12(e.java:12) at com.salesforce.marketingcloud.e.d
+ 4(e.java:4) at com.salesforce.marketingcloud.e$a.a
+ 18(e.java:18) at com.salesforce.marketingcloud.e$a.doInBackground
+ 2(e.java:2) at android.os.AsyncTask$2.call
+ 333(AsyncTask.java:333) at java.util.concurrent.FutureTask.run
+ 266(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker
+ 1162(ThreadPoolExecutor.java:1162) at java.util.concurrent.ThreadPoolExecutor$Worker.run
+ 636(ThreadPoolExecutor.java:636) at java.lang.Thread.run
+ 764(Thread.java:764)

A: Please see Google's LONG STANDING bugs with regards to JobIntentService and "star" this bug (ref. https://issuetracker.google.com/issues/63622293) and the other similar associated bugs.  This bug is not being generated by the Marketing Cloud SDK.


text:
Q: Can't read objects from a file So, to implement the file I/O, i made the following code. i also made a header file cuz i keep using it again and again. i am new to making header files, and including them so pls point out the mistakes and how to rectify them.
this is my header file
#ifndef STUDENT_H
#define STUDENT_H

class student
{
    public:
        void getstud();
        void putstud();
        int retroll();
        char* retname();
        int retclass();
        student();
        virtual ~student();
        student(const student& other);
    protected:
    private:
        int roll;
        char name[35];
        int Class;
};

#endif // STUDENT_H

and this is the corresponding cpp file
#include "student.h"

using namespace std;
void student::getstud()
{
    cout<<"\nenter the roll number : "; cin>>roll;
    cin.clear(); cin.ignore(1);
    cout<<"\nenter the name        : "; cin.getline(name, 35);
    cout<<"\nenter the class       : "; cin>>Class;
}

void student::putstud()
{
    cout<<"\nroll number : "<<roll;
    cout<<"\nname        : "<<name;
    cout<<"\nClass       : "<<Class;
}

int student::retroll() {return roll;}

char* student::retname() {return name;}

int student::retclass() {return Class;}

student::student()
{
    //ctor
}

student::~student()
{
    //dtor
}

student::student(const student& other)
{
    //copy ctor
}

and this is the program :
# include <fstream>
# include <conio.h>
# include "student.cpp"

using namespace std;

int main()
{
    student s, s2;
    fstream file;

    file.open("recs.dat", ios::binary);
    cout<<"enter the details of a student :\n";
    s.getstud();
    file.write((char *)&s, sizeof(s));
    file.seekg(0); file.clear();
    file.read((char *)&s2, sizeof(s2));
    s2.putstud();
    s.putstud();
    file.close();
    return 0;
}

the output comes something like
enter the details of the student :
enter roll number : 23
enter name        : danny
enter Class       : 12

roll number  : (some number)
name         :
class        : 8
roll number  : 23
name         : danny
class        : 12

what could go wrong? pls help.


text:
Q: Delete Query from codeigniter I'm trying to figure out how I need to do this query. I'm trying to delete all the users who have registered but not activated witin a certain time limit.
function purgeNA($expirePeriod)
{
    $this->db->where('usersStatusesID', 1);
    $this->db->where('UNIX_TIMESTAMP(registrationDate) <', time() - $expirePeriod);
    $this->db->delete($this->usersRegistrationsTable);
}

Here's my db structure:
usersRegistrationsTable - userID, registrationDate
usersTable              - userID, usersStatusesID

A: To my knowledge, codeigniter doesn't support JOINs in DELETE queries via the Active Record interface. Instead, you'll need to execute a SQL statement:
$sql = "DELETE FROM
          usersTable u
          JOIN usersRegistrationsTable r ON u.userID = r.userID
          WHERE usersStatusesID = 1 AND UNIX_TIMESTAMP(registrationDate) < ?";
$this->db->query($sql, array(time() = $expirePeriod));


text:
Q: Notification Hub Bulk Import Failing with "Bad Format" error I have followed the sample code provided by Microsoft at the following location:
https://learn.microsoft.com/en-us/previous-versions/azure/azure-services/dn790624(v=azure.100)
When I create the job NotificationHubJobType.ImportCreateRegistrations everything runs and completes without an error. However when I look at the output created by the job I have a failure file with every registration listed as follows:
<AppleRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"><RegistrationId i:nil="true" /><DeviceToken>1234</DeviceToken></AppleRegistrationDescription>,BadRequest,Bad Format

Notice at the end it says "BadRequest,Bad Format". I do not know what this if referring to or how to fix it. Here is a sample from my input file:
<AppleRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"><RegistrationId i:nil="true" /><DeviceToken>1234</DeviceToken></AppleRegistrationDescription>
<AppleRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"><RegistrationId i:nil="true" /><DeviceToken>4321</DeviceToken></AppleRegistrationDescription>

Any help or suggestions would be greatly appreciated.

A: We apologize for the inaccuracy in the document, we are in a process of fixing it. Can you please try to use NotificationHub SDK instead of Service Bus SDK mentioned in the document.
Also, the XML should look like:
< RegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance", Type="AppleRegistrationDescription" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">< RegistrationId i:nil="true" />< DeviceToken>1234< /DeviceToken>< /AppleRegistrationDescription>


text:
Q: Sending a mail as both HTML and Plain Text in .net I'm sending mail from my C# Application, using the SmtpClient. Works great, but I have to decide if I want to send the mail as Plain Text or HTML. I wonder, is there a way to send both? I think that's called multipart.
I googled a bit, but most examples essentially did not use SmtpClient but composed the whole SMTP-Body themselves, which is a bit "scary", so I wonder if something is built in the .net Framework 3.0?
If not, is there any really well used/robust Third Party Library for sending e-Mails?

A: On top of using AlternateViews views to add both the html and the plain text view, make sure you are not also setting the body of the Mail Message object.
// do not do this:
var msg = new MailMessage(model.From, model.To);
msg.Body = compiledHtml;

As it will make your email contain the html content in both views, overriding the alternative views.

A: For the people(like me) who've had the problem of gmail displaying the plaintext part instead of the html part.
Gmail seems to always display the last part in your message.
So if you've added the html part before your plain text part chances are gmail will always show the plain text variant.
To fix this you can simply add the plain text part before your html part.

A: The MSDN Documentation seems to miss one thing though, I had to set the content type manually, but otherwise, it works like a charm :-)
MailMessage msg = new MailMessage(username, nu.email, subject, body);
msg.BodyEncoding = Encoding.UTF8;
msg.SubjectEncoding = Encoding.UTF8;

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContent);
htmlView.ContentType = new System.Net.Mime.ContentType("text/html");
msg.AlternateViews.Add(htmlView);

A: What you want to do is use the AlternateViews property on the MailMessage
http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx

A: Just want to add that you can use defined constants MediaTypeNames.Text.Html and MediaTypeNames.Text.Plain instead of "text/html" and "text/plain", which is always a preferable way. It's in System.Net.Mime namespace.
So in the example above, it would be:
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContent, null, MediaTypeNames.Text.Html);

A: I'm just going to put a note here for anyone that's having problems and finds their way to this page - sometimes, Outlook SMTP servers will reconvert outgoing email.  If you're seeing your plain-text body vanish entirely, and nothing but base64-encoded attachments, it might be because your server is reencoding the email.  Google's SMTP server does not reencode email - try sending through there and see what happens.

A: For anyone who bumped into this issue you might want to check if you have preheader tags in your html.
In my html I've added a  tag with a phrase of "Activate your client admin account by clicking the link.".
It seems like gmail is flagging the phrase "clicking the link" after removing it, all my emails that has been sent, are going straight to the inbox.


text:
Q: C++ Login System tips I am trying to make a secure auth system without using php/post any tips on how i can improve this. Maybe adding more checks?
if (IsWindows8OrGreater())
{
    cout << "Wrong Windows Version Contact an Admin" << endl;
    cout << "press any key then press enter to exit" << endl;
    cin.get();
    return 0;
}
DWORD disk_serialINT;
GetVolumeInformation("C://", NULL, NULL, &disk_serialINT, NULL, NULL, NULL, NULL);
TCHAR volumeName[MAX_PATH + 1] = { 0 };
TCHAR fileSystemName[MAX_PATH + 1] = { 0 };
DWORD serialNumber = 0;
DWORD maxComponentLen = 0;
DWORD fileSystemFlags = 0;
if (GetVolumeInformation(_T("C:\\"),volumeName,ARRAYSIZE(volumeName),& serialNumber, & maxComponentLen, & fileSystemFlags,  fileSystemName, ARRAYSIZE(fileSystemName)))
{
        _tprintf(_T("Serial Number: %lu\n"), serialNumber);
        _tprintf(_T("fileSystemFlags Number: %lu\n"), fileSystemFlags);
}
if (Customer == serialNumber && CustomerFlags == fileSystemFlags)
{
    printf("Serial Number Matches required version\n");
}


text:
Q: how to add pdf header and footer dynamically using hhandoko (play26-scala-pdf) in play framework 2.6 I'm using hhandoko (play26-scala-pdf) library for dynamic pdf generation.
The task is to generate a pdf from tabular format data (more than 1000 rows). First, I create an HTML page and generate a pdf from the above library (hhandoko). I need to add a header and footer for pdf (each page).
How do I add header and footer?
pdfGen
        .toBytes(
          views.html.pdfGenerator("hello", Seq.empty, 33.3,None),
          ""
          ,
          Seq("fonts/opensans-regular.ttf")
    )


text:
Q: "Why" is every polynomial representation of SL(2) selfdual? Given a field $K$ of characteristic $0$. It seems to me that every finite-dimensional polynomial representation of $\mathrm{SL}_2\left(K\right)$ is self-dual (i. e., isomorphic to its dual). In fact, every representation of $\mathrm{SL}_2\left(K\right)$ is a direct sum of irreducible representations (since $\mathrm{SL}_2\left(K\right)$ is semisimple), and the irreducible representations are the canonical representations on $K\left[x,y\right]_n$ which are known to be self-dual. But is there a simpler proof without subdividing into irreducibles?

A: Because its Weyl group contains -1.
For split semisimple groups in char 0, taking duals corresponds to acting by -1 on the weight lattice, where irreducible polynomial representations correspond to weights modulo the action of the Weyl group. So if -1 is in the Weyl group (acting on the weight lattice), then any (irreducible) representation is isomorphic to its dual. This includes the groups with Dynkin diagrams A1, Bn, Cn, Dn for n even,  E7, E8, F4, G2 but not An for n>1, Dn for n odd and E6.

A: Here is a variant of Richard's answer.  In the group $ SU(2) $ every element is conjugate to its inverse.  Hence the characters of a representation and its dual are the same.  (Richard's answer is essentially this answer restricted to the torus, which is sufficient.)
To alleviate your concerns, smooth complex representations of $SU(2) $  and algebraic complex representations of $SL_2(\mathbb{C}) $ are the same thing.

A: I'm not sure that you can expect to avoid "subdividing into irreducibles", since
the result is not true without semisimplicity. If $K$ has characteristic $p>0$,
the $SL_2(K) = SL(V)$-representation on the $p+1$-dimensional space
$\operatorname{Sym}^p(V)$ (the $p$th symmetric power of the natural 2 dim'l representation)
is not self-dual.

A: The question itself and some of the comments seem out of focus to me, so let me add to what Richard and George write the following summary version of an answer.  I'd stress that nothing here is really complicated or subtle to prove apart from the basic Cartan-Weyl classification and (in characteristic 0) complete reducibility for finite dimensional representations.
First, the group itself is defined and split over the prime field (here $\mathbb{Q}$), hence over any larger field.   Chevalley's theory implies that the representations discussed here are absolutely irreducible over $K$.   (For a semisimple group defined but not split over a field, more analysis is needed of representations which require a field extension to become absolutely irreducdible.)
Anyway, for a connected semisimple group the "rational" and "polynomial" representations are the same, unlike the reductive group GL$(n,K)$.   The group also being simply connected in this case, the rational/polynomial representations are essentially those of the Lie algebra and are more easily classified by dominant integral highest weights in that setting.   So each irreducible representation or simple module in question has a unique highest weight $\lambda$.  The easy textbook criterion for such a module to be self-dual is just that $\lambda = -w_0 \lambda$ where $w_0$ is the longest element of the Weyl group.   As Richard Borcherds points out, this is -1 just for simple types listed, including type $A_1$.
So far nothing really depends on characteristic 0.   But as George McNinch observes, there are plenty of cases where nonsimple modules in prime characteristic fail to be completely reducible and are typically not self-dual.   So you do need to invoke complete reducibility (and non-canonical direct sum decompositions) to dispose of the characteristic 0 question.
P.S.  It's certainly possible to treat the rank 1 case here by direct ad hoc methods in characteristic 0, including the needed proof of complete reducibility (using the easily computed Casimir operator).   For irreducible representations, self-duality is a trivial consequence of the fact that these representations are uniquely classified (up to isomorphism) by their dimensions 1, 2, 3, ....   But such an ad hoc argument fails to provide much enlightenment.  And the general theory allows one to see that the group representations and Lie algebra representations are essentially the same, whether the groups are regarded as Lie groups or algebraic groups (or just as abstract groups).   Of course, finite dimensionality is a key point throughout, since the infinite dimensional representation theory involves harder questions.


text:
Q: RAM size dependent on memory type I have a laptop with the processor Intel 4450U installed. The specification says

Max Memory Size (dependent on memory type) 32 GB

So what does the (dependent on memory type) actually mean for me? I would like to upgrade the PC with maximum available capacity, but I can't find any clues that would help me to understand what limits and for each type of RAM (DDR4 / DDR3L) are applied. Is there a way to figure it out?

A: In this case the memory type probably refers to the type of memory chips accepted by the mainboard chosen by the system manufacturer than the speed or generation of the RAM.
When looking at the maximum memory a specific pre-built computer supports, you do not consult the CPU details, you consult the documentation for the system you purchased, where the limits will be spelled out.
Laptops typically use SO-DIMMs, which are smaller than the regular DIMMs used in desktop computers, and these have an accompanying limitation on the physical number of memory chips that will fit on them, and therefore the maximum amount of memory each SO-DIMM can hold.
Then, if the laptop only has 1 user-accessible memory slot, you are limited to only that one slot's maximum memory. If the laptop has two slots, then you get to put to SO-DIMMs in with an accompanying higher maximum memory in the computer.
So, what the CPU says and what you'll actually get are two different things. Consult your system documentation, not the CPU's technical specs.

A: Some manufacturers allow higher densities of ECC (error-correcting code) RAM.  Dell Precision T1650s can support 16 GB of non-ECC, but up to 32 GB of ECC.  ECC was very important once for servers, but nowadays memory manufacturing is reliable enough that there's not much difference.  See https://blog.codinghorror.com/to-ecc-or-not-to-ecc/ .


text:
Q: What dropdown box does rails_admin use? I want to use it in my rails projects instead of the default selectbox, but can't figure out what kind it is or how to implement it in my code.
The rails_admin one is more like a textbox with typeahead instead of just a standard dropdown.
Thanks!

A: It looks like they have created their own, here take a look:
https://github.com/sferik/rails_admin/blob/master/app/assets/javascripts/rails_admin/ra.filtering-multiselect.js
It would be nice to pull it out and make a plugin, as a note it does look like it depends on jQuery, and jQueryUI.


text:
Q: Selecionar elementos aleatoriamente de um array sem repetir Antes de tudo, procurei em diversos sites sobre esse problema e encontrei inúmeros exemplos, mas infelizmente nenhum desses exemplos funcionou na resolução do meu problema.
Enfim, estou desenvolvendo um quiz com base no jogo CS:GO, onde será mostrada uma foto e o usuário precisa acertar o nome da posição referente a foto (com base no jogo). Para isso, criei um array que possui objetos, que, por sua vez, possuem a imagem e o nome da posição que será mostrada. Por conta disso eu preciso que esses objetos com essas infos. sejam escolhidos randomicamente sem repetição, até o array não ter mais opções disponíveis.
Consegui chegar perto desse meu objetivo através desse código:

const maps = [
  {
    mapName: "dust ii",
    positions: [
      {
        posicao: "fundo",
        posicaoImg: "#",
      },
      {
        posicao: "escuro baixo",
        posicaoImg: "#",
      },
      {
        posicao: "base tr",
        posicaoImg: "#",
      },
      {
        posicao: "base ct",
        posicaoImg: "#",
      },
    ],
  },
  {
    mapName: "mirage",
    positions: [
      {
        posicao: "fundomirage",
        posicaoImg: "#",
      },
      {
        posicao: "escuro baixomirage",
        posicaoImg: "#",
      },
    ],
  },
];

let selectElementMap = document.getElementById("mapSelector");
let valueSelectedMap;
let positionAlreadyChosen = [];

function getSelectedValuesIndex() {
  valueSelectedMap =
    selectElementMap.options[selectElementMap.selectedIndex].value; // pegando o mapa através do "<select>" no html

  let positions = maps[valueSelectedMap].positions; // pega o array que contem o nome das posições e a imagem

  let randomArrayPos = Math.floor(
    Math.random() * maps[valueSelectedMap].positions.length
  );

  return (showPosition = positions[randomArrayPos].posicao); // pega uma posição aleatória do mapa
}

function basicLogic() {
  getSelectedValuesIndex();

  // verificar se a posição gerada já foi selecionada
  if (!positionAlreadyChosen.includes(showPosition)) {
    positionAlreadyChosen.push(showPosition);
  }
  console.log(positionAlreadyChosen);
}

      <select name="mapSelector" id="mapSelector">
        <option value="" disabled selected>Selecione um mapa</option>
        <option value="0">Dust II</option>
        <option value="1">Mirage</option>
        <option value="2">Cache</option>

      </select>

    <button class="play" onclick="basicLogic();">Jogar</button>

Logo, com esse código eu consigo o seguinte resultado quando clico para pegar os elementos random:

Com tudo explicado, minha dúvida é a seguinte:
Há uma forma mais fácil de se fazer esse processo, sem que seja preciso clicar 9x (como no exemplo) para que todas as posições sejam escolhidas?

A: Já pensou em apenas criar uma cópia do seu array e ordenar de forma aleatória?

const desordenar = (arr) => {
  const copia = [...arr];

  for (let i = copia.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [copia[i], copia[j]] = [copia[j], copia[i]];
  }

  return copia;
};

const desordenado = desordenar(['fundo', 'base tr', 'base ct']);
console.log(desordenado.shift()); // Pega o primeiro da lista
console.log(desordenado.shift()); // Pega o segundo da lista
console.log(desordenado.shift()); // Pega o terceiro da lista

A função acima é baseada no algoritmo Fisher-Yates shuffle que consistem em colocar todos os elementos em um array e, de trás pra frente, permutar sua posição com algum elemento aleatório.

No caso do seu código a sugestão seria a seguinte:

const maps = [{
    mapName: "dust ii",
    positions: [{
        posicao: "fundo",
        posicaoImg: "#",
      },
      {
        posicao: "escuro baixo",
        posicaoImg: "#",
      },
      {
        posicao: "base tr",
        posicaoImg: "#",
      },
      {
        posicao: "base ct",
        posicaoImg: "#",
      },
    ],
  },
  {
    mapName: "mirage",
    positions: [{
        posicao: "fundomirage",
        posicaoImg: "#",
      },
      {
        posicao: "escuro baixomirage",
        posicaoImg: "#",
      },
    ],
  },
];

const desordenados = {};

let selectElementMap = document.getElementById("mapSelector");

const desordenar = (arr) => {
  const copia = [...arr];

  for (let i = copia.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [copia[i], copia[j]] = [copia[j], copia[i]];
  }

  return copia;
};

function basicLogic() {
  const valueSelectedMap = selectElementMap.options[selectElementMap.selectedIndex].value;
  const desordenado = desordenados[valueSelectedMap]?.length ? desordenados[valueSelectedMap] :  desordenar(maps[valueSelectedMap].positions); // o array que será randomizado com base no <select> do usuario
  desordenados[valueSelectedMap] = desordenado;
  console.log(desordenado.shift()); // Pega o primeiro da lista
}

      <select name="mapSelector" id="mapSelector">
        <option value="" disabled selected>Selecione um mapa</option>
        <option value="0">Dust II</option>
        <option value="1">Mirage</option>
        <option value="2">Cache</option>

      </select>

    <button class="play" onclick="basicLogic();">Jogar</button>

Referência: Shuffle an array.


text:
Q: Recover deleted records
Possible Duplicate:
How do I get back some deleted records?

Our C#.NET application mistakenly deleted all records from all tables of its database.
The application automatically takes backups, and the last backup it took after this delete is big in size, which means there must be useful data in the backup. The recovery model of the database is SIMPLE and I turned the server off after the records were deleted.
How can I recover the deleted records?

A: It sounds like, with your scenario, the easiest way would be to grab a backup of the database and restore it side-by-side your current database.  You need to ensure that this backup contains the deleted records.  Then simply do an INSERT INTO ... SELECT FROM ... to get the deleted records from the old database (via a backup/restored version) into your current.
If you don't have a backup of the database containing all of the data, you may be out of luck here.

A: Here are few suggestions:

*

*If you have transaction started then you can rollback the transaction which will get teh deleted records back.

*If you have the full backup of the DB then restore the DB and all your data will be in place.

*If you have taken a snapshot fo the DB then you can restore from that snapshot as well like
USE master;
RESTORE DATABASE DBNAME FROM DATABASE_SNAPSHOT = 'SNAPSHOT NAME';
GO

*Else, if you have transaction log enabled then you can restore from transaction log as all deletes gets logged.
Check this link on how to do the same
http://raresql.com/2011/10/22/how-to-recover-deleted-data-from-sql-sever/


text:
Q: ValueError: Could not interpret optimizer identifier:  my TensorFlow.keras is on '2.1.6-tf'`.
I have built a simple cnn as follows: but the optimizer isn't working, throwing this error  :
ValueError: Could not interpret optimizer identifier: <tensorflow.python.keras.optimizers.Adam object at 0x7f149b4f7908>

from sklearn.model_selection import train_test_split
from tensorflow.keras import datasets, layers, models, Input
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from keras.regularizers import l2
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt

# create model
model = Sequential()
model.add(Dense(10, input_dim=10, activation='relu'))
model.add(Dense(9, activation='relu'))
model.add(Dense(1, activation='relu'))

# Compile model
opt = Adam(lr=0.0001, clipnorm=1.0, clipvalue=0.5)
model.compile(loss='binary_crossentropy', optimizer= opt, metrics=['accuracy'])

  [1]: https://i.stack.imgur.com/Mu9KJ.png

A: First you need to import 'Adam' optimizer from keras using adam_v2:
from tensorflow.python.keras.optimizers import adam_v2

and then define your optimizer as below and small reminder lr keyword is deprecated you will use learning_rate:
opt = adam_v2.Adam(learning_rate=0.0001, clipnorm=1.0, clipvalue=0.5)

then you can proceed...


text:
Q: aplicacion cliente /servidor con TCPClient Buenos días, estoy desarrollando una aplicacion que se comunica con una caja de control y recibe datos de la mismo. la caja de control me envia una trama en ascii con la cual determino si un sensor esta siendo tapado o una bucla esta siendo pisada, y le envio una trama en ascii para controlar 2 semaforos. la comuniacion que utilizo es via serial/ethernet con un conversor. el problema que tengo es que con la clase TCPclient, puedo enviar datos a la caja de control sin problemas, pero cuando deseo recibir datos de la misma utilizando tcplistener me aparece el mensaje:

la comunicacion con la caja de control es de forma continua es decir que estoy recibiendo y enviado datos al mismo tiempo. como puedo solucionar este problema si puedo enviar por que no puedo recibir sin problemas, que estoy haciendo mal?
les adjunto un fragmento del codigo que me valida la recepcion de datos y me arroja el error.
Public Class RecebirDato
Public Delegate Sub ClientCarrier(conexionTcp As ConexionTCP)
Public Event OnClientConnected As ClientCarrier
Public Event OnClientDisconnected As ClientCarrier
Public Delegate Sub DataRecieved(conexionTcp As ConexionTCP, data As String)
Public Event OnDataRecieved As DataRecieved
Public Shared _tcpListener As TcpListener
Public Shadows _acceptThread As Thread
Private connectedClients As New List(Of ConexionTCP)

Public Sub New()
    AddHandler OnDataRecieved, AddressOf MensajeRecibido
    AddHandler OnClientConnected, AddressOf ConexionRecibida
    AddHandler OnClientDisconnected, AddressOf ConexionCerrada
End Sub

Private Sub MensajeRecibido(conexionTcp As ConexionTCP, datos As String)
    Dim paquete = New Paquete(datos)
    Dim valor As String
    Dim principal As New Principal
    Dim contenido As String = paquete.Contenido
    Dim valores As List(Of String) = Mapa.Deserializar(contenido)
    valor = valores(0)
    Dim msgPack = New Paquete(valor)
    conexionTcp.EnviarPaquete(msgPack)
    principal.txtObservaciones.Text = valor
End Sub

Private Sub ConexionRecibida(conexionTcp As ConexionTCP)
    SyncLock connectedClients
        If Not connectedClients.Contains(conexionTcp) Then
            connectedClients.Add(conexionTcp)
        End If
    End SyncLock
    'Invoke(New Action(Function() InlineAssignHelper(label1.Text, String.Format("Clientes: {0}", connectedClients.Count))))
End Sub

Private Sub ConexionCerrada(conexionTcp As ConexionTCP)
    SyncLock connectedClients
        If connectedClients.Contains(conexionTcp) Then
            Dim cliIndex As Integer = connectedClients.IndexOf(conexionTcp)
            connectedClients.RemoveAt(cliIndex)
        End If
    End SyncLock
    'Invoke(New Action(Function() InlineAssignHelper(label1.Text, String.Format("Clientes: {0}", connectedClients.Count))))
End Sub

Public Sub EscucharClientes(_ipAddress As String, _port As Integer)
    Try
        _tcpListener = New TcpListener(IPAddress.Parse(_ipAddress), _port)
        _tcpListener.Start()
        _acceptThread = New Thread(AddressOf AceptarClientes)
        _acceptThread.Start()
    Catch e As Exception
        MessageBox.Show(e.Message.ToString())
    End Try
End Sub

Private Sub AceptarClientes()
    Do
        Try
            Dim conexion = _tcpListener.AcceptTcpClient()
            Dim srvClient = New ConexionTCP(conexion)
            With srvClient
                .ReadThread = New Thread(AddressOf LeerDatos)
            End With
            srvClient.ReadThread.Start(srvClient)
            RaiseEvent OnClientConnected(srvClient)
        Catch e As Exception
            MessageBox.Show(e.Message.ToString())
        End Try
    Loop While True
End Sub

Private Sub LeerDatos(client As Object)
    Dim cli = TryCast(client, ConexionTCP)
    Dim charBuffer = New List(Of Integer)()
    Do
        Try
            If cli Is Nothing Then
                Exit Try
            End If
            If cli.streamReader.EndOfStream Then
                Exit Try
            End If
            Dim charCode As Integer = cli.streamReader.Read()
            If charCode = -1 Then
                Exit Try
            End If
            If charCode <> 0 Then
                charBuffer.Add(charCode)
                Continue Do
            End If
            If OnDataRecievedEvent IsNot Nothing Then
                Dim chars = New Char(charBuffer.Count - 1) {}
                For i As Integer = 0 To charBuffer.Count - 1
                    chars(i) = Convert.ToChar(charBuffer(i))
                Next i
                Dim message = New String(chars)
                RaiseEvent OnDataRecieved(cli, message)
            End If
            charBuffer.Clear()
        Catch generatedExceptionName As IOException
            Exit Try
        Catch e As Exception
            MessageBox.Show(e.Message.ToString())
            Exit Try
        End Try
    Loop While True
    RaiseEvent OnClientDisconnected(cli)
End Sub

End Class
de antemano gracias por su ayuda.

A: ya lo resolvi, lo único que hize fue crear una clase cliente TCP que me enviara y recibiera datos de un servidor, es clase la instancio las veces que necesite con rutas ip que se encuentren dentro del segmento de red.
gracias saludos.


text:
Q: design pattern for determine if an app has shutdown cleanly what's the best design pattern to check to see if an app has shutdown cleanly(eg. didn't crash)?
It seems creating a lock file in the current directory and deleting the file upon normal shutdown is a good way, or is it?
are there better ways?
The app is in java, so I plan to add a shutdown hook to the instance to delete the lock file. is this a good way?

A: Adding a shutdown hook doesn't seem ideal to me, as I'd expect a shutdown hook to still be executed if the application crashed. I'd just make the deletion part of "normal system exit".
But yes, having a file seems pretty reasonable to me. One caveat though - consider what would happen if your application were opened twice or more concurrently. You may want to create a randomly-named file instead of one with a fixed name.


text:
Q: Google Cloud Text To Speech REST API Authentication So I want to use the Google Cloud Text to Speech using a simple POST request from my C++ program, the problem is with their authentication. I did create a service account as they mentioned and I got the file containing my private key. But I don't know how can I use it in my POST request to be authenticated ?
POST Url: https://texttospeech.googleapis.com/v1beta1/text:synthesize
and here is my POST body:
{
    "audioConfig": {
    "audioEncoding": "LINEAR16",
    "pitch": "0.00",
    "speakingRate": "1.00"
  },
  "input": {
    "text": "Hello World"
  },
  "voice": {
    "languageCode": "en-US",
    "name": "en-US-Wavenet-E"
  }
}

A: I found out that I need to create an API Key Credential from the following link:
https://console.developers.google.com/apis/credentials?project=[your-project-name]
and then append "?key=[API_KEY]" to my POST url and the authentication problem is fixed !

A: You have to set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON file that contains your service account key.