text:
Q: How to set backgrond in alert dialog in android I am new in android and developing one of application. In this application, I need to open dialog box about company info.
That box open success in every mobile but background of dialog display white in some mobile and blank in some mobile.
So, How can i set background of particular color so display same in all mobiles.
Below of my dialog alert code:
private void aboutas() {
        ImageView image = new ImageView(this);

        TextView tv = new TextView(this);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        tv.setText(Html
                .fromHtml("
 &nbsp &nbsp Version 1.0

 &nbsp &nbsp Developed by   XYZ

&nbsp &nbsp  Powered by   XYZ

 &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp  Copyright © 2015
"));

        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        String titlepage = "About wallperper app";
        alertDialog.setTitle(titlepage);
        alertDialog.setView(tv);
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // TODO Add your code for the button here.

            }
        });
        // Set the Icon for the Dialog
        alertDialog.setIcon(R.drawable.ic_launcher_icon);
        alertDialog.show();

    }

I tried to solve but not get it proper.
Any one have a idea?
Thanks

A: you can set custom view programmatically like this way..
LayoutInflater inflater = getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.dialog_layout, (ViewGroup) getCurrentFocus());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialoglayout);
builder.show();

then after to get reference of component
e.g. Button btn = (Button) dialoglayout.findViewById(R.id.button_id);

A: If you just want a light theme and aren't particular about the specific color, then you can pass a theme id to the AlertDialog.Builder constructor.
AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)...

or
AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)...

or You can create a custom alertDialog and use a xml layout. in the layout, you can set the background color and textcolor.
Something like this:
Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
LayoutInflater inflater = (LayoutInflater)ActivityName.this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_layout,(ViewGroup)findViewById(R.id.layout_root));
dialog.setContentView(view);

A: Create a layout xml with your desired background color.
Place your TextView,ImageView.. components in the layout.
Inflate it to get the View
And finally set the AlertDialog's view as the inflated View


text:
Q: Vertical line not centered between columns using ruledtabular How do I get the vertical line in the middle of the columns while using ruledtabular, not like this?
\documentclass{revtex4-2}
\begin{document}
\begin{ruledtabular}
\begin{tabular}{c|c}
    a & b \\
    aaaaa & bbbbb \\
\end{tabular}
\end{ruledtabular}
\end{document}

Simple answers while maintaining the use of ruledtabular and the house style (full width tables), that will be accepted by journal editors preferred :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert an angle in degrees, to a vector I'm doing some game programming. FWIW I'm using XNA, but I'm doubtful that this is relevant.
I'd like to convert degrees to a directional vector (ie X and Y) with magnitude 1.
My origin (0,0) is in the upper left.
So I'd like 0 degrees to convert to [0, -1]
I thought the best way to do this was to take my definition of North/Up and rotate it using a matrix, but this does not seem to be working.
Here is the Code...
public class Conversion
{
    public static Vector2 GetDirectionVectorFromDegrees(float Degrees)
    {
        Vector2 North= new Vector2(0, -1);
        float Radians = MathHelper.ToRadians(Degrees);

        var RotationMatrix = Matrix.CreateRotationZ(Radians);
        return Vector2.Transform(North, RotationMatrix);
    }
}

... and here are my unit tests...
[TestFixture]
public class Turning_Tests
{
    [Test]
    public void Degrees0_Tests()
    {
        Vector2 result = Conversion.GetDirectionVectorFromDegrees(0);
        Assert.AreEqual(0, result.X);
        Assert.AreEqual(-1, result.Y);
    }
    [Test]
    public void Degrees90_Tests()
    {
        Vector2 result = Conversion.GetDirectionVectorFromDegrees(90);
        Assert.AreEqual(1, result.X);
        Assert.AreEqual(0, result.Y);
    }
    [Test]
    public void Degrees180_Tests()
    {
        Vector2 result = Conversion.GetDirectionVectorFromDegrees(180);
        Assert.AreEqual(0, result.X);
        Assert.AreEqual(1, result.Y);
    }
    [Test]
    public void Degrees270_Tests()
    {
        Vector2 result = Conversion.GetDirectionVectorFromDegrees(270);
        Assert.AreEqual(-1, result.X);
        Assert.AreEqual(0, result.Y);
    }

}

Am I approaching this all wrong?
Should I be using a matrix?
Have I screwed up and converted from degrees to radians in the wrong place?
I've seen suggestions that this can be done using code like:
new Vector2((float)Math.Cos(Angle), (float)Math.Sin(Angle));

...or sometimes...
new Vector2((float)Math.Sin(Angle), (float)Math.Cos(Angle));

However these don't seem to work either
Can someone put me on the right path... or better yet give me some code which causes the 4 provided unit tests to path?
Many thanks in advance.

A: Just use:
new Vector2((float)Math.Cos(radians), (float)Math.Sin(radians))

Be sure to convert from degrees to radians with this approach too.
This uses the mathematician's convention of starting from [1, 0] and going in the direction towards [0, 1] (that is counter-clockwise with the orientation that mathematicians use for the two axes).
To use instead your convention (starting from [0, -1] and going in the direction of [1, 0]) you need:
new Vector2((float)Math.Sin(radians), -(float)Math.Cos(radians))

Note that your conversion from degrees to radians can never be exact (it involves something with π). You should allow for some tolerance in your tests. Also, if you use double instead of float for the radians, you will have some extra precision in the intermediate calculation.


text:
Q: Find elements with certain pattern in attribute I have some elements with id attributes like this:

...

...

...

...

How i can select only those
 elements that end with -1 in the id attribute?

A: There is a functions ends-with so using //div[ends-with(@id, '-1')] should suffice. For more complex stuff you can use matches e.g. //div[matches(@id, '-[0-9]+$')] would select all div elements where the id attribute value ends with a minus - followed by a number of digits.


text:
Q: Автоматическая отправка email Мне нужно ПОЛНОСТЬЮ автоматическая отправка письма на email. Очень распространённый код ниже прекрасен: он заполняет поля письма и автоматически выбирает программу отправки, но критически не хватает последнего пинка - автоматического "нажатия" на кнопку отправки.
 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
        emailIntent.setData(Uri.parse("mailto:" + "andron.gen@gmail.com"));
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "My email subject");
        emailIntent.putExtra(Intent.EXTRA_TEXT, "My email body");

        try {startActivity(Intent.createChooser(emailIntent, "Send email using..."));
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(MainActivity.this, "No email clients installed.", Toast.LENGTH_SHORT).show();}

Что нужно дописать/исправить, что бы оно само пошло гулять?

A: Средствами андроид вы этого сделать не сможете т.к. система запрещает вам делать какие-либо действия без ведома пользователя.
Если вы хотите отправлять email как вы хотите, вам необходимо написать полностью свой сервис по отправке почты и взаимодействовать с ним из вашего приложения.


text:
Q: Only fire Material Autocomplete when more than 2 chars have been entered I have a material autocomplete component that is working pretty well. I've shamelessly cobbled it together from various online examples. I am struggling to figure out how to have the search only fire when 2 or more chars are entered.
assignSearchAutocomplete(){
    this.acCtrl.valueChanges
        .pipe(
            debounceTime(500),
            tap(() => {
                this.acErrorMsg = "";
                this.acFilteredItems = [];
                this.acIsLoading = true;
            }),
            switchMap(value => this.svcGetFacetGql.watch({ name: ".*" + value + ".*", label: this.facetLabel, options: { fetchPolicy: 'cache-and-network' } })
                .valueChanges
                .pipe(
                    tap(() => {
                        this.acIsLoading = false
                    }),
                )
            )
        )
        .subscribe(response => {
            if (response['data'] == undefined) {
                this.acErrorMsg = response['Error'];
                this.acFilteredItems = [];
            } else {
                this.acErrorMsg = "";
                this.acFilteredItems = response['data']['Facet'];
            }
        });
}

I've tried inserting an if statement and using a ternary operator :? but can't get it to work.
Thanks

A: What if you try with a filter ?
this.acCtrl.valueChanges
  .pipe(
    debounceTime(500),
    filter(value => value.length > 2),
    tap(() => {
    ...
    }
  );

A: You can filter out those values, where the string is empty or too short.
assignSearchAutocomplete(){
    this.acCtrl.valueChanges
        .pipe(
            // new part
            filter(value => value && value.length >=2),
            // end of new part
            debounceTime(500),
            tap(() => {
                this.acErrorMsg = "";
                this.acFilteredItems = [];
                this.acIsLoading = true;
            }),
            // ...
        )
        .subscribe(response => {
            if (response['data'] == undefined) {
                this.acErrorMsg = response['Error'];
                this.acFilteredItems = [];
            } else {
                this.acErrorMsg = "";
                this.acFilteredItems = response['data']['Facet'];
            }
        });
}


text:
Q: Undoing changes made to local file with git I have two branches of my project: master and live. I made some changes to my local files and when i was done, i wanted to push the changes to master. I never knew the current branch on git was live. I ran:
git add .
git commit -m "integrated ckeditor to replace Froalaeditor"
git pull --rebase bonychicken master

It was at this point git spat out:
From github.com:Lord-sarcastic/bonychicken
 * branch            master     -> FETCH_HEAD
First, rewinding head to replay your work on top of it...
Applying: changed debug to false
Applying: integrated ckeditor to replace Froalaeditor.

And then I lost all changes to my local files.
So far i've tried
git reflog master
git reset --hard HEAD@{0}

It doesn't work.
Neither does git rebase --abort

A:
I never knew the current branch on git was live

In your case, git reflog live, since you seem to have committed on the branch named live.
Then you can read the commit SHA1 you just created, and reset --hard your live branch to said commit.


text:
Q: Silence javascript errors in the browser Suppose I'm doing a CORS request but I don't always know it works for various reasons. A request like:
$.ajax('http://a-website.com:8888');

When it fails, the browser shows an error in the console:

XMLHttpRequest cannot load http://a-website.com:8888. Origin http://another-website.com is not allowed by Access-Control-Allow-Origin.

How can I intercept it and avoid it showing up in the page console as an error?

A: You can put your ajax call in a try catch
try{
   $.ajax('http://a-website.com:8888');
}
catch(e){
   //your catching logic
}

A: If it's being printed in console, it means something is doing that.
In my projects, I use top print a JS variable in HTML Document, and use a function for printing in console. That function also allows to provide a title for the log and prints data's type.
In that function I verify that variable, if it's false I just return without printing anything. This way I can easily shutdown any log application-wide.
I suggest you to take a look where this console.log() is, and delete it, or ask its author to allow disabling it.


text:
Q: Linearization of product of three variables Let $h=xyz$, where $x,y \in \{0,1\}$ and $z \in [0,T]$ with $T>0$ being a constant. Is there any method that can linearize  $h=xyz$? For example, if $h=xy$ the method in here can be used to linearize this.

A: A slightly better answer to this (better in the sense is that it gives the convex hull) is to use the 8 inequalities:
$$ h \leq z$$
$$h \leq T x$$
$$h \leq Ty$$
$$x \leq 1$$
$$y \leq 1$$
$$z \leq T$$
$$h \geq Tx + Ty + z - 2T$$
$$h \geq 0$$

A: We want to model $h=xyz$, where $x,y \in \{0,1\}$ and $z \in [0,T]$ with $T>0$ being a constant. We first linearize $xy$ in the same way as described in the link you posted. To do so, we introduce a new variable $w$ along with the following constraints:
$$w \leq x$$
$$w \leq y$$
$$w \geq x+y-1$$
$$ 0 \leq w \leq 1$$
All that is left now is to model $h=wz$. Since $z$ is upper bounded by $T$ and lower bounded by 0 we can do this in the following way:
$$h\leq T w$$
$$h \leq z$$
$$h \geq z - (1-w)T$$
$$h \geq 0$$.
So, if either $x$ or $y$ is zero, it will follow from the first two and the fourth constraint that $w = 0$. From constraint 5 and 8 it will then follow that $h=0$.
If, however $x=y=1$, constraints 1 to 3 will force $w=1$. Constraints 6 and 7 will then force $h=z$.


text:
Q: How can I use Autofac to resolve implementations of an interface only if they aren't "more" specialised? Summary
I'd like to know if it's possible to get Autofac to return an enumeration of all registered types that implement an interface on the proviso that they don't also implement an interface that derives from the requested one (i.e. aren't "more specialised" than requested).
Skip to the bottom for a code sample that demonstrates this.
Background
In a program I'm writing, I have a "controller" class that (until recently) accepted collections of 4 different types of collaborators, resolved and injected into it using Autofac during application startup:
public DeviceComponentController(
    IEnumerable<Lazy<IClientRequestProcessor<T>>> clientRequestProcessors,
    IEnumerable<Lazy<IClientResponseGenerator<T>>> clientResponseGenerators,
    IEnumerable<Lazy<IComponentDeviceMessageDecoder<T>>> deviceMessageDecoders,
    IEnumerable<Lazy<IComponentDeviceMessageEncoder<T>>> deviceMessageEncoders)
{
    // ...
}

However, I found that in some cases I needed collaborators to perform some particular logic that didn't really fit into any of these roles (i.e. was not directly related to client request processing, response generation, etc.). I could have "saddled" that logic onto a class already handling one of these things, but that would have violated Single Responsibility Principle.
Instead, I created a new interface IDeviceComponentControllerCollaborator (pretty verbose, I know!), from which these other interfaces extended:
interface IDeviceComponentControllerCollaborator
{
    // ...
}

interface IClientRequestProcessor : IDeviceComponentControllerCollaborator
{
    // ...
}

interface IClientResponseGenerator : IDeviceComponentControllerCollaborator
{
    // ...
}

// Etc.

I modified the controller constructor to accept additional collaborators that didn't fit neatly into any of the existing roles, but were able to interact with the other collaborators:
public DeviceComponentController(
    IEnumerable<Lazy<IClientRequestProcessor<T>>> clientRequestProcessors,
    IEnumerable<Lazy<IClientResponseGenerator<T>>> clientResponseGenerators,
    IEnumerable<Lazy<IComponentDeviceMessageDecoder<T>>> deviceMessageDecoders,
    IEnumerable<Lazy<IComponentDeviceMessageEncoder<T>>> deviceMessageEncoders,
    IEnumerable<Lazy<IDeviceComponentControllerCollaborator<T>>> genericCollaborators)
{
    // ...
}

However, I'm not entirely sure what the best way is of making Autofac resolve the genericCollaborators parameter when I request a DeviceComponentController. What I'd like is it to enumerate every registered IDeviceComponentControllerCollaborator that isn't a client request processor, client response generator, etc.
SSCCE
I've reduced the issue to the code sample below. Any solution for this code sample should hopefully resolve the issue I'm facing as well.
void Main()
{
    var builder = new ContainerBuilder();

    // These types _must_ be registered with all implemented interfaces.
    // In my real program I use an extension method to register these types,
    // which for simplicity uses `.AsImplementedInterfaces()`.
    //
    // However, the extension method in my program returns the registration
    // builder, so I can extend the registration on a case-by-case basis if I want
    // (e.g. adding metadata).
    builder.RegisterType<Foo>().AsImplementedInterfaces();
    builder.RegisterType<Bar>().AsImplementedInterfaces();
    builder.RegisterType<Baz>().AsImplementedInterfaces();
    builder.RegisterType<SomeGenericCollaborator>().AsImplementedInterfaces();
    builder.RegisterType<SomeOtherGenericCollaborator>().AsImplementedInterfaces();
    builder.RegisterType<YetAnotherGenericCallaborator>().AsImplementedInterfaces();

    var container = builder.Build();

    // Should give me Foo.
    var collaboratorsA = container.Resolve<IEnumerable<ISpecialisedCollaboratorA>>();

    // Should give me Bar and Baz.
    var collaboratorsB = container.Resolve<IEnumerable<ISpecialisedCollaboratorB>>();

    // Problem: how do I resolve just the "generic" collaborators?
    // I.e.
    //   - SomeGenericCollaborator
    //   - SomeOtherGenericCollaborator
    //   - YetAnotherGenericCallaborator
    //
    // var genericCollaborators = container.Resolve<...>(); ???
    //
    // This does not work (returns all 6 collaborators):
    // var genericCollaborators = container.Resolve<IEnumerable<ICollaborator>>();
}

// Interfaces
interface ICollaborator
{
}

interface ISpecialisedCollaboratorA : ICollaborator
{
}

interface ISpecialisedCollaboratorB : ICollaborator
{
}

// Implementation
class Foo : ISpecialisedCollaboratorA
{
}

class Bar : ISpecialisedCollaboratorB
{
}

class Baz : ISpecialisedCollaboratorB
{
}

class SomeGenericCollaborator : ICollaborator
{
}

class SomeOtherGenericCollaborator : ICollaborator
{
}

class YetAnotherGenericCallaborator : ICollaborator
{
}

Would this be something I'd need to resolve using named/keyed services, or is there an alternative?


text:
Q: Routing network traffic thru a Windows machine is very slow I have two Windows 10 Pro for Workstations machines connected via Thunderbolt Ethernet and would like to utilize the fast 10GbE connection to NAS server via PC_A to improve transfer rates for PC_B that doesn't have 10GbE adapter. The 10.10.10.0 network is managed by a router connected to a switch.
The requirement is to forward traffic from PC_B to NAS thru PC_A when it is available.
Network topology:

I don't want to bridge interfaces (in case one of the machines are down).
So far I did the following:

*

*On PC_A I've enabled routing (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\IPEnableRouter=1 and started routing service)

*On PC_A I've enabled Internet Connection Sharing from 10.10.10.100 interface to fast 20GbE interface which changed its IP to 192.168.137.1

*On PC_B I've set 20GbE interface to DHCP which got IP: 192.168.137.27 with gateway 192.168.137.1

*On PC_B I've added a static route for NAS IP route -p add 10.10.10.102 mask 255.255.255.255 192.168.137.1 IF 3 (where interface 3 is fast 20GbE one)

The transfer speed is extremely slow about 1MB/s, I have a feeling that "Internet Connection Sharing" isn't actually using Windows router.
When I disable "Internet Connection Sharing" and assign static IP to both sides of the 20GbE connection I can transfer data with full speed, but PC_B can't reach NAS server.
How can I forward traffic via PC_A or increase the speed of "Internet Connection Sharing"?


text:
Q: VM Heap Tab missing in DDMS Going over this blog on memory analysis, and realized i don't have any  VM Heap Tab  in my DDMS tool. Searched all over the tool, not finding that. Am i missing some thing, can you please point me to the right place. Thanks for your help in advance
I am using Android Studio in Ubuntu
Cheers

A: Window--->Show View--->Android--->Heap

A: Deleting the DDMS workspace preferences folder solved the issue. Preference is stored in %USERPROFILE%.android\monitor-workspace (e.g. C:\Users\my_user.android\monitor-workspace).
For Ubuntu users, you can find the file in
   home/my_user/.android/monitor-workspace.

Its a hidden file, so use Ctrl + H to view them.


text: Q: Get the file name using Google file ID Is it possible to get the file name using a the ID of a Google file? I was able to gather the ID's, open and download the files, but I want to get the file name as well.


text:
Q: Failed to extract files from Delphi resource file I have been using FindResource, LoadResource and LockResource to access resources in a res file. I have a wave file which I want extract and play through my Delphi application.
I have done it without extraction, but it's not the thing I want to do. I want to first extract the wave file. Can anyone point me to the right solution?

A: If you're already calling LoadResource and LockResource, then you're already halfway there. LockResource gives you a pointer to the first byte of the resource data. Call SizeofResource to find out how many bytes are there, and you can do whatever you want with that block of memory, such as copy it to another block of memory or write it to a file.
resinfo := FindResource(module, MakeIntResource(resid), type);
hres := LoadResource(module, resinfo);
pres := LockResource(module, hres);
// The following is the only new line in your code. You should
// already have code like the above.
size := SizeofResource(module, resinfo);

Copy to another memory block:
var
  buffer: TBytes;

SetLength(buffer, size);
Move(pres^, buffer[0], size);

Write to a file:
var
  fs: TStream;

fs := TFileStream.Create('foo.wav', fmCreate);
try
  fs.Write(pres^, size);
finally
  fs.Free;
end;

This gives us several ways to play that wave data:
PlaySound(MakeIntResource(resid), module, snd_Resource);
PlaySound(PChar(pres), 0, snd_Memory);
PlaySound(PChar(@buffer[0]), 0, snd_Memory);
PlaySound('foo.wav', 0, snd_FileName);

A: You can use TResourceStream class to load the WAVE resource, and save it to disk using SaveToFile method.


text:
Q: How to use std::fpos? On the 27.5.4 of the latest C++ standard draft, I find a weird template class std::fpos, but I don't know what it is intended for. (The documentation is vague, less informative, and hard to understand.)
I'm writing my own mini-STL for embedded systems, where I cannot use the compiler-provided STL because of its non-portability. So, I must understand what it means.
For example, I want to use C++11 to develop a linux kernel module, in this case, you cannot direct use any compiler-provided C++ standard library, no matter whether you use clang, gcc, or vc++. None is portable to the linux kernel. So, I have to implement a minimal STL from scratch.
Is there any example to illustrate how to use std::fpos?

A: std::fpos<StateT> is used to represent a position in a stream, including the conversion state, i.e., the std::mbstate_t or it replacement for user provided character types. You can use std::pos<StateT> to restore the position of seekable streams, notably file streams. It is the result of the various seek operations on streams and is used as the argument for the seek operations seeking to an absolute position.
In principle, std::fpos<StateT> represent just a byte position in a stream. For streams travelling in the internal representation, i.e., where no encoding/decoding is needed, the byte position is probably all it stores. When file streams enter the picture, the position may be massive (i.e., bigger than could be represented with built-in integers in C++98 which only required 32 bits; std::fpos<StateT> was part of the standard since the first version) and the external encoding may be different than the internal one, requiring to capture encoding state.


text:
Q: Room error: Type of the parameter must be a class annotated with @Entity or a collection/array of it I'm getting the following error:
error: Type of the parameter must be a class annotated with @Entity or a collection/array of it.
    java.lang.String matchId);

on my matchedBefore() query:
@Dao
interface MatchedUsersDao {

    // Checks to see if user has matched before (if it returns 1)
    @Query("SELECT COUNT(*) FROM matched_users WHERE :matchId = match_id LIMIT 1")
    fun matchedBefore(matchId: String): Int

    @Insert(onConflict = OnConflictStrategy.ABORT)
    fun addMatchUid(matchId: String)
}

Here is my Entity
@Entity(tableName = "matched_users")
data class MatchedUser(
    @PrimaryKey(autoGenerate = true) val id: Int,
    @ColumnInfo(name = "match_id") val matchId: String
)

DB
@Database(entities = arrayOf(MatchedUser::class), version = 1)
abstract class AppDatabase : RoomDatabase() {

    abstract fun matchedUsersDao(): MatchedUsersDao
}

and I instantiate my DB in my Application:
class CustomApplication : Application() {

    companion object {
        var database: AppDatabase? = null
    }

    override fun onCreate() {
        super.onCreate()
        CustomApplication.database = Room.databaseBuilder(this, AppDatabase::class.java, "AppDatabase").build()
    }

Can someone tell me what the error is indicating and how I can solve it?

A: Your problem is this line
@Insert(onConflict = OnConflictStrategy.ABORT)
fun addMatchUid(matchId: String)

If you want use @Insert annotations you must send instance of MatchedUser not String.
So you can :
1) Send new MatchedUser with your id (insert empty MatchedUser with your id)
You code must be like this
@Insert(onConflict = OnConflictStrategy.ABORT)
fun addMatchUid(matchUser: MatchedUser)

2) Wrote new @Query for inserting just id in db


text:
Q: Highlight Headings in Navigation Pane in Word for Mac that contain the search string In the Windows version of Microsoft Word, I find it VERY useful that the headings listed in the Navigation pane get highlighted if their contents contain the search string. In this way, I can manually zero in on the search results only for sections I deem applicable. I feel severely handicapped when I switch to the Mac version of Word that it only highlights one heading at a time.
Is there a way to achieve the same functionality in the Mac version of Word?


text:
Q: Github failed to Authentication On my laptop (operating system Ubuntu 20.04), the git is installed and it's version is git version 2.33.0 and I have check the configuration using below command,
git config --list
command result is:
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
filter.lfs.clean=git-lfs clean -- %f
user.name=imdadulhaque1
user.email=imdadul......@gmail.com
user.password=........

N.B: I just use dot for security
Although I have used the same user name and same password but it's failed to push and show the below error,
Username for 'https://github.com': imdadulhaque1
Password for 'https://imdadulhaque1@github.com':
remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.
remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more information.
fatal: Authentication failed for 'https://github.com/imdadulhaque1/LearningOpenCV_with_Projects.git/'


text:
Q: Searching a log file
Possible Duplicate:
Searching using Regex in VIM or elsewhere

I'm searching a huge ~600 Mb file for a particular pattern which is 7 Hexadecimal values long. The Problem is

*

*the 'pattern' could be on the next line and

*there are several addressing lines.

I got rid of problem 1 by getting rid of all the carriage returns but I'm still faced with even if the values are on the next line I have no idea how to search past the address line. Below is an example:
0x000001A0: 36 5B 09 76 99 31 55 09 78 99 34 51 49 BF E0 03
0x000001B0: 28 0B 0A 03 0B E0 07 28 0B 0A 03 0B 49 58 09 35
For example: I want to be able to find the pattern 49 BF E0 03 28 0B 0A, Which goes across lines 1 and 2 above but I can't just search for it regularly because of the 0x000001B0: at the beginning of the line Any suggestions or c++ code or excel ideas would be helpful. I'm using VIM at the moment to open this big file and using excel won't open the entire thing.

A: Python, just read in line, split, chuck the first part, concat the hex into a string, and search. Something like this would work:
hex = ""
for each line in lines:
    tmp = line.split() // split on whitespace
    hex += tmp[1:] // grab everything after address

if hex.contains(pattern):
    # do something

Or use a regex, but you get the basic idea.

A: You could use a circular buffer.

*

*Open the file

*Read a line

*Read address and discart it

*Read first value and put it into the buffer

*Read next value, and throw last value of the buffer (std::list could be good for that)

*Check if buffer contains the pattern

*Loop through 5 up to the end of the line

*Loop through 2 up to the end of the file


text:
Q: Having trouble setting up react environment I'm learning ReactJS and tried to set up environment following this video
but I get errors when i execute 'npm run it' command in cmd.
Here's  package.json file:
{
  "name": "react-folder",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "it": "webpack-dev-server --hot"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-preset-react": "^6.24.1",
    "webpack": "^4.29.3",
    "webpack-dev-server": "^3.1.14"
  },
  "dependencies": {
    "react": "^16.8.1",
    "react-dom": "^16.8.1"
  }
}
Errors

A: npm install webpack-cli (if you are using older version of npm use npm install webpack-cli --save or you can just easily create react app with npx create-react-app AppName

A: 1st try installing webpack-cli as it's a requirement to run webpack now.
npm i -D webpack-cli


text:
Q: How I get model data without primary key I'm having trouble updating the data I get from my database. When I want to update directly from my model object, I get this error

arg = {k: v for k, v in kv_generator(self, arg.items())}
AttributeError: 'NoteORM' object has no attribute 'items'.

How do I get the data of my model excluding the primary key?
class NoteORM(Base):
    __tablename__ = "Notes"

    NoteID = Column(Integer, primary_key=True)
    Reciver = Column(Integer, ForeignKey("Users.UserID"))
    Note = Column(String, nullable=False)
    FilePath = Column(Text)
    IsSend = Column(String)
    created_at = Column(DateTime, server_default=func.now())
    updated_at = Column(DateTime, onupdate=func.now())

    u_notes = relationship("UsersORM", backref="Notes")

    # getting attirbute of object
    def props(cls):
        return [i for i in cls.__dict__.keys() if i[:1] != '_']

    entity = session.query(NoteORM).get(11)
    fields = props(entity) #I also get primary key :) when ı add underscore my primary key
                           #_NoteID also get error Invalid column name '_NoteID'

how can i update via object, is there a better way?

A:
how can i update via object, is there a better way?

SQLAlchemy's Session.merge() method takes care of the details for you:
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, declarative_base

engine = create_engine("sqlite://")
Base = declarative_base()

class Note(Base):
    __tablename__ = "note"
    id = Column(Integer, primary_key=True, autoincrement=False)
    note_text = Column(String, nullable=False)

Base.metadata.create_all(engine)

# create an existing "note 1"
with Session(engine) as sess:
    sess.add(Note(id=1, note_text="original note 1 text"))
    sess.commit()

# create a new Note object that we can use to update "note 1"
new_note_1 = Note(id=1, note_text="new note 1 text")

# simply adding new_note_1 to the session won't work
with Session(engine) as sess:
    sess.add(new_note_1)
    try:
        sess.commit()
    except IntegrityError as ie:
        print(ie)
        """
        (sqlite3.IntegrityError) UNIQUE constraint failed: note.id
        [SQL: INSERT INTO note (id, note_text) VALUES (?, ?)]
        [parameters: (1, 'new note 1 text')]
        """

# merging new_note_1 into the session works
engine.echo = True
with Session(engine) as sess:
    sess.merge(new_note_1)
    """
    SELECT note.id AS note_id, note.note_text AS note_note_text
    FROM note
    WHERE note.id = ?
    [generated in 0.00072s] (1,)
    """
    sess.commit()
    """
    UPDATE note SET note_text=? WHERE note.id = ?
    [generated in 0.00075s] ('new note 1 text', 1)
    """


text:
Q: Mixing radio buttons and text_field I'm trying to combine radio buttons and text_field for a single value :
= f.radio_button :system, "bacteria"
Bacteria
= f.radio_button :system, "mammalian"
Mammalian
= f.radio_button :system, "yeast"
Yeast
= f.radio_button :system, "insect"
Insect
= f.radio_button :system, "other"
Other:
= f.text_field :system, class:"input-small"

When I submit, nothing happens because a blank value is given in params even if a radio is checked (I think it considers the text field).
I tried to give another name to the text_field, and replaced the :system value in the controller after updating, but it looks like a dirty way...
Do you have any cleaner ideas ?

A: Here you can not directly mix radio_button and text_field together for the same field.
I think you can define one extra radio_button field that will be hidden and whose value will get updated when user enters into text_field.
= f.radio_button :system, "bacteria"
Bacteria
= f.radio_button :system, "mammalian"
Mammalian
= f.radio_button :system, "yeast"
Yeast
= f.radio_button :system, "insect"
Insect
= f.radio_button :system, "other"
Other:
= f.radio_button :system, nil, :id => :hidden_radio, :style => "display:none"
= f.text_field :free_system_input, class:"input-small", :id => :free_system_input

In above you will be writing onchange event on text_field and whenever value gets entered inside text_field it will set hidden radio_button's value to the text_field_value.
:javascript
 $("free_system_input").keyup(function(){
   $("hidden_radio").val($(this).val())
 })

Above code is just to give idea how to deal with issue and will not work just as it is .. :)

A: Thanks to Sandip's help, I managed to fix my problem!
Here is the view:
= f.radio_button :system, "bacteria"
Bacteria
= f.radio_button :system, "mammalian"
Mammalian
= f.radio_button :system, "yeast"
Yeast
= f.radio_button :system, "insect"
Insect
%br/
= f.radio_button :system, nil, id: 'other_system_radio',
                checked: radio_checked?('system', f.object.system)
Other:
%input.input-small#other_system_text{ value: text_input?('system', f.object.system) }

I use helper functions to manage edit form (fill the text field if the value if different from the given ones):
def radio_checked?(type,val)
  case type
    when 'system'
      ['bacteria', 'mammalian', 'yeast', 'insect'].include?(val) ? '' : 'checked'
    end
  end

def text_input?(type,val)
  case type
    when 'system'
      ['bacteria', 'mammalian', 'yeast', 'insect'].include?(val) ? '' : val
  end
end

And a bit of Javascript to select the "Other" radio button when the user focuses on the text field:
@handle_other_field = ->
  $('#other_system_text').focus( -> $('#other_system_radio').attr('checked','checked'))
  $('#other_system_text').keyup( -> $('#other_system_radio').val($(this).val()))


text:
Q: How can I include a file from a higher parent directory? How can I include a file from a higher parent directory in my index.php file?
Code:
//This is my index page
include_once "./../../../idea/file.html";

The project structure

A: You seem to be missing a dot. You will need to use one ../ for each depth you want to got up.
Try:
include_once "../../../../idea/file.html";

A: Assume your base path is responsive directory. You can include any file like this:
include_once(BASE_PATH."idea/file.html");


text:
Q: Make a sidebar disappear when you go under 450px I'm making a site and i want my sidebar to disappear when i go under 450px's because then all the other content gets bigger on phone. How can i do this with media queries?

@media (max-width: 450px){

}

Proteinpulver

Fatburners

Gainers

Aminosyror

Utrustinig för träning hemma

Mineraler för att orka

  get  up

 take  action

   take  over

A: This should do the trick:

@media screen and (max-width: 450px) {
  .sidebar {
    display: none;
  }
}

Proteinpulver

Fatburners

Gainers

Aminosyror

Utrustinig för träning hemma

Mineraler för att orka

  get  up

 take  action

   take  over

A:

@media (max-width: 450px){

   .sidebar{
   display: none;

}

Proteinpulver

Fatburners

Gainers

Aminosyror

Utrustinig för träning hemma

Mineraler för att orka

  get  up

 take  action

   take  over


text:
Q: Foreign key constraint exception in basic table design I'm using Entity Framework Core and have a simple 5 table design, but get an error and can't figure out why. What am I missing?
Exception:

Introducing FOREIGN KEY constraint
  'FK_GraphicItems_GraphicUploadTemplateItems_GraphicUploadTemplateItemId'
  on table 'GraphicItems' may cause cycles or multiple cascade paths.
  Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other
  FOREIGN KEY constraints.

Base:
public abstract class Base
{
    public int Id { get; set; }
    public DateTime DateCreated { get; set; } = DateTime.Now;
}

Client:
public class Client : Base
{
    public Guid Key { get; set; }
    public string Name { get; set; }
}

Graphic:
public class Graphic : Base
{
    public int ClientId { get; set; }
    public virtual Client Client { get; set; }
    public ICollection<GraphicItem> Items { get; set; } = new HashSet<GraphicItem>();
    public ICollection<Tag> Tags { get; set; } = new HashSet<Tag>();
}

GraphicItem: (the property GraphicUploadTemplateId causes the exception)
public class GraphicItem : Base
{
    public int GraphicId { get; set; }
    public virtual Graphic Graphic { get; set; }
    public int GraphicUploadTemplateItemId { get; set; }
    public virtual GraphicUploadTemplateItem UploadTemplateItem { get; set; }
}

GraphicUploadTemplate:
public class GraphicUploadTemplate : Base
{
    public int ClientId { get; set; }
    public virtual Client client { get; set; }
    public ICollection<GraphicUploadTemplateItem> Items { get; set; }
}

GraphicUploadTemplateItem:
public class GraphicUploadTemplateItem : Base
{
    public int GraphicUploadTemplateId { get; set; }
    public virtual GraphicUploadTemplate UploadTemplate { get; set; }
}

A: There will be a link to the corresponding GraphicUploadTemplateItem already through GraphicItem.UploadTemplateItem.Id, i think that causes the circular reference.

A: Fixed the problem by setting the property type to nullable
public class GraphicItem : Base
{
    public int GraphicId { get; set; }
    public virtual Graphic Graphic { get; set; }
    public int? GraphicUploadTemplateItemId { get; set; }
    public virtual GraphicUploadTemplateItem UploadTemplate { get; set; }
}


text:
Q: use MyPy on unittest setUp and tearDown methods I wonder how to apply mypy on unittest code.
Situation:
class TestPoint(unittest.TestCase):
    def setUp(self) -> None:
        self.point_origin = Point(0, 0, 0, name="origin")

    def tearDown(self) -> None:
        self.point_origin = None

    def test_point_coordinates(self) -> None:
        self.assertIsInstance(self.point_origin.x, (float, int))
        self.assertIsInstance(self.point_origin.y, (float, int))
        self.assertIsInstance(self.point_origin.z, (float, int))

This results in:
tests\test_geometry.py:114: error: Incompatible types in assignment (expression has type "None", variable has type "Point")

Now I can fix this inside the code to check if self.point_origin equals None, but the entire point was to tear down the fields before each test.
Should I just skip mypy in the test files? Or is there a better way to apply mypy on test code and/or change my test setup?


text:
Q: Return a new instance from a class method I've implemented a date class, which calculates the next day's date and the previous day's date.
eg. if today is 3/26/2022 (MM/DD/YYYY) then my method nextday gives 3/27/2022.
However, instead of returning a string, I am trying to return an instance but it's not working properly. It's calculating the day correctly but changes the original instance.
This is my class:
class Date:
    """
    Assigning class arguments
    """
    min_year = 1800
    dow_jan1 = "Wednesday"
    def __init__(self,month=1,day=1,year=min_year):
        """
        Assigning instance arguments and checking the validity of dates.
        If Not valid then an Exception is raised.
        """
        self.c_month = month
        self.c_day = day
        self.c_year = year

        if self.c_year < self.min_year:
            raise Exception("Invalid Year")
        elif self.c_month <1 or self.c_month > 12:
            raise Exception("Invalid Month")
        elif self.c_day<1 or self.c_day > 31:
            raise Exception("Invalid Day")
        else:
            if self.c_month == 2:
                if self.year_is_leap(self.c_year):
                    if self.c_day<1 or self.c_day > 29:
                        raise Exception("Invalid Day")
                else:
                    if self.c_day<1 or self.c_day > 28:
                        raise Exception("Invalid Day")
            else:
                months_31_days = [1,3,5,7,8,10,12]
                if self.c_month in months_31_days:
                    if self.c_day<1 or self.c_day > 31:
                        raise Exception("Invalid Day")
                else:
                    if self.c_day<1 or self.c_day > 30:
                        raise Exception("Invalid Day")

    def year_is_leap(self,year=None):
        """
        Finds if a year is Leap or not
        Parameters:
            year : takes a year which is to be checked
                    however if a year is not provided then the instance argument year (self.c_year)
                    is set as default value
        """
        if year is None:
            year = self.c_year

        if (year % 4) == 0:
            if (year % 100) == 0:
                if (year % 400) == 0:
                    return True
                else:
                    return False
            else:
                 return True
        else:
            return False

    def __str__(self):
        """
        returns the date in suitable format
        eg. 2/14/1900 => February 14, 1900
        """
        months = {1:"January",2:"February",3:"March",4:"April",
                  5:"May",6:"June",7:"July",8:"August",9:"September",
                  10:"October",11:"November",12:"December"}
        return "{} {}, {}".format(months[self.c_month],self.c_day,self.c_year)

    def nextday(self):
        """
        Returns next date in date object
        """
        leap_year = self.year_is_leap(self.c_year)
        #print(leap_year)

        if self.c_month in (1, 3, 5, 7, 8, 10, 12):
            month_length = 31
        elif self.c_month == 2:
            if leap_year:
                month_length = 29
            else:
                month_length = 28
        else:
            month_length = 30

        if self.c_day < month_length:
            self.c_day += 1
        else:
            self.c_day = 1
            if self.c_month == 12:
                self.c_month = 1
                self.c_year += 1
            else:
                self.c_month += 1
        print("The next date is [mm-dd-yyyy] %d-%d-%d." % (self.c_month, self.c_day,self.c_year))
        return self #Date(self.c_month,self.c_day,self.c_year) #Date #self.__class__()

    ```

I've tried to return `self`, `Date()`, `Date(self.c_month,self.c_day,self.c_year)` and `self.__class__()`, however none of it worked.
When I run:

firstdate = Date(1,1,Date.min_year)
print(firstdate)
print("The date after ", firstdate, "is", firstdate.nextday())

I am getting the output:

January 1, 1800
The next date is [mm-dd-yyyy] 1-2-1800.
The date after  January 2, 1800 is January 2, 1800

A: The most straightforward solution will be creating a new instance of Date with same values as self (basically copy it) and work with it, not changing self:
class Date:
    # other methods here

    def nextday(self):
        """
        Returns next date in date object
        """
        new_date = Date(self.c_month, self.c_day, self.c_year)
        is_leap_year = new_date.year_is_leap(new_date.c_year)

        if new_date.c_month in {1, 3, 5, 7, 8, 10, 12}:
            month_length = 31
        elif new_date.c_month == 2:
            month_length = 28 + is_leap_year
        else:
            month_length = 30

        if new_date.c_day < month_length:
            new_date.c_day += 1
        else:
            new_date.c_day = 1
            if new_date.c_month == 12:
                new_date.c_month = 1
                new_date.c_year += 1
            else:
                new_date.c_month += 1
        print("The next date is [mm-dd-yyyy] %d-%d-%d." % (new_date.c_month, new_date.c_day,new_date.c_year))
        return new_date

You could also implement some convenience methods (e.g. .copy to copy the date or __format__ to print the date, but that's out of question scope)

A: The problem is that you change the object attributes. For example on nextday method, you write self.c_day += 1, you are changing the object itself.
Instead, if you want to return a new Date, you need to write c_day += 1 then return Date(c_month, c_day, c_year)


text:
Q: Magento and Wordpress - $_GET variable disappears from query_string In a Wordpress+Magento integrated environment, I have a form in Wordpress that submits to another wordpress page. This form has an input field with the name of "zip". When this form submits, the "zip" seems to not make it to the receiving page. I can see it go through, in the network console, but doing a var_dump on $_GET (on the receiving page) comes up empty.
I've looked at solutions online that include installing a plug-in and also trying to add the variable into query_vars, but neither of these seemed to resolve the issue.
I suspect that there is some redirect happening, in Magento/Apache or Wordpress that is stripping off the GET parameters.
Thoughts/solutions?

A: Found the issue:
IndexController.php was modified and it was not forwarding the POST/GET variables.
I was able to modify the code to forward the variables and the issue has been resolved.


text:
Q: Is it possible to have auto margins when you have position:absolute? I'm having an issue where a div is not butting up to the very top of the page.  I tried to solve this by adding
position:absolute;
top:0px;

which put it at the top like I wanted but it also went to the left of the page.  I want it to be centered in the page which works if I use auto left and right margins without position:absolute.
Is there any way to have auto margins AND position it at the very top of the page?

A: I think you have to set left and right (or maybe only left) to 50%
left:50%;
right:50%;

A: Not an answer to your question, but this sounds like a hacky solution. Don't use position: absolute to solve spacing issues - it has too many other consequences, some of which we can't even see that become apparent on smaller resolutions and such.
Better use Firebug or a similar tool to find out what is causing the space, and fix the reason. It's annoying, but really worth the time.
If you really need to do this, one solution might be to put the position: absolute on a div that spans across the whole screen (width: 100%) and put the real div in there - presumably with the correct margins. (I can't build a test case right now so I can't guarantee 100% that this will work.)

A: position: absolute takes elements out of the normal flow calculations, so I'm not sure whether or not you can have auto-margins.
Either way, it's generally a bad idea for something like that. My advice is to look into why it's not butting up against the top of the page with normal positioning instead.
I never get that problem because the first thing I do in all of my stylesheets is reset all margins and padding to zero and then redefine them explicitly.
In your case, this might be enough:
html, body {
  margin-top: 0;
  padding-top: 0;
}


text:
Q: Python libreries for chatbot and installation procedures I'm doing my first project in python and not familiar with python. I'm using visual studio code version 1.38.1 and python version 3.7.3. And using flask framework. I need to create a chatbot. So which are the libreries I have to use and how to install those libreries

A: you need nltk library (natural language toolkit ) , scikit-learn , random and string .
as a beginner i recommend this guide that can help you create your first chatbot from scratch
to install libraries just you can use pip3
pip3 install nltk sklearn

A: Regarding what types of libraries you want to use depends on how you want your chatbot to work. Google out that first. Regarding installing you can use pip to install any library/framework you want. Example: pip install library-name


text:
Q: PySpark sql dataframe pandas UDF - java.lang.IllegalArgumentException: requirement failed: Decimal precision 8 exceeds max precision 7 I am using Databricks 4.3 (includes Apache Spark 2.3.1, Scala 2.11), Python version 3.5.
I have a Spark data frame df_spark and I ran pandas grouped UDF on it to get a new Spark data frame df_spark2, which only have one column of string type.
When I shows the head of the df_spark2, I got error:
org.apache.spark.SparkException: Job aborted due to stage failure: Task 18 in stage 12.0 failed 4 times, most recent failure: Lost task 18.3 in stage 12.0 (TID 1973, 10.96.133.5, executor 0): java.lang.IllegalArgumentException: requirement failed: Decimal" precision 8 exceeds max precision 7

I tested the pandas grouped by UDF on a pandas data frame and it works well. The codes are:
sample = df[df.acct_id==10030255388]
reformat.func(sample)

Also I can successfully show the schema of the df_spark2
df_spark_2.schema

I got : StructType(List(StructField(Donation,StringType,true)))
below is my codes
df_spark = spark.createDataFrame(df)

from pyspark.sql.functions import pandas_udf, PandasUDFType
@pandas_udf('''Donation string''', PandasUDFType.GROUPED_MAP)  # first parameter is the schema of the output dataframe
def reformat(df):
  Donation = df[['amount','charges','organization','rowColor']].to_json(orient='records')
  temp_dict = {}
  temp_dict[df.acct_id.unique().item()] = Donation
  temp_df = pd.DataFrame.from_dict(data = temp_dict, orient='index', columns=['Donation'])
  return(temp_df)

df_spark_2 = df_spark.groupby("acct_id").apply(reformat)
#I got the messages: df_spark_2:pyspark.sql.dataframe.DataFrame = [Donation: string]

df_spark_2.head()
#here is where I got error messages.

below is the details of my error messages
---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
<command-2141407> in <module>()
----> 1 df_spark_2.head()

/databricks/spark/python/pyspark/sql/dataframe.py in head(self, n)
   1193         """
   1194         if n is None:
-> 1195             rs = self.head(1)
   1196             return rs[0] if rs else None
   1197         return self.take(n)

/databricks/spark/python/pyspark/sql/dataframe.py in head(self, n)
   1195             rs = self.head(1)
   1196             return rs[0] if rs else None
-> 1197         return self.take(n)
   1198
   1199     @ignore_unicode_prefix

/databricks/spark/python/pyspark/sql/dataframe.py in take(self, num)
    520         [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]
    521         """
--> 522         return self.limit(num).collect()
    523
    524     @since(1.3)

/databricks/spark/python/pyspark/sql/dataframe.py in collect(self)
    479         # Default path used in OSS Spark / for non-DF-ACL clusters:
    480         with SCCallSiteSync(self._sc) as css:
--> 481             sock_info = self._jdf.collectToPython()
    482         return list(_load_from_socket(sock_info, BatchedSerializer(PickleSerializer())))
    483

/databricks/spark/python/lib/py4j-0.10.7-src.zip/py4j/java_gateway.py in __call__(self, *args)
   1255         answer = self.gateway_client.send_command(command)
   1256         return_value = get_return_value(
-> 1257             answer, self.gateway_client, self.target_id, self.name)
   1258
   1259         for temp_arg in temp_args:

/databricks/spark/python/pyspark/sql/utils.py in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

/databricks/spark/python/lib/py4j-0.10.7-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
--> 328                     format(target_id, ".", name), value)
    329             else:
    330                 raise Py4JError(

Py4JJavaError: An error occurred while calling o332.collectToPython.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 44 in stage 3.0 failed 4 times, most recent failure: Lost task 44.3 in stage 3.0 (TID 329, 10.96.134.14, executor 1): java.lang.IllegalArgumentException: requirement failed: Decimal precision 8 exceeds max precision 7
    at scala.Predef$.require(Predef.scala:224)
    at org.apache.spark.sql.types.Decimal.set(Decimal.scala:114)
    at org.apache.spark.sql.types.Decimal$.apply(Decimal.scala:453)
    at org.apache.spark.sql.types.Decimal.apply(Decimal.scala)
    at org.apache.spark.sql.vectorized.ArrowColumnVector$DecimalAccessor.getDecimal(ArrowColumnVector.java:360)
    at org.apache.spark.sql.vectorized.ArrowColumnVector.getDecimal(ArrowColumnVector.java:105)
    at org.apache.spark.sql.execution.vectorized.MutableColumnarRow.getDecimal(MutableColumnarRow.java:130)

/databricks/spark/python/lib/py4j-0.10.7-src.zip/py4j/java_gateway.py in __call__(self, *args)
   1255         answer = self.gateway_client.send_command(command)
   1256         return_value = get_return_value(
-> 1257             answer, self.gateway_client, self.target_id, self.name)
   1258
   1259         for temp_arg in temp_args:

/databricks/spark/python/pyspark/sql/utils.py in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

/databricks/spark/python/lib/py4j-0.10.7-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
--> 328                     format(target_id, ".", name), value)
    329             else:
    330                 raise Py4JError(

Py4JJavaError: An error occurred while calling o332.collectToPython.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 44 in stage 3.0 failed 4 times, most recent failure: Lost task 44.3 in stage 3.0 (TID 329, 10.96.134.14, executor 1): java.lang.IllegalArgumentException: requirement failed: Decimal precision 8 exceeds max precision 7
    at scala.Predef$.require(Predef.scala:224)
    at org.apache.spark.sql.types.Decimal.set(Decimal.scala:114)
    at org.apache.spark.sql.types.Decimal$.apply(Decimal.scala:453)
    at org.apache.spark.sql.types.Decimal.apply(Decimal.scala)
    at org.apache.spark.sql.vectorized.ArrowColumnVector$DecimalAccessor.getDecimal(ArrowColumnVector.java:360)
    at org.apache.spark.sql.vectorized.ArrowColumnVector.getDecimal(ArrowColumnVector.java:105)
    at org.apache.spark.sql.execution.vectorized.MutableColumnarRow.getDecimal(MutableColumnarRow.java:130)
    at org.apache.spark.sql.execution.collect.Collector$.collect(Collector.scala:64)
    at org.apache.spark.sql.execution.collect.Collector$.collect(Collector.scala:70)
    at org.apache.spark.sql.execution.ResultCacheManager.getOrComputeResult(ResultCacheManager.scala:497)
    at org.apache.spark.sql.execution.CollectLimitExec.executeCollectResult(limit.scala:48)
    at org.apache.spark.sql.Dataset$$anonfun$collectToPython$1.apply(Dataset.scala:3236)
    at org.apache.spark.sql.Dataset$$anonfun$collectToPython$1.apply(Dataset.scala:3234)
    at org.apache.spark.sql.Dataset$$anonfun$53.apply(Dataset.scala:3334)
    at org.apache.spark.sql.execution.SQLExecution$$anonfun$withCustomExecutionEnv$1.apply(SQLExecution.scala:89)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:175)
    at org.apache.spark.sql.execution.SQLExecution$.withCustomExecutionEnv(SQLExecution.scala:84)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:126)
    at org.apache.spark.sql.Dataset.withAction(Dataset.scala:3333)
    at org.apache.spark.sql.Dataset.collectToPython(Dataset.scala:3234)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:380)
    at py4j.Gateway.invoke(Gateway.java:295)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:251)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalArgumentException: requirement failed: Decimal precision 8 exceeds max precision 7
    at scala.Predef$.require(Predef.scala:224)
    at org.apache.spark.sql.types.Decimal.set(Decimal.scala:114)
    at org.apache.spark.sql.types.Decimal$.apply(Decimal.scala:453)
    at org.apache.spark.sql.types.Decimal.apply(Decimal.scala)
    at org.apache.spark.sql.vectorized.ArrowColumnVector$DecimalAccessor.getDecimal(ArrowColumnVector.java:360)
    at org.apache.spark.sql.vectorized.ArrowColumnVector.getDecimal(ArrowColumnVector.java:105)
    at org.apache.spark.sql.execution.vectorized.MutableColumnarRow.getDecimal(MutableColumnarRow.java:130)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage1.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$10$$anon$1.hasNext(WholeStageCodegenExec.scala:620)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408)
    at org.apache.spark.shuffle.sort.BypassMergeSortShuffleWriter.write(BypassMergeSortShuffleWriter.java:148)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:96)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:53)
    at org.apache.spark.scheduler.Task.run(Task.scala:112)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:384)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    ... 1 more

A: I think the error started from where you triggered df_spark_2.count().collect().
If you just want to take the count of dataframe, just use count() -
df_spark_2.count()

A simple explanation of both function is below.

count() - Returns the number of rows in this DataFrame.
Collect() - Return all the elements of the dataset as an array at the
driver program. This is usually useful after a filter or other
operation that returns a sufficiently small subset of the data.


text:
Q: Split multiple CSV cell values from multiple columns using Ruby I'm trying to split multiple values in a CSV cell. I can do it right if the multiple values in a cell is found in a single column only, but I'm having difficulty doing it if the multiple values are found in multiple columns. Any guidance will be appreciated.
Here's the sample of the data I'm trying to split:
| Column A              | Column B               |
|Value1, Value2, Value3 | Value3, Value4, Value5 |
|Value6                 | Value7, Value8         |

I'm aiming to have a result like this:
| Column A | Column B |
| Value1   | Value3   |
| Value2   | Value4   |
| Value3   | Value5   |
| Value6   | Value7   |
| Value6   | Value8   |

Here's my code:
require 'csv'

split_a = []
split_b = []

def split_values(value)
  value = value.to_s
  value = value.gsub('/', ',').gsub('|', ',').gsub(' ', ',')
  return value.split(',').map(&:strip)
end

source_csv = kendo_shipment = CSV.read('source_file.csv', headers: true, header_converters: :symbol, liberal_parsing: true).map(&:to_h)

source_csv.each do |source_csv|
  column_a = source_csv[:column_a]
  column_b = source_csv[:column_b]
  column_a = split_values(column_a)
  column_a.each do |column_a|
    next if column_a.nil? || column_a.empty?

    split_a << [
      column_a: column_a,
      column_b: column_b
    ]
  end
end

split_a.each do |key, split_a|
  column_a = key[:column_a]
  column_b = key[:column_b]
  column_b = split_values(column_b)
  column_b.each do |column_b|
    next if column_b.nil? || column_b.empty?

    split_b << [
      column_a,
      column_b
    ]
  end
end

A: Here is the code:
require 'csv'

source_csv = CSV.read('source_file.csv',
  col_sep: '|',
  headers: true,
  header_converters: lambda {|h| h.strip},
  liberal_parsing: true
)
COLUMN_NAMES = ['Column A', 'Column B']

# Column values
columns = COLUMN_NAMES.map do |col_name|
  source_csv&.map do |row|
    row[col_name]&.split(',')&.map(&:strip)
  end&.flatten(1) || []
end

# repeat the last value in case the number of values in the columns differs:
vals_last_id = columns.map {|col| col.count}.max - 1
columns.each do |col|
  # replace `col.last` with `nil` on the next line if you want to leave the value blank
  col.fill(col.last, col.length..vals_last_id) if col.length <= vals_last_id
end

values = columns[0].zip(*columns[1..-1])
# result:
pp values; 1
# [["Value1", "Value3"],
#  ["Value2", "Value4"],
#  ["Value3", "Value5"],
#  ["Value6", "Value7"],
#  ["Value6", "Value8"]]

Generate CSV text, with | (pipe) delimiter instead comma:
csv = CSV.new( '',
  col_sep: '|',
  headers: COLUMN_NAMES,
  write_headers: true
);
values.each {|row| csv << row};
puts csv.string
# Column A|Column B
# Value1|Value3
# Value2|Value4
# Value3|Value5
# Value6|Value7
# Value6|Value8

Formatted output:
col_val = [COLUMN_NAMES] + values
col_widths = (0..(COLUMN_NAMES.count - 1)).map do |col_id|
  col_val.map {|row| row[col_id]&.length || 0}.max
end
fmt = "|" + col_widths.map {|w| " %-#{w}s "}.join('|') + "|\n"
col_val.each {|row| printf fmt % row}; 1
# | Column A | Column B |
# | Value1   | Value3   |
# | Value2   | Value4   |
# | Value3   | Value5   |
# | Value6   | Value7   |
# | Value6   | Value8   |

A: There is a special option to define a column separator col_sep: '|' it simplifies the code.
require 'csv'

source_csv = CSV.read('source_file.csv', col_sep: '|', headers: true, header_converters: :symbol, liberal_parsing: true)

split_a = []
split_b = []

# I just assign values to separate arrays, because I am not sure what kind of data structure you want to get at the end.
source_csv.each do |row|
  split_a += row[:column_a].split(',').map(&:strip)
  split_b += row[:column_b].split(',').map(&:strip)
end

# The result
split_a
# => ["Value1", "Value2", "Value3", "Value6"]

split_b
# => ["Value3", "Value4", "Value5", "Value7", "Value8"]

A: As you want the output to be a CSV file I would suggest that it look like:
Column A|Column B
Value1|Value3
Value2|Value4
Value3|Value5
Value6|Value7
Value6|Value8

rather than
| Column A | Column B |
| Value1   | Value3   |
| Value2   | Value4   |
| Value3   | Value5   |
| Value6   | Value7   |
| Value6   | Value8   |

Enclosing each line with column separators and adding unnecessary spaces makes it unnecessarily difficult to extract the text of interest from the file.

Let's begin by creating the file you are given, though I have modified your example to make it easier to follow what is happening.
str=<<~_
| Column A   | Column B   |
| A1, A2, A3 | B1, B2, B3 |
| A4         | B4, B5     |
_

IN_NAME = 'in.csv'
OUT_NAME = 'out.csv'

File.write(IN_NAME, str)
  #=> 84

See IO::write1.

As the structure of this file resembles a CSV file only vaguely, I think it's easiest to read it using ordinary file I/O methods.
header, *body = IO.foreach(IN_NAME, chomp: true).with_object([]) do |line,arr|
  arr << line.gsub(/^\| *| *\|$/, '')
             .split(/ *\| */)
             .flat_map { |s| s.split(/, +/) }
end

(I provide an explanation of this calculation later.) This results in the following:
header
  #=> ["Column A", "Column B"]
body
  #=> [["A1", "A2", "A3", "B1", "B2", "B3"], ["A4", "B4", "B5"]]

See IO::foreach, Enumerator#with_object and Enumerable#flat_map. Note that foreach without a block returns an enumerator that I have chained to with_object.

At this point it is convenient to compute the number of rows to be written to the output file after the header row.
mx = body.map(&:size).max
  #=> 6

Next we need to modify body to make it suitable for writing the output CSV file.
mod_body = Array.new(body.size) do |i|
  Array.new(mx) { |j| body[i][j] || body[i].last }
end.transpose
  #=> [["A1", "A4"], ["A2", "B4"], ["A3", "B5"], ["B1", "B5"],
  #    ["B2", "B5"], ["B3", "B5"]]

See Array::new.
It is now a simple matter to write the output CSV file.
require 'csv'

CSV.open(OUT_NAME, "wb", col_sep: '|', headers: header, write_headers: true) do |csv|
  mod_body.each { |a| csv << a }
end

See CSV::open.
Lastly, let's look at the file that was written.
puts File.read(OUT_NAME)

diplays
Column A|Column B
A1|A4
A2|B4
A3|B5
B1|B5
B2|B5
B3|B5

See IO::read1.

To explain the calculations made in
header, *body = IO.foreach(IN_NAME, chomp: true).with_object([]) do |line,arr|
  arr << line.gsub(/^\| *| *\|$/, '')
             .split(/ *\| */)
             .flat_map { |s| s.split(/, +/) }
end

it is easiest to run it with some puts statements inserted.
header, *body = IO.foreach(IN_NAME, chomp: true).with_object([]) do |line,arr|
  puts "line = #{line}"
  puts "arr = #{arr}"
  arr << line.gsub(/^\| *| *\|$/, '')
             .tap { |l| puts "  line after gsub = #{l}" }
             .split(/ *\| */)
             .tap { |a| puts "  array after split = #{a}" }
             .flat_map { |s| s.split(/, +/) }
             .tap { |a| puts "  array after flat_map = #{a}" }
end
  #=> [["Column A", "Column B"], ["A1", "A2", "A3", "B1", "B2", "B3"],
  #    ["A4", "B4", "B5"]]

The following is displayed.
line = | Column A   | Column B   |
arr = []
  line after gsub = Column A   | Column B
  array after split = ["Column A", "Column B"]
  array after flat_map = ["Column A", "Column B"]
line = | A1, A2, A3 | B1, B2, B3 |
arr = [["Column A", "Column B"]]
  line after gsub = A1, A2, A3 | B1, B2, B3
  array after split = ["A1, A2, A3", "B1, B2, B3"]
  array after flat_map = ["A1", "A2", "A3", "B1", "B2", "B3"]
line = | A4         | B4, B5     |
arr = [["Column A", "Column B"], ["A1", "A2", "A3", "B1", "B2", "B3"]]
  line after gsub = A4         | B4, B5
  array after split = ["A4", "B4, B5"]
  array after flat_map = ["A4", "B4", "B5"]

1. IO methods are commonly invoked on File. That is permissible since File.superclass #=> IO.


text:
Q: why the multi line text field got strike through in alert mail of sharepoint I have created an alert on a sharepoint custom list as immediate alert.when i modify the field of multiple line of text then in alert email i get the both previous as well as the current  item value strikethrough .
can some one help me out why this is happening?
the alert works fine for the single line of text field.

A: Steps to resolve the issue :

*

*Go to alerttemplate.xml file located at "C:\Program Files\Common
Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\XML\"

*Keep the copy of alerttemplate.xml for backup.

*Edit original alerttemplate.xml file.

*Depending on your listtype make the limit length 1000. (if list is custom list edit the line under GenericList and so on)
<Limit Len="1000" AutoHyperLinkNoEncoding="TRUE" MoreText="...">
       <GetVar Name="OldValue#{Field}" />
 </Limit>

*iisreset
Shukraj Khadse
L&T Infotech | Vashi, Navi Mumbai | India


text:
Q: How to write to Z drive by using fopen()? I have mentioned the below code.
  $commandFile = "contains the some big string";
  if($fp = fopen("file:///Z:/testName.txt","w+"))
  {
    fwrite($fp,$commandFile);
    fclose($fp);
  }

Z drive has the user credentials i.e (username:network,Pass:network). Z drive is mapped to my computer. How to write this file to Z drive?
Thanks in advance.

A: If this Z is regular drive on machine running the script, then plain:
fopen('Z:/testName.txt',"w+")

should be sufficient.


text:
Q: How to read bytes from a file, whereas the result byte[] is exactly as long I want the result byte[] to be exactly as long as the file content. How to achieve that.
I am thinking of ArrayList<Byte>, but it doe not seem to be efficient.

A: Personally I'd go the Guava route:
File f = ...
byte[] content = Files.toByteArray(f);

Apache Commons IO has similar utility methods if you want.
If that's not what you want, it's not too hard to write that code yourself:
public static byte[] toByteArray(File f) throws IOException {
    if (f.length() > Integer.MAX_VALUE) {
        throw new IllegalArgumentException(f + " is too large!");
    }
    int length = (int) f.length();
    byte[] content = new byte[length];
    int off = 0;
    int read = 0;
    InputStream in = new FileInputStream(f);
    try {
        while (read != -1 && off < length) {
            read = in.read(content, off, (length - off));
            off += read;
        }
        if (off != length) {
            // file size has shrunken since check, handle appropriately
        } else if (in.read() != -1) {
            // file size has grown since check, handle appropriately
        }
        return content;
    } finally {
        in.close();
    }
}

A: I'm pretty sure File#length() doesn't iterate through the file. (Assuming this is what you meant by length()) Each OS provides efficient enough mechanisms to find file size without reading it all.

A: Allocate an adequate buffer (if necessary, resize it while reading) and keep track of how many bytes read. After finishing reading, create a new array with the exact length and copy the content of the reading buffer.

A: Small function that you can use :

// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

    // Get the size of the file
    long length = file.length();

    // You cannot create an array using a long type.
    // It needs to be an int type.
    // Before converting to an int type, check
    // to ensure that file is not larger than Integer.MAX_VALUE.
    if (length > Integer.MAX_VALUE) {
        throw new RuntimeException(file.getName() + " is too large");
    }

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
           && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
        offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
        throw new IOException("Could not completely read file "+file.getName());
    }

    // Close the input stream and return bytes
    is.close();
    return bytes;
}


text:
Q: One big call vs. multiple smaller TSQL calls I have a ADO.NET/TSQL performance question. We have two options in our application:
1) One big database call with multiple result sets, then in code step through each result set and populate my objects. This results in one round trip to the database.
2) Multiple small database calls.
There is much more code reuse with Option 2 which is an advantage of that option. But I would like to get some input on what the performance cost is. Are two small round trips twice as slow as one big round trip to the database, or is it just a small, say 10% performance loss? We are using C# 3.5 and Sql Server 2008 with stored procedures and ADO.NET.

A: I would think it in part would depend on when you need the data. For instance if you return ten datasets in one large process, and see all ten on the screen at once, then go for it. But if you return ten datasets and the user may only click through the pages to see three of them then sending the others was a waste of server and network resources. If you return ten datasets but the user really needs to see sets seven and eight only after making changes to sets 5 and 6, then the user would see the wrong info if you returned it too soon.
If you use separate stored procs for each data set called in one master stored proc, there is no reason at all why you can't reuse the code elsewhere, so code reuse is not really  an issue in my mind.

A: It sounds a wee bit obvious, but only send what you need in one call.
For example, we have a "getStuff" stored proc for presentation. The "updateStuff" proc calls "getStuff" proc and the client wrapper method for "updateStuff" expects type "Thing". So one round trip.
Chatty servers are one thing you prevent up front with minimal effort. Then, you can tune the DB or client code as needed... but it's hard to factor out the roundtrips later no matter how fast your code runs. In the extreme, what if your web server is in a different country to your DB server...?
Edit: it's interesting to note the SQL guys (HLGEM, astander, me) saying "one trip" and the client guys saying "multiple, code reuse"...

A: I am struggling with this problem myself. And I don't have an answer yet, but I do have some thoughts.
Having reviewed the answers given by others to this point, there is still a third option.
In my appllication, around ten or twelve calls are made to the server to get the data I need. Some of the datafields are varchar max and varbinary max fields (pictures, large documents, videos and sound files). All of my calls are synchronous - i.e., while the data is being requested, the user (and the client side program) has no choice but to wait. He may only want to read or view the data which only makes total sense when it is ALL there, not just partially there. The process, I believe, is slower this way and I am in the process of developing an alternative approach which is based on asynchronous calls to the server from a DLL libaray which raises events to the client to announce the progress to the client. The client is programmed to handle the DLL events and set a variable on the client side indicating chich calls have been completed. The client program can then do what it must do to prepare the data received in call #1 while the DLL is proceeding asynchronously to get the data of call #2. When the client is ready to process the data of call #2, it must check the status and wait to proceed if necessary (I am hoping this will be a short or no wait at all). In this manner, both server and client side software are getting the job done in a more efficient manner.

A: If you're that concerned with performance, try a test of both and see which performs better.
Personally, I prefer the second method. It makes life easier for the developers, makes code more re-usable, and modularizes things so changes down the road are easier.

A: I personally like option two for the reason you stated: code reuse
But consider this: for small requests the latency might be longer than what you do with the request.  You have to find that right balance.

A: As the ADO.Net developer, your job is to make the code as correct, clear, and maintainable as possible. This means that you must separate your concerns.
It's the job of the SQL Server connection technology to make it fast.
If you implement a correct, clear, maintainable application that solves the business problems, and it turns out that the database access is the major bottleneck that prevents the system from operating within acceptable limits, then, and only then, should you start persuing ways to fix the problem. This may or may not include consolidating database queries.

A: Personally I would go with 1 larger round trip.
This will definately be influenced by the exact reusability of the calling code, and how it might be refactored.
But as mentioned, this will depend on your exact situation, where maintainability vs performance could be a factor.

A: Don't optimize for performance until a need arisess to do so. This means that you should analyze your anticipated use patterns and determine what the typical frequency of use for this process will be, and what user interface latency will result from the present design.  If the user will receive feedback from the app is less than a few (2-3) seconds, and the application load from this process is not an inordinate load on server capacity, then don't worry about it.  If otoh the user is waiting an unacceptable amount of time for a response (subjectve but definitiely measurable) or if the server is being overloaded, then it's time to begin optimization.  And then, which optimization techniques will make the most sense, or be the most cost effective, depend on what your analysis of the issue tells you.
So, in the meantime, focus on maintainability.  That means, in your case, code reuse


text:
Q: Replace keys with values and write in a new file Python I've got a problem trying to replace keys (dictionary) that I have in a file, with its corresponding values. More details: an input file called event_from_picks looks like:
EVENT2593
EVENT2594
EVENT2595

EVENT41025
EVENT2646
EVENT2649

Also, my dictionary, created by reloc_event_coords_dic() looks like:
{'EVENT23595': ['36.9828   -34.0538   138.1554'], 'EVENT2594': ['41.2669   -33.0179   139.2269'], 'EVENT2595': ['4.7500   -32.7926   138.1523'], 'EVENT41025': ['16.2453   -32.9552   138.2604'], 'EVENT2646': ['5.5949   -32.4923   138.1866'], 'EVENT2649': ['7.9533   -31.8304   138.6966']}

What I'd like to end up with, is a new file with the values instead of the keys. In this case, a new file called receiver.in which will look like:
36.9828   -34.0538   138.1554
41.2669   -33.0179   139.2269
4.7500   -32.7926   138.1523
16.2453   -32.9552   138.2604
5.5949   -32.4923   138.1866
7.9533   -31.8304   138.6966

My wrong function (I know I must have a problem with loops but I can't figure out what) so far is:
def converted_lines ():
    file_out = open ('receiver.in', 'w')
    converted_lines = []
    event_dict = reloc_event_coords_dic()
    data_line = event_dict.items() # Takes data as('EVENT31933', ['10.1230 -32.8294 138.1718'])
    for element in data_line:
        for item in element:
            event_number = element[0] # Gets event number
            coord_line = event_dict.get (event_number, None)
    with open ('event_from_picks', 'r') as file_in:
        for line in file_in:
            if line.startswith("  "):
                continue
            if event_number:
                converted_lines.append ("%s" % coord_line)
        file_out.writelines(converted_lines)

Thanks for reading!

A: just do the following:
with open('receiver.in', 'w') as f:
    f.writelines([v[0] for v in reloc_event_coords_dic().itervalues()])

A: Your first loop just leaves the last pair in the coord_line variable.
Better do
event_dict = reloc_event_coords_dic()
with open ('event_from_picks', 'r') as file_in:
    with open('receiver.in', 'w') as file_out:
        for in_line in file_in:
            file_out.writelines(event_dict[in_line.strip()])

(untested, but you should get the logic).


text:
Q: C++ How to write a code that counts top words while removing any special characters from text file How do I take a text file from the command line that opens and reads it, and then count the top words in that file but also removes any special characters. I have this code done here and used maps but it isn't counting every word. For instance "hello." is one word and also "$#%hello<>?/". I have this file from the song shake it off that's supposed to read shake 78 times but I only counted 26 in this code.
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>

using namespace std;

string ask(const string& msg) {
  string ans;
  cout << msg;
  getline(cin, ans);
  return ans;
}
int main() {

  ifstream fin( ask("Enter file name: ").c_str() ) ;
  if (fin.fail()) {
    cerr << "ERROR"; // this is if the file fails to open
    return 1;
  }
  map<string, int> wordCount;
  string entity;
  while (fin >> entity) {
    vector<string> words;

for (int i = 0, a = 0; i < entity.length(); i++) {
  char& c = entity[i];
  if (c < 'A' || (c > 'Z' && c < 'a') || c > 'z') {
    string word = entity.substr(a, i - a);
    a = i + 1;
    if (word.length() > 0)
      words.push_back(word);
  }
}
for (auto & word : words)
  wordCount[word]++;

}
fin.close();

vector<string> topWords;
const size_t MAX_WORDS = 10;
for ( auto iter = wordCount.begin(); iter != wordCount.end(); iter ++ ) {

int som = 0, lim = topWords.size();
while (som < lim) {
  int i = ( som + lim ) / 2;
  int count = wordCount[topWords[i]];
  if ( iter -> second > count)
    lim = i;
  else if ( iter -> second < count )
    som = i + 1;
  else
    som = lim = i;

}
if (som < MAX_WORDS ) {
  topWords.insert( topWords.begin() + som, iter -> first );
  if ( topWords.size() > MAX_WORDS )
    topWords.pop_back();
}
}
for (auto & topWord : topWords)
  cout << "(" << wordCount[topWord] << ")\t" << topWord << endl;

return 0;

}

One last thing if yall can probably help me on is how would I also write a code that takes a number from the command line alongside the filename and with that number, display the number of top words corresponding with that number passed in the command line, I would assume there is a parse args involved maybe.
Thank you again!
https://s3.amazonaws.com/mimirplatform.production/files/48a9fa64-cddc-4e45-817f-3e16bd7772c2/shake_it_off.txt
!hi!
@hi@
#hi#
$hi$
%hi%
^hi^
&hi&
*hi*
(hi(
)hi)
_hi_
-hi-
+hi+
=hi=
~hi~
`hi`
:hi:
;hi;
'hi'
"hi"
<hi<
>hi>
/hi/
?hi?
{hi{
}hi}
[hi[
]hi]
|hi|
\hi\

bob bob bob bob bob bob bob !@#@$$%#&@^*()@*#)_++(#<><#:":bob@#@$$%#&@^*()@*#)_++(#<><#:":
!@#@$$%#&@^*()@*#)_++(#<><#:":bob@#@$$%#&@^*()@*#)_++(#<><#:":  !@#@$$%#&@^*()@*#)_++(#<><#:":bob@#@$$%#&@^*()@*#)_++(#<><#:":
!@#@$$%#&@^*()@*#)_++(#<><#:":bob@#@$$%#&@^*()@*#)_++(#<><#:": !@#@$$%#&@^*()@*#)_++(#<><#:":bob@#@$$%#&@^*()@*#)_++(#<><#:

this is the special character test

A: Your original code is somewhat hard to refine, I have followed your description to get a program that uses STL.

*

*Combine erase with remove_if to remove unwanted chars

*Use set to resort by counts

If you have some experience with Boost, it's a use case with multimap or bimap, which can make the code even more cleaner.
#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>

using namespace std;

string ask(const string& msg) {
  string ans;
  cout << msg;
  getline(cin, ans);
  return ans;
}
int main() {
  // ifstream fin(ask("Enter file name: ").c_str());
  ifstream fin("shake_it_off.txt");
  if (fin.fail()) {
    cerr << "ERROR";  // this is if the file fails to open
    return 1;
  }
  map<string, size_t> wordCount;
  string entity;

  while (fin >> entity) {
    entity.erase(std::remove_if(entity.begin(), entity.end(),
                                [](char ch) { return !isalpha(ch); }),
                 entity.end());
    wordCount[entity] += 1;
  }

  auto cmp = [](const std::pair<std::string, size_t>& lhs,
                const std::pair<std::string, size_t>& rhs) {
    return lhs.second > rhs.second;
  };
  std::multiset<std::pair<std::string, size_t>, decltype(cmp)> top(
      wordCount.begin(), wordCount.end(), cmp);
  auto it = top.begin();
  const size_t MAX_WORDS = 10;
  for (size_t i = 0; i < MAX_WORDS && it != top.end(); ++i, ++it) {
    cout << "(" << it->first << ")\t" << it->second << endl;
  }

  return 0;
}


text:
Q: Assistance with WinNT MPM MaxRequestsPerChild In our httpd-mpm.conf file, we have this section active:
# WinNT MPM
# ThreadsPerChild: constant number of worker threads in the server process
# MaxRequestsPerChild: maximum  number of requests a server process serves
<IfModule mpm_winnt_module>
    ThreadsPerChild       128
    MaxRequestsPerChild  1024
</IfModule>

MaxRequestsPerChild was originally 0, meaning no limit, but we were getting hard memory allocation errors, so as per Apache documentation, we put a finite limit on this value. We're running /server-status to monitor, but I can't seem to correlate this value with anything that's showing up. Would like to confirm that the change is working, and whether it should be increased or decreased.
Excerpt from /server-status:

Srv
PID
Acc
M
SS
Req
Conn
Child
Slot
Client
VHost
Request

0-36
59996
0/300/2456
_
35
265
0.0
0.42
1.33
wks315.acme.local
www.acme.com
NULL

0-36
59996
2/180/2166
W
0
0
0.0
0.00
0.54
161.216.164.20
www.acme.com
POST /loadMenu HTTP/1.1

0-36
59996
0/281/2426
_
23
296
0.0
0.00
1.11
184.151.190.107
www.acme.com
NULL

0-36
59996
0/9/1867
_
15
390
0.0
0.00
1.40
192.168.5.41
www.acme.com
NULL

0-36
59996
0/304/2294
_
59
218
0.0
0.05
0.12
192.168.5.231
www.acme.com
NULL

0-36
59996
4/274/2489
C
0
249
0.0
0.07
0.90
wks342
www.acme.com
NULL

Legend:

Column
Description

Srv
Child Server number - generation

PID
OS process ID

Acc
Number of accesses this connection / this child / this slot

M
Mode of operation

SS
Seconds since beginning of most recent request

Req
Milliseconds required to process most recent request

Conn
Kilobytes transferred this connection

Child
Megabytes transferred this child

Slot
Total megabytes transferred this slot

I though at first it might be the last value in Acc "this slot", meaning that if this exceeds 1024, then the worker is restarted, but that's not the case. I've been monitoring the second value "this child", and it seems to peak around 320, never getting close to 1024. So I'm not sure what I should be looking at.


text:
Q: SQL Query using Windowing Functions - Lead and Lag for insert & update output I need a sql query to peform the below operations using Windowing function Lag and Lead.
For each Key, I need to perform the below Insert and update in the final output
Insert Condition:
1. By Default, LAYER_NO=0 , needs to be written in output.
2. If there is any change in the value of COL1,COL2,COL3, with respective to its precious record,then that records needs to be written in output.
Example: key_1 with layer_no=2, there is a change of value from 400 to 600 in COL3
Update Condition:
1. If there were NO changes in the value of COL1,COL2,COL3, with respective to its previous record,but there is a change in "DEPART column", this value needs to be updated in the output.
2.Even the LAYER_NO should be updated sequentially, after inserting the record with layer_no=0
Example: key_1 with layer_no=3, there were NO changes in COL1,COL2,COL3, But there is value change in DEPART column as "xyz" , so this needs to be updated in the output.
select * from input_table;
+-----+--------+----+----+----+------+
|  KEY|LAYER_NO|COL1|COL2|COL3|DEPART|
+-----+--------+----+----+----+------+
|key_1|       0| 200| 300| 400|   abc|->default write
|key_1|       1| 200| 300| 400|   abc|
|key_1|       2| 200| 300| 600|   abc|--->change in col3,so write
|key_1|       2| 200| 300| 600|   abc|
|key_1|       3| 200| 300| 600|   xyz|--->change in col4,so update
|key_2|       0| 500| 700| 900|   prq|->default write
|key_2|       1| 888| 555| 900|   prq|--->change in col1 & col 2,so write
|key_3|       0| 111| 222| 333|   lgh|->default write
|key_3|       1| 084| 222| 333|   lgh|--->change in col1,so write
|key_3|       2| 084| 222| 333|   rrr|--->change in col4,so update
+-----+--------+----+----+----+------+

what will be the SQL query to generate the below output from input_table ?
Expected Output:
+-----+--------+----+----+----+------+
|  KEY|LAYER_NO|COl1|COl2|COl3|DEPART|
+-----+--------+----+----+----+------+
|key_1|       0| 200| 300| 400|   abc|
|key_1|       1| 200| 300| 600|   xyz|
|key_2|       0| 500| 700| 900|   prq|
|key_2|       1| 888| 555| 900|   prq|
|key_3|       0| 111| 222| 333|   lgh|
|key_3|       1| 084| 222| 333|   rrr|
+-----+--------+----+----+----+------+

A: This can be done by first working out the rows that have had their col1, col2 or col3 columns changed, and then by finding the latest depart value for the subsequent rows, like so:
WITH your_table AS (SELECT 'key_1' KEY, 0 layer_no, 200 col1, 300 col2, 400 col3, 'abc' depart FROM dual UNION ALL
                    SELECT 'key_1' KEY, 1 layer_no, 200 col1, 300 col2, 400 col3, 'abc' depart FROM dual UNION ALL
                    SELECT 'key_1' KEY, 2 layer_no, 200 col1, 300 col2, 600 col3, 'abc' depart FROM dual UNION ALL
                    SELECT 'key_1' KEY, 2 layer_no, 200 col1, 300 col2, 600 col3, 'abc' depart FROM dual UNION ALL
                    SELECT 'key_1' KEY, 3 layer_no, 200 col1, 300 col2, 600 col3, 'xyz' depart FROM dual UNION ALL
                    SELECT 'key_2' KEY, 0 layer_no, 500 col1, 700 col2, 900 col3, 'prq' depart FROM dual UNION ALL
                    SELECT 'key_2' KEY, 1 layer_no, 888 col1, 555 col2, 900 col3, 'prq' depart FROM dual UNION ALL
                    SELECT 'key_3' KEY, 0 layer_no, 111 col1, 222 col2, 333 col3, 'lgh' depart FROM dual UNION ALL
                    SELECT 'key_3' KEY, 1 layer_no, 084 col1, 222 col2, 333 col3, 'lgh' depart FROM dual UNION ALL
                    SELECT 'key_3' KEY, 2 layer_no, 084 col1, 222 col2, 333 col3, 'rrr' depart FROM dual),
   changed_rows AS (SELECT KEY,
                           layer_no,
                           col1,
                           col2,
                           col3,
                           depart,
                           CASE WHEN LAG(col1) OVER (PARTITION BY KEY ORDER BY layer_no) = col1
                                     AND LAG(col2) OVER (PARTITION BY KEY ORDER BY layer_no) = col2
                                     AND LAG(col3) OVER (PARTITION BY KEY ORDER BY layer_no) = col3
                                     THEN 0
                                ELSE 1
                           END changed_cols1_to_3
                    FROM   your_table),
    define_grps AS (SELECT KEY,
                           layer_no,
                           col1,
                           col2,
                           col3,
                           depart,
                           changed_cols1_to_3,
                           SUM(changed_cols1_to_3) OVER (PARTITION BY KEY ORDER BY layer_no) grp
                    FROM   changed_rows)
SELECT KEY,
       grp -1 layer_no,
       col2,
       col2,
       col3,
       MAX(depart) KEEP (dense_rank LAST ORDER BY layer_no) depart
FROM   define_grps
GROUP BY KEY,
         col1,
         col2,
         col3,
         grp;

KEY     LAYER_NO       COL2       COL2       COL3 DEPART
----- ---------- ---------- ---------- ---------- ------
key_1          0        300        300        400 abc
key_1          1        300        300        600 xyz
key_2          0        700        700        900 prq
key_2          1        555        555        900 prq
key_3          1        222        222        333 rrr
key_3          0        222        222        333 lgh

The changed_rows subquery checks col1, col2 and col3 to see if it has the same values as the previous row (no change) or not (change). We assign a value of 1 to changed rows and 0 to unchanged rows.
The define_grps subquery works out the running total of the changed_cols1_to_3 column across all the rows per key. This has the effect of grouping each set of consecutive rows where cols 1, 2 and 3 are the same.
Finally, we can pick the last row for each group. The new layer_no is simply the grp number minus 1.


text:
Q: 1and1 Security Exception Issue I have bought a shared windows hosting plan from 1and1. Having uploaded the default Visual Studio "Web Pages" site, I am getting the following error on 1and1. Considering this is a default Microsoft template, I am very surprised to say the least.
I would appreciate any help that anybody is able to provide.
Many Thanks.
'Security Exception
  Description: The application attempted to perform an operation not allowed by the
security policy.  To grant this application the required permission please contact your
system administrator or change the application's trust level in the configuration file.

     Exception Details: System.Security.SecurityException:
Request for the permission of type 'System.Security.Permissions.SecurityPermission,
mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

Source Error:

Line 3:      <head>
Line 4:          <meta charset="utf-8" />
Line 5:          <title>@Page.Title - My ASP.NET Web Page</title>
Line 6:          <link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />
Line 7:          <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />

 Source File:  e:\kunden\homepages\41\d516833426\www\_SiteLayout.cshtml    Line:  5

Stack Trace:

[SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
   System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark) +31
   System.Security.CodeAccessPermission.Demand() +46
   System.Web.HttpContext.System.IServiceProvider.GetService(Type service) +54
   System.Web.HttpContextWrapper.GetService(Type serviceType) +11
   System.Web.WebPages.UrlRewriterHelper.IsUrlRewriterTurnedOn(HttpContextBase httpContext) +108
   System.Web.WebPages.UrlRewriterHelper.WasRequestRewritten(HttpContextBase httpContext) +13
   System.Web.WebPages.UrlUtil.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath) +138
   System.Web.WebPages.UrlUtil.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath) +103
   System.Web.WebPages.UrlUtil.GenerateClientUrl(HttpContextBase httpContext, String basePath, String path, Object[] pathParts) +144
   System.Web.WebPages.WebPageExecutingBase.Href(String path, Object[] pathParts) +44
   ASP._Page__SiteLayout_cshtml.Execute() in e:\kunden\homepages\41\d516833426\www\_SiteLayout.cshtml:5
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +199
   System.Web.WebPages.WebPage.ExecutePageHierarchy(IEnumerable`1 executors) +69
   System.Web.WebPages.WebPage.ExecutePageHierarchy() +131
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +90
   System.Web.WebPages.<>c__DisplayClass7.<RenderPageCore>b__6(TextWriter writer) +233
   System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +10
   System.Web.WebPages.WebPageBase.Write(HelperResult result) +80
   System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +63
   System.Web.WebPages.WebPageBase.PopContext() +267
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +98
   System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal(HttpContextBase httpContext) +171
   System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal(HttpContext context) +66
   System.Web.WebPages.WebPageHttpHandler.ProcessRequest(HttpContext context) +5
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +341
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18055'

A: Your hoster (1and1) forces sites to run in Medium Trust.  Medium Trust is obsolete, and ASP.NET no longer supports it going forward.  See https://stackoverflow.com/a/17218344/59641 and http://support.microsoft.com/kb/2698981 for more information.
You could try convincing 1and1 to run your site in Full Trust.  Otherwise you should consider moving to a new hoster that allows Full Trust.