In Europa Universalis IV, how do I give orders to allied AI armies?

Question: When in war together, my AI allies, colonies and vassals tend to do stupid things such as using their main fleet to blockade a single port, or right-out commanding their army home for tea time, all while my force is slaughtered by enemy stacks of doom.
In situations where huge stacks are required, I often attach to an allied force in the hope that it will do something useful, but most of the time it is in vain. This is giving me a major headache, and I've lost countless wars to it.
So... is there a way to control allied armies and navies, for example by making them attach to my stack?
Internet research hints at the "Attach to this unit?" checkbox, but unfortunately it doesn't have a tooltip, and I haven't managed to get it to work.
I've done some experimentation, and in the most successful case I got an army to follow me for two provinces before abandoning me. In all other cases, I was simply ignored.
Finally, once these basic issues are solved: Is there a way to transport allied troops over an ocean?
Answer: There's really no way to directly order around the AI armies, and you can't order them into any of your transports. The best thing to do is usually just to let them do their thing (save yourself the trouble of sieging the provinces close to your allies or rushing headlong into a doomstack) while you send your guys in to do the bulk of the work, like heading straight for the capital or harassing any new stacks that pop up.
Comment: @Nix OP already knows about it. But it's unreliable because the AI treats it as a suggestion instead of a rule. But it works frequently enough.
Comment: @Nix that's completely wrong... It attaches the AI army to yours brah.
Comment: Unfortunate, as this is a defensive war and the enemy doomstack is heading straight for _my_ capital... what about the "Attach to this unit?" checkbox?
Comment: @mic_e The "attach to this unit" basically joins one of your units to an allied unit, under their command. You surrender the control of the army to them; you cannot control units that are not yours. However, some times, allies choose to join their forces with yours. They will then follow you around untill they get tired of it. Here is an explanation of the feature in Crusader Kings 2, the UI and function is similar. http://gaming.stackexchange.com/questions/122190/can-i-join-my-armies-to-my-lieges-armies/122590#122590
Comment: @Harry That doesn't sound right, dawg. Could you please document it and post as an answer? It's basically what OP needs.
Answer: With the Art of War DLC it is possible to give allied objectives which influence the actions of AI allies and subjects in wars. These are split into two types:

Province objectives are handled from the province screen and allows the player to tell their AI allies to focus on specific enemy
provinces. This will both make them more likely to send armies to
besiege that province and to engage enemy armies that are located in
it.
Subject military focuses are handled from the subjects screen and allow the player to change the military priorities of their subject nations to either aggressive or supportive.

Aggressive subjects will not attach to your armies and will instead
focus on their own operations, engaging enemy armies and besieging
their provinces.
Supportive subjects will behave in the opposite
fashion, attaching to or staying near friendly armies and avoiding
independent operations in enemy territory.
If you have no military
focus set, they will attempt to judge
for themselves when it is best to attach and when it is best to act
independently.


Bad 3d performance of intel ironlake

Question: I'm using ubuntu 13.04 and got VERY bad 3d performance with intel ironlake comparing with a windows installation.
Is there any way I can improve this?
I already tried various paramaters of the i915 kernel module, but that didn't help much...
SNA is already enabled.
Answer: Add the following option in grub file
<code>i915.semaphores=1
</code>
Then
<code> sudo update-grub
</code>
Mine is
<code> GRUB_CMDLINE_LINUX_DEFAULT="quiet splash i915.lvds_downclock=1 drm.vblankoffdelay=1  i915.semaphores=1"
</code>
Try adding this to /etc/environment
<code> CLUTTER_PAINT=disable-clipped-redraws:disable-culling
</code>
[RESOLVED] Poor performance on Ironlake compared to old Intel GPU
Intel Ironlake OpenGL Performance On Mesa 9.1
Answer: Download and install the official graphics drivers for all intel processors. I had some minor problems with some games but this solved that issue.
https://01.org/linuxgraphics/
These drivers are given by Intel Open Source Technology Center and are always updated. Don't forget to add their source in your source list, to always get the updated drivers.

Bad 3d performance of intel ironlake


operator << in c#

Question: i couldn't understand this code in c#
int i=4
int[] s =new int [1<<i];
Console.WriteLine(s.length);

the ouput is 16
i don't know why the output like that?
Answer: bit shift operator
Answer: From documentation

If first operand is an int or uint
  (32-bit quantity), the shift count is
  given by the low-order five bits of
  second operand.
If first operand is a long or ulong
  (64-bit quantity), the shift count is
  given by the low-order six bits of
  second operand.
Note that i<<1 and i<<33 give the same
  result, because 1 and 33 have the same
  low-order five bits.

This will be the same as 2^( the actual value of the lower 5 bits ).
So in your case it would be 2^4=16.
Answer: I'm assuming you mean i in place of r...
<<n means "shift left by n* bits". Since you start with 1=binary 00...00001, if you shift left 4 times you get binary 00...10000 = 16 (it helps if you are familiar with binary arithmetic - otherwise "calc.exe" has a binary converter).
Each bit moves left n places, filling (on the right) with 0s. *=note that n is actually "mod 32" for int, so (as a corner case) 1 << 33 = 2, not 0 which you might expect.
There is also >> (right shift), which moves for the right, filling with 0 for uints and +ve ints, and 1 for -ve ints.
Answer: << is the left shift operator
x << y

means shift x to the left by y bits.
3 is 0011, 3<<1 is 0110 which 6.
It's usually used to multiply by 2 (shifting to the left is multiplying by 2)
Answer: As already mentioned, << is the left shift operator.  In your particular example, the array size is being defined as a power of 2.  The value 1 shifted left by some number is going to be 1, 2, 4, 8, 16, ...

operator << in c#


Is Engi Med-Bot Dispersal affected by MedBay upgrades?

Question: The title pretty much says it all. Do med-bay upgrades make healing in rooms besides the med-bay faster when you have med-bot dispersal?
Answer: There is a developer who has answered that med-bay upgrades do not affect the Engi med-bot dispersal healing speed: source.
I also measured the effect with a fully upgraded and fully powered med-bay. Before any upgrades, it took 10 seconds for a crew member to hit 50% health in front of an open airlock. After all upgrades and med-bay fully powered, it took 10 seconds for a crew member to hit 50% health in front of an open airlock.
Engi Med-Bot Dispersal is not affected by MedBay upgrades.
Comment: Welp, can't argue with the code. Guess I'll switch accepted answers.
Answer: Yes, i've currently got that same setup in my save-game. It does increase the rate although it still seems to be reduced as compared to manning the med-bay.
Comment: +1: This agrees with both my experiences, and my reading of the description. Reduced healing outside the medbay makes sense to me as a proportion of the healing *inside* the me bay.
Answer: I tested this with an Enig and an airlock. With no med bay 50% health took 7.6 seconds, with 1 med bay it took 10.5s, and with 2 med bay it took 10.5s. So as of 2023 extra power to med bay either has no impact, or has a negligible impact.


What's the difference between the Red Dot and Reflex sights?

Question: What's the difference between the Red Dot and Reflex sights in Call of Duty: Black Ops?
Comment: I was *so* ready to find a duplicate on this, but [it's both a different game *and* a different pair of sights](http://gaming.stackexchange.com/questions/8807/difference-between-holographic-and-red-dot-sight "Although it still was a Red Dot, haha~"). Well, hopefully this comment will stop others from engaging in their own similarly futile searches.
Comment: it sounds like you manage your time well.
Answer: Taken from COD Wikia:

The differences between the Reflex Sight and the Red Dot Sight is the Reflex Sight has a slightly larger field of view when looking through the optics.

Personally, I am a bit more comfortable with the reflex sight than with the RDS.Tactically, there is almost no difference.
Comment: lets not forget you can customize your reflex dot to whatever you like. My personal fav is the cyan coloured X.
Answer: From my experience, Reflex Sights produces more "tunnel vision" compared to Red Dot Sights, which reduces your field of vision slightly when aiming down the sight. But as for gameplay mechanics-wise, they function pretty much the same.


React-navigation, createMaterialTopTabNavigator. Problem

Question: picture
My problem is that I don't know were to put "title". I have TabNavigator, with two pages. You can see on the image, which is what I really want to do.
import React from 'react';
import { Text, View,Button } from 'react-native';
import { createMaterialTopTabNavigator } from 'react-navigation';

class HomeScreen extends React.Component {

    render() {

        return (
            <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                <View >
                    <Button
                        title='Click me'
                        onPress={() => this.props.navigation.navigate('HomeScreen')} />
                </View>
            </View>
        );
    }
}

class SettingsScreen extends React.Component {
    render() {
        return (
            <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                <Text>Settings!</Text>
            </View>
        );
    }
}

export default createMaterialTopTabNavigator({
    Test1: { screen: HomeScreen },
    Test2: { screen: SettingsScreen },
});

Answer: One possible solution is to wrap the MaterialTopTabNavigatorinside a StackNavigator and add the title option to it. So your code should looks something similar to this:
import React from 'react';
import { Text, View,Button } from 'react-native';
import { createMaterialTopTabNavigator, createStackNavigator } from 'react-navigation';

class HomeScreen extends React.Component {
  render() {
    return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <View >
            <Button
                title='Click me'
                onPress={() => this.props.navigation.navigate('HomeScreen')} />
          </View>
        </View>
    );
  }
}

class SettingsScreen extends React.Component {
  render() {
    return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <Text>Settings!</Text>
        </View>
    );
  }
}

const App = createMaterialTopTabNavigator({
  Test1: { screen: HomeScreen },
  Test2: { screen: SettingsScreen },
});

export default createStackNavigator({
  app: {
    screen: App,
    navigationOptions: {
      title: 'Screen title',
    },
  },
});

Comment: I guess you already have another navigator as parent. Can you please share more code?
Comment: that is all of the code. but before I use createMaterialTopTabNavigator. I was install react-native-tab-view ( https://github.com/react-native-community/react-native-tab-view )


Generating output on query string

Question: I have an ASP.NET website in which I have to perform a certain operation. I have  to displaying the ID's from the DB on menu.aspx page in this format {1:2:3:4}. The above format is not a problem and can be just be written with
Response.Write("{");
for.. loop(until last ID)
{
Response.Write(query to fetch ID's) + ":";
}
Response.Write("}");

But here comes my question. I have to generate this ID when the user types the query within the URL somewhat like http://localhost/website/menu.aspx?search=yes
Note that I am saying that user will type this URL. I know that query string can pass the values from one form to another but this is a single web form and if I attach this ?search=yes, it should return the result. How can this be done?
This is somewhat similar to searching in Google. For eg: I can type www.google.com/search?Stack and I get the results
Answer: Use the Request.QueryString collection:
foreach(var item in Request.QueryString)
{
       Response.Write(Request.QueryString[item] + ":");
}

//etc.

Comment: Can this made such that the user may type anything after search =(equal to) but it has to generate the same output.
For eg: `http://localhost/website/?search=code`,
`http://localhost/website/?search=example`,
`http://localhost/website/?search=whatever`

All of them should generate the same output.
Answer: The following example will work if there is a querystring parameter named "search" with any value (including blank).
if (Request.QueryString["search"] != null) {

    Response.Write("{");
    for.. loop(until last ID) {
        Response.Write(query to fetch ID's) + ":";
    }
    Response.Write("}");
}

Comment: `string.IsNullOrEmpty` already checks for null, so there is no need for `?? string.Empty`.  It should also just work directly as `if (!string.IsNullOrEmpty(Request["search"])) {`
Comment: Where in the page menu.aspx.cs would I have to put this code?
Comment: Hey! Thanks a lot. In continuation to this, can this made such that the user may type anything after search =(equal to) but it has to generate the same output. For eg: http://localhost/website/?search=code, http://localhost/website/?search=example, http://localhost/website/?search=whatever All of them should generate the same output.
Comment: Yes, I edited the code above so that if there is a url param named 'search' in the URL, it will output that code.
Comment: umm.. I have to change some things so that on this query string `localhost/website/?search=jessegavin` , the jessegvain should be appended to my output i.e jessegavin{1:2:3:4). Similarly for all other values searched through query string should be appended to the output. Can you please help me in this too?

Generating output on query string


Airmon-ng on Termux(Android)

Question: I rooted my Redmi Note 10S to trying to use aircrack-ng, but It don't worked, because my phone's wifi chip isn't compatible with monitor mode.
So I bought a wireless adapter and type-c to usb adapter, and it also didn't worked. The adapter's chip is a MediaTek 6360(It appeared on dmesg when i boot with adapter already connected)
It appears on "termux-usb -l" as "/dev/bus/usb/001/002", i gave permission with "termux-usb -r /dev/bus/usb/001/002", but it also didn't appear on airmon-ng.
idk what to do.
Answer: Late response but what worked for me was installing a custom kernel.
https://www.kali.org/docs/nethunter/building-nethunter/
I didn't have to use the rom only the custom kernel.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Airmon-ng on Termux(Android)


Do I need to be influential with my human teammate to win Tourism Victory?

Question: I'm playing a game with a friend where I'm doing my best to stack tourism. I've noticed that I'm still "exotic" to him and he has a TON of culture. I also cannot generate many tourism bonuses for him because "open borders" does not exist.
Do I have to become influential with my human ally (teammate) to win a culture/tourism victory? (more tourism than his total culture)
I cannot find the information on this anywhere.
Answer: First, I have no idea. But after firing up a test game with me and an AI in a team (with 4 other AI players) the evidence seems to indicate you do need to influence your teammate.
First, the victory screen shows my teammate as one of the 'targets' in the cultural victory progress:

Second, the culture overview screen for victory indicates I'm influential with 0 of 5 other civilisations, implying I need to influence my teammate as there's only 4 other players.

I'm not claiming this is a definitive answer, but until we've some strong evidence (someone winning or not when all players except their teammate are influenced) this is probably the best we've got.
Comment: U are correct it requires influential in all players teammates or not. Typically if one teammate was going culture the other teammate would not
Comment: @Paralytic Doesn't this seem broken though? I mean you can't get open borders bonus from your teammate. My teammate wasn't going for culture, he was going diplomacy but he had more culture than me for  a long time from city-state gifts. He still produces a lot! With a computer civ, i could kill a rival who had a bunch of culture, or do open borders at least. I think there is even some other bonuses that I may not get. Anyway, it doesn't matter too much because diplomatic victory is so easy he'll win long before I do, but I did want to know
Comment: Anyway, I'm marking this as the answer unless someone clearly refutes it. If my friend wins diplo victory we may reload and avoid diplomatic victory and see about the tourism victory just to make sure
Comment: Nah I've won a cultural victory before the modern era
Answer: Yes, you will have to become influential with your human ally. With that influence you will be able to boost tourism between the two of you.


Detect AM/PM vs 24 hr clock preference from Java Locale information?

Question: I am looking for a way to tell in a Java program if a particular locale prefers display of time in 12 hour AM/PM or in 24 hour clock.  Now, normally I would just use DateFormat to properly format the date as appropriate for the Locale.  However, I'm attempting to localize a stem-and-leaf calendar display of transit schedules which requires some direct knowledge of the locale preferences.  You can see an example of a schedule here:
http://onebusaway.org/where/standard/schedule.action?id=1_538
Any ideas on how I can detect 12 hour AM/PM vs 24 hour programmatically?
Answer: You can probe it, like this:
boolean hasAmPmClock(Locale locale) {
        DateFormat stdFormat = DateFormat.getTimeInstance(DateFormat.SHORT,
                Locale.US);
        DateFormat localeFormat = DateFormat.getTimeInstance(DateFormat.LONG,
                locale);
        String midnight = "";
        try {
            midnight = localeFormat.format(stdFormat.parse("12:00 AM"));
        } catch (ParseException ignore) {
        }
        return midnight.contains("12");
}

Answer: I found another way that's a little less roundabout than the accepted answer:
DateFormat format;
// ...
boolean is24Hour;
if (format instanceof SimpleDateFormat) {
    SimpleDateFormat sdf = (SimpleDateFormat)format;
    String pattern = sdf.toPattern();
    is24Hour = !pattern.contains("a");
}

Still pretty gross, and it won't work with other DateFormat concrete types, but the standard ways of getting a DateFormat object seem to return SimpleDateFormat.


Cannot open /dev/vfio/noiommu-0: Operation not permitted

Question: I am trying to open file /dev/vfio/noiommu-0 with read and write access (O_RDWR), but the error occurs.
char* filename = "/dev/vfio/noiommu-0";
int fd = open(filename, O_RDWR);
if (fd < 0)
    printf("Cannot open %s: %s\n", filename, strerror(errno));

The output is Cannot open /dev/vfio/noiommu-0: Operation not permitted
I've changed the permissions of the file to crw-rw-rw- and changed the owner of the file from root to myuser, but it didn't help. Also myuser has permissions to read upper folders.
Could you please explain why I cannot read and write to this file, and how can I overcome these issues?
Comment: Why are you sure the error is " Operation not permitted"? Try to use `perror` or printf the result of `strerror`.  https://www.man7.org/linux/man-pages/man3/strerror.3.html https://www.man7.org/linux/man-pages/man3/perror.3.html
Comment: @SirJoBlack I changed the code and printed `strerror(errno)`, which says "Operation not permitted".
Comment: See https://lwn.net/Articles/660745/ or https://stackoverflow.com/questions/65274122/running-dpdk-c-program-without-root-privileges
Comment: Did you tested the code as root!?
Comment: If it doesn't work as root (also if it works as root)  it might be most likely a kernel configuration problem
Comment: @SirJoBlack the code works if I run it as root, but the problem is  that I want to run it without root privileges. However, the article that you've sent [https://lwn.net/Articles/660745/](https://lwn.net/Articles/660745/) suggests setting `CAP_SYS_RAWIO` capabilities, and it solved the problem. Thanks!
Answer: Setting CAP_SYS_RAWIO capabilities solved the issue (source).
Answer: The man page for open() lists the following reasons why a call to open() may return -1:
ERRORS
       open(), openat(), and creat() can fail with the following errors:

       EACCES The requested access to the file is not allowed, or search
              permission is denied for one of the directories in the
              path prefix of pathname, or the file did not exist yet and
              write access to the parent directory is not allowed.  (See
              also path_resolution(7).)

       EACCES Where O_CREAT is specified, the protected_fifos or
              protected_regular sysctl is enabled, the file already
              exists and is a FIFO or regular file, the owner of the
              file is neither the current user nor the owner of the
              containing directory, and the containing directory is both
              world- or group-writable and sticky.  For details, see the
              descriptions of /proc/sys/fs/protected_fifos and
              /proc/sys/fs/protected_regular in proc(5).

       EBADF  (openat()) pathname is relative but dirfd is neither
              AT_FDCWD nor a valid file descriptor.

       EBUSY  O_EXCL was specified in flags and pathname refers to a
              block device that is in use by the system (e.g., it is
              mounted).

       EDQUOT Where O_CREAT is specified, the file does not exist, and
              the user's quota of disk blocks or inodes on the
              filesystem has been exhausted.

       EEXIST pathname already exists and O_CREAT and O_EXCL were used.

       EFAULT pathname points outside your accessible address space.

       EFBIG  See EOVERFLOW.

       EINTR  While blocked waiting to complete an open of a slow device
              (e.g., a FIFO; see fifo(7)), the call was interrupted by a
              signal handler; see signal(7).

       EINVAL The filesystem does not support the O_DIRECT flag.  See
              NOTES for more information.

       EINVAL Invalid value in flags.

       EINVAL O_TMPFILE was specified in flags, but neither O_WRONLY nor
              O_RDWR was specified.

       EINVAL O_CREAT was specified in flags and the final component
              ("basename") of the new file's pathname is invalid (e.g.,
              it contains characters not permitted by the underlying
              filesystem).

       EINVAL The final component ("basename") of pathname is invalid
              (e.g., it contains characters not permitted by the
              underlying filesystem).

       EISDIR pathname refers to a directory and the access requested
              involved writing (that is, O_WRONLY or O_RDWR is set).

       EISDIR pathname refers to an existing directory, O_TMPFILE and
              one of O_WRONLY or O_RDWR were specified in flags, but
              this kernel version does not provide the O_TMPFILE
              functionality.

       ELOOP  Too many symbolic links were encountered in resolving
              pathname.

       ELOOP  pathname was a symbolic link, and flags specified
              O_NOFOLLOW but not O_PATH.

       EMFILE The per-process limit on the number of open file
              descriptors has been reached (see the description of
              RLIMIT_NOFILE in getrlimit(2)).

       ENAMETOOLONG
              pathname was too long.

       ENFILE The system-wide limit on the total number of open files
              has been reached.

       ENODEV pathname refers to a device special file and no
              corresponding device exists.  (This is a Linux kernel bug;
              in this situation ENXIO must be returned.)

       ENOENT O_CREAT is not set and the named file does not exist.

       ENOENT A directory component in pathname does not exist or is a
              dangling symbolic link.

       ENOENT pathname refers to a nonexistent directory, O_TMPFILE and
              one of O_WRONLY or O_RDWR were specified in flags, but
              this kernel version does not provide the O_TMPFILE
              functionality.

       ENOMEM The named file is a FIFO, but memory for the FIFO buffer
              can't be allocated because the per-user hard limit on
              memory allocation for pipes has been reached and the
              caller is not privileged; see pipe(7).

       ENOMEM Insufficient kernel memory was available.

       ENOSPC pathname was to be created but the device containing
              pathname has no room for the new file.

       ENOTDIR
              A component used as a directory in pathname is not, in
              fact, a directory, or O_DIRECTORY was specified and
              pathname was not a directory.

       ENOTDIR
              (openat()) pathname is a relative pathname and dirfd is a
              file descriptor referring to a file other than a
              directory.

       ENXIO  O_NONBLOCK | O_WRONLY is set, the named file is a FIFO,
              and no process has the FIFO open for reading.

       ENXIO  The file is a device special file and no corresponding
              device exists.

       ENXIO  The file is a UNIX domain socket.

       EOPNOTSUPP
              The filesystem containing pathname does not support
              O_TMPFILE.

       EOVERFLOW
              pathname refers to a regular file that is too large to be
              opened.  The usual scenario here is that an application
              compiled on a 32-bit platform without
              -D_FILE_OFFSET_BITS=64 tried to open a file whose size
              exceeds (1<<31)-1 bytes; see also O_LARGEFILE above.  This
              is the error specified by POSIX.1; before Linux 2.6.24,
              Linux gave the error EFBIG for this case.

       EPERM  The O_NOATIME flag was specified, but the effective user
              ID of the caller did not match the owner of the file and
              the caller was not privileged.

       EPERM  The operation was prevented by a file seal; see fcntl(2).

       EROFS  pathname refers to a file on a read-only filesystem and
              write access was requested.

       ETXTBSY
              pathname refers to an executable image which is currently
              being executed and write access was requested.

       ETXTBSY
              pathname refers to a file that is currently in use as a
              swap file, and the O_TRUNC flag was specified.

       ETXTBSY
              pathname refers to a file that is currently being read by
              the kernel (e.g., for module/firmware loading), and write
              access was requested.

       EWOULDBLOCK
              The O_NONBLOCK flag was specified, and an incompatible
              lease was held on the file (see fcntl(2)).

How are you absolutely certain that it'd only ever fail with "Operation not permitted"?
Instead, call perror() after the call to open(), or print the result of strerror().
Comment: I changed the code and printed `strerror(errno)`, which says "Operation not permitted".


A flexible foreign key

Question: I have a sql server database. I'm developing a vb.net application.
Now I'm thinking to have an "Event" table that should keep all the events related with my database. But one of the fields of this table should be a field ObjectID that is related with the record that this event has to do. But this record may be on different tables. For example :

Event 1 ---- Record 25 on table Clients
Event 2 ---- Record 30 Table Invoices
Event 3 ---- Record 40 Table Articles
...

The problem is that this field ObjectID should be a Foreign key in a flexible way , because may be related with different tables.
Is there any way I can resolve this case ?
Thank you !
Comment: Possible duplicate: [SQL Server foreign key to multiple tables](http://stackoverflow.com/questions/15935402/sql-server-foreign-key-to-multiple-tables)
Comment: Possible duplicate of [SQL Server foreign key to multiple tables](https://stackoverflow.com/questions/15935402/sql-server-foreign-key-to-multiple-tables)
Comment: can you give an example of a `Client Event` and a `Invoice Event`?  You likely just need a qualifier column on `Event` to indicate what type of event each is.  Hard to tell exactly what you are asking
Comment: You can index it to make joins faster. But you'll have to have some other column to define what other table the objectId apart of. Or you'll have to have a nullable column for each table you want to have events for and set the foreign key on each column.
Comment: @Plitonix My problem is how can I read the specific record on specific table  for which this event is created? I'm using Entity Framework..
Comment: Since Entity Framework come out often, should it be added as a tag for this question?
Comment: With entity framework, there is an inherited notions that may be what you are looking for. It is close to Zohar's solution.  See those article here. However, I know know how much of this can be implemented without code first.

http://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph
Answer: One way to solve it would be to add a table to your database to act like a base for the other tables and connet it with a one to one relationship to the other tables, and then connect the events table to this base table.
This will allow you to keep data integrity for each of the tables.
The base table can be as simple as just one column, or can have columns thay all other tables have in common, thus implementing a sort of "inheritance" in your data structure.
Create the base table (assuming no common columns between other tables):
CREATE TABLE TblObjectBase
(
    ObjectBase_Id int IDENTITY(1,1) PRIMARY KEY
)

Then, for any other table that needs to be referenced by the ObjectId in the Events table:
CREATE TABLE TblClients
(
    Client_Id int PRIMARY KEY,
    Client_FirstName varchar(10),
    Client_LastName varchar(10),
    --  Other client related data
    CONSTRAINT FK_TblClients_TblObjectBase
               FOREIGN KEY(Client_Id)
               REFERENCES TblObjectBase(ObjectBase_Id)
)

CREATE TABLE TblInvoices
(
    Invoice_Id int PRIMARY KEY,
    -- other incoice related data
     CONSTRAINT FK_TblInvoices_TblObjectBase
               FOREIGN KEY(Invoice_Id)
               REFERENCES TblObjectBase(ObjectBase_Id)
)

The only thing remaining is to insert a new value to the TblObjectBase for any insert on your other tables.  This can be be easily achived by either stored procedures or instead of insert triggers.
An insert procedure could look like this:
CREATE PROCEDURE Insert_TblClients
(
    @Client_FirstName varchar(10),
    @Client_LastName varchar(10),
    -- any other client related data you might have
)
AS
DECLARE @ClientId int

-- Insert a new record to the base table:
INSERT INTO TblObjectBase DEFAULT VALUES;

-- Get the id you've just inserted:
SELECT @ClientId = SCOPE_IDENTITY();

-- Insert the data to the clients table:
INSERT INTO TblClients
(Client_Id, Client_FirstName, Client_LastName.....) VALUES
(@ClientId, @Client_FirstName, @Client_LastName...)

An instead of insert trigger would look like this:
CREATE TRIGGER TblClients_IO_Insert ON TblClients INSTEAD OF INSERT
AS
BEGIN

DECLARE @ClientId int

-- Insert a new record to the base table:
INSERT INTO TblObjectBase DEFAULT VALUES;

-- Get the id you've just inserted:
SELECT @ClientId = SCOPE_IDENTITY();

INSERT INTO TblClients
(Client_Id, Client_FirstName, Client_LastName.....)
SELECT @ClientId, Client_FirstName, Client_LastName.....
FROM inserted

END

If you choose to go with the instead of insert, the fact that the Identity value comes from another table should be transparent to the client (your vb.net program).
Comment: do you think this idea is suitable with my case , since I'm using Entity Framework on my application ?
Comment: I"ve never worked with entity framework so I can't say., I just suggested a way to keep the fk relationship. Why don't you try just a couple of tables and see if EF can handle it?
Comment: ok , but could you explain to me , how this base table will connect to other tables , so I need one field as FK for each table or ???
Comment: what I don't see in your model is how can I read an event. I mean if I want to get the specific record in the specific table that is related with an event ?
Comment: Well, in this model all the tables that are connected with a 1:1 relationship basically share a single identity column. This means that the client_id value can't be the same as an Invoices_id column. You can add a column to the TblObjectBase table that will state the name of the table the records refers to if it will make your code easier, or maybe a column to the events table that will state the object type that reaised the event. However, it's not needed for relational integrity, as the id columns for all the tables that can raise events are exclusive within all the tables that share the 1:1
Answer: SQL Server doesn't support creating such constraint.
But you can simulate the link programmatically without much trouble.
CREATE TABLE tbl_Event
(
    [idEvent]       INT IDENTITY(1,1) NOT NULL,
    [TableSource]   INT NOT NULL,
    [SourceId]      INT NOT NULL
    --Events fields
    CONSTRAINT [PK_Tests] PRIMARY KEY CLUSTERED
    (
        [id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

In the above exemple, SourceId is the foreign key
TableSource is used to know which table the foreign key is from.
In table source you could use sys.objects.object_id of the table.
However, since you don't have much control on those keys that are managed by SQL, I recommend using you own table with defined constant for each table instead of sys.objects.
This way you also have more control on which table can have foreign key in this table and it become really handy overtime.
CREATE TABLE tbl_tableSource(
    [idTableSource] INT IDENTITY(1,1) NOT NULL,
    [Constant]      INT NOT NULL,
    [Name]          NVARCHAR(255) NULL
 CONSTRAINT [PK_Tests] PRIMARY KEY CLUSTERED
(
    [idTableSource] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO tbl_tableSource
VALUES(1000, 'tbl_SomeTable')

INSERT INTO tbl_tableSource
VALUES(2000, 'tbl_SomeOtherTable')

Also, this kind of relation, is less good for performance then standard one. So the field type of your keys and of the constant is really important. It should not be heavy. This because you will need to create an index on tbl_event.
To simulate cascade delete ON, you need to implement trigger on parent table like this :
CREATE TRIGGER OneParentTableOnDelete ON  tbl_SomeTable
FOR DELETE
AS
BEGIN

    DELETE tbl_Event
    FROM DELETED
    INNER JOIN tbl_Event ON tbl_Event.TableSource = [Constant for tbl_SomeTable]
                         AND tbl_Event.idSource = DELETED.id --PrimaryKey

END

To retrieve data, you can then do like this
--For events about one foreign key
SELECT *
FROM tbl_event
WHERE tbl_Event.TableSource = [Constant for tbl_SomeTable]
AND tbl_Event.idSource = @idPrimareyKeyOfSomeTable

--Fore events about multiple foreign key
SELECT *
FROM [tbl_SomeTable]
INNER JOIN tbl_event ON tbl_Event.TableSource = [Constant for tbl_SomeTable]
                      AND tbl_Event.idSource = [tbl_SomeTable].id --PrimaryKey

Comment: on my VB.net program , I use entity Framework. Is it possible to construct an EF query to get data with your structure ?
Comment: I got really few experience with Entity Framework. The part that may not work with Entity Framework are triggers.  http://stackoverflow.com/questions/21943314/entity-framework-6-code-first-trigger
Answer: You could create an 'INDEXED VIEW' -- define it however you like to pull the objectIDs + any other relevant fields, as you've described, from record 25 of the clients table, record record 30 of the invoices table, and so on.
You could do the same thing with a stored procedure.
Depending on how you intend to consume the data -- if you're just pulling it into a vb.net datatable, either of these options should work fine.
A benefit to an approach like this is that you don't have to create or maintain any new tables in your database.
Comment: More here on stored procedures: https://msdn.microsoft.com/en-us/library/ms187926.aspx
Comment: Do you think that this solution , can work in my application that use Entity Framework 6 ?
Comment: You can map entities to stored procedures (some examples here: https://msdn.microsoft.com/en-us/data/gg699321.aspx).  You can map entities to views as well.  You don't have to build your queries in the database -- usually I prefer to -- but you could just as well build your entities by querying directly in from application as well.  Lots of options.

A flexible foreign key


`gnome-keyring-daemon` hangs if I log out & then log in again

Question: When I start my computer (an up-to-date Ubuntu 18.04), and log in and do a days work, everything's fine. I then log out, and leave the computer on while no-one logs in. The next morning I log in again, and gnome-keyring-daemon is running at 100% CPU. SSHing will hang without connecting, because it's trying to unlock the appropriate ssh private key, and gpg won't decrypt anything, again waiting for a private key to be unlocked.
If I restart the computer, everything works fine. This happens all the time for the last several months.
Answer: I don't have a good programmatic answer, but I've found that if I open a terminal window and 'kill -9 processnumber' that will terminate the process. It apparently restarts by itself and frees up the connection.


Azure Functions dynamic input / output binding based on Service Bus trigger message content

Question: I'm trying to create Azure Function 2.0 with multiple bindings. The function gets triggered by Azure Service Bus Queue message and I would like to read Blob based on this message content. I've already tried below code:
public static class Functions
{
    [FunctionName(nameof(MyFunctionName))]
    public static async Task MyFunctionName(
        [ServiceBusTrigger(Consts.QueueName, Connection = Consts.ServiceBusConnection)] string message,
        [Blob("container/{message}-xyz.txt", FileAccess.Read, Connection = "StorageConnName")] string blobContent
    )
    {
        // processing the blob content
    }
}

but I'm getting following error:

Microsoft.Azure.WebJobs.Host: Error indexing method 'MyFunctionName'. Microsoft.Azure.WebJobs.Host: Unable to resolve binding parameter 'message'. Binding expressions must map to either a value provided by the trigger or a property of the value the trigger is bound to, or must be a system binding expression (e.g. sys.randguid, sys.utcnow, etc.).

I saw somewhere that dynamic bindings can be used but perhaps it's not possible to create input binding based on another input binding. Any ideas?
Answer: I'm actually surprise that did not work. There are lots of quirks with bindings. Please give this a shot:
public static class Functions
{
    [FunctionName(nameof(MyFunctionName))]
    public static async Task MyFunctionName(
        [ServiceBusTrigger(Consts.QueueName, Connection = Consts.ServiceBusConnection)] MyConcreteMessage message,
        [Blob("container/{message}-xyz.txt", FileAccess.Read, Connection = "StorageConnName")] string blobContent
    )
    {
        // processing the blob content
    }
}

Create a DTO:
public class MyConcreteMessage
{
    public string message {get;set;}
}

Ensure that the message that you are using in the servicebus is something like this:
{
  "message": "MyAwesomeFile"
}

It should now be able to read your binding container/{message}-xyz.txt and recognize that message


Dual boot windows 8.1 stuck

Question: I have windows 8.1 and Ubuntu 14.04 in my system. I have used boot repair tool  in Ubuntu to fix the grub. Now the boot menu is showing( Before it was not showing). I am also able to boot to Ubuntu. But after selecting Windows from boot menu and press enter. All i am getting a weired screen. Windows is not loading. This is the paste screen boot repair generated http://paste.ubuntu.com/10568910/. Somebody Please help me to fix this.

Thanks for the response. I am able to manually select windows from the drop down. Then after that it is not starting up windows. All i am getting is Ubuntu's purple color background and many strikes all over it. I have almost figured out what is the issue here.
In http://paste.ubuntu.com/10568910/ it says.

The NTFS partition is in an unsafe state. Please resume and shutdown
  Windows fully (no hibernation or fast restarting), or mount the volume
  read-only with the 'ro' mount option.
  mount -t ntfs-3g -o remove_hiberfile /dev/sda1 /mnt/boot-sav/sda1

The issue seems to be Windows's fast start up. It needs to be disabled. Now i have to disable it. But the issue is i have to boot to Windows to disable it, and that is what currently i am not able to do.

Fixed issue now. All i did was, boot into windows using live cd. Then run
bootrec/fixmbr
bootrec/fixboot
Then i am able to boot into my windows. Turned off fast startup from Power options. After that used Ubuntu loaded pen drive to boot to Ubuntu and fix the grub.
Answer: Fixed issue now. All i did was, boot into windows using live cd. Then run
bootrec/fixmbr
bootrec/fixboot
Then i am able to boot into my windows. Turned off fast startup from Power options. After that used Ubuntu loaded pen drive to boot to Ubuntu and fix the grub.
Answer: Can you still get to windows if you manually select your Windows partition before you get to the Ubuntu boot options screen (pressing either F10 or F12 while the computer is first starting up and then selecting Windows in this boot menu)? I can't say I know how to fix your loader, but if the above works and Windows boots then at least you can rule out your Windows installation being damaged. I've also experienced strange things happen when Windows was in the middle of applying updates and I hadn't yet booted back into Windows to let it finish.

Dual boot windows 8.1 stuck


Lost huge shade tree now AC/temp is suffering - are sun shades an option?

Question: Lost a huge shady camphor that filtered sunlight for about 75% of the house (1 story, ranch style, 1200sqft). Obviously another tree won't be viable for several decades but is there a way to use sunsails/shades to gain a similar effect? Not sure what my neighbors would think of it, but not too concerned there. I assume I would have to put up poles to hold the shades and have some way of lowering them/removing them during hurricanes. Is there an obvious reason people don't do this more that I'm missing?
Comment: Another name for sun shades is wind sails.  The anchoring is very important even with light wind.  It will depend on how your house is insulated and how many windows.  Possible just window films or window awnings will work also.  Enough/large amount of sun shade for the house might be close to amount of money for decent size tree(totally unknown).
Comment: Remember - wind on a sail is what moved ships around the world for centuries before steam power. Wind will look at a 4x4 and laugh at the toothpick before snapping it.
Comment: Time to improve the attic insulation. Could put small awnings on some windows.
Answer: Pergola
I built something similar to this:

Very easy to make, many options for the structure. Vine grows on it, in the summer leaves block the sun and make shade on the windows ; in the winter the leaves fall off and it lets the sun in.
Only drawback is I have to trim the vegetation once a year.
This is also quite wind proof, due to being full of holes.
Here's another one:

Basically you need a structure (metal, wood, your choice) either suspended from the wall or resting on feet/columns. Then pull some wire through it, for example every 20cm, to act as support for the plants. You can see the wires in the pic. Choice of plants depends on climate, but the faster they grow, the more trimming you'll have to do.
Wisteria will give flowers in the spring, then shade as leaves grow at the beginning of summer. They will also colonize your roof if you let them.
Comment: @JimStewart as far as the random internet photo is concerned, I have no idea. I built mine out of square steel tubes, suspended to the wall with a steel cable. Can't post a photo because I've temporarily taken it down to install exterior insulation.
Comment: Are these steel rods embedded in a brick or stone wall? How deep into the wall do they go?  How thick is the wall? Are the rods braced above by cables?


Can't open pickatime, picker.open() is not a function

Question: I've a problem to open the timepicker of pickadate.js
I've tried to open it with the code below but it doesn't works for me.
I get an error : "picker.open() is not a function".
this my js code :
$('.timepicker').pickatime({
    default: 'now', // Set default time
    fromnow: 0,       // set default time to * milliseconds from now (using with default = 'now')
    twelvehour: false, // Use AM/PM or 24-hour format
    donetext: 'OK', // text for done-button
    cleartext: 'Clear', // text for clear-button
    canceltext: 'Cancel', // Text for cancel-button
    autoclose: true, // automatic close timepicker
    ampmclickable: false // make AM PM clickable
});

$('#test').click(function () {
    event.stopPropagation();
    event.preventDefault();
    var picker =  $('.timepicker').pickatime('picker');
    picker.open();
});

A weird thing : I tried to open a pickadate object with the same method and it works perfectly ..
Do you have a solution to avoid it ?
thanks for helping
Answer: Haven't quite figured out why, but for me the following works:
Instead of
picker.open();
do
picker.data('clockpicker').show();
Hope that helps!
Answer: It's too late to answer but it will help others.

    var picker = $('.timepicker').pickatime({
       default: 'now', // Set default time
       fromnow: 0,       // set default time to * milliseconds from now (using with default = 'now')
       twelvehour: false, // Use AM/PM or 24-hour format
       donetext: 'OK', // text for done-button
       cleartext: 'Clear', // text for clear-button
       canceltext: 'Cancel', // Text for cancel-button
       autoclose: true, // automatic close timepicker
       ampmclickable: false // make AM PM clickable
   });

  $('#test').click(function () {
    event.stopPropagation();
    event.preventDefault();
    // var picker =  $('.timepicker').pickatime('picker');
    picker.open();
  });

reference


Uploading image to s3 bucket usket using aws sdk php

Question: I am trying to move a file from my php code to s3 bucket using this code:
<code>  $bucket = "bucket-name";

        $s3 = S3Client::factory(array(
            'key'    => 'xxxxxx',
            'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
        ));

            $baseImageUrl = "http://www.xxxxx.com/banner_mobile.jpg";

            $keyname = "31.jpg";
            try {
            // Upload data.
            $result = $s3->putObject(array(
                 'Bucket'       => $bucket,
                'Key'          => $keyname,
                'Body'   => $baseImageUrl,
                'ContentType'  => 'image/jpg',
                'ACL'          => 'public-read'

            ));
            // Print the URL to the object.
            echo $result['ObjectURL'] . "\n";

            } catch (S3Exception $e) {
                echo $e->getMessage() . "\n";
            } catch(Exception $ex){
                echo $ex->getMessage()."\n";
            }
</code>
An empty file (or corrupted file) gets uploaded to s3 bucket. The actual size of image is 37KB, but the uploaded file was of size 40B. What is the reason for this?
Comment: `$baseImageUrl` should be a path to a local file not the `url` to this file
Comment: @mayank: i want the same thing to be done as uploading an image from a web service result image url into the s3 bucket specified location.
Answer: As it seems you're inserting the url as the body of the file, so you're uploading a image file with text, if you want to upload that file you'll need to have the path or the content of the file


How does the Link Amp mod affect the maximum link range for portals in Ingress?

Question: The Link Amp mod is now available to be installed on portals. However, its leaked description only mentions that it increases the maximum link distance, without providing any numbers. So...
What is the exact effect of a Link Amp mod on the maximum linking distance? Is the effect cumulative if several Link Amp mods are installed?
Also - this will be harder to test until we will start getting the mods from regular hacks, but do these mods have 'levels' such as shields? Very Rare Link Amps allow to create longer links than Rare Link Amps?
Answer: The first one doubles the max distance. With every deployed Link Amplifier you get less and less benefit from them, so you should deploy better one first to be more efficient. This is a way to discourage deployment of same mods on portal.

First one = +1x range
Second one = +0.5x range
Third one = +0.25x range
Fourth one = +0.25x range
Total max is +2x (3x the original length)

taken from: http://decodeingress.me/ingress-manual/ingress-items/portal-mods/link-amplifier/
Comment: When you say +2x, do you mean the outcome is "times two" or actually "plus double"? It looks to me like the signage here is inconsistent. The first is probably 2x, the second 1.5x, etc. That or use +1, +.5, etc. Unless the first actually triples the distance!
Comment: The third and fourth linkamps have the same amount of amplification according to the decodeingress article you've provided which is +0.25x range.
Comment: @Flaunting your last edit on the "Fourth one" line isn't correct. The fourth Linkamp's amplification is same as the third one.
Comment: Actually the first one is the one with best quality, not the one in leftmost slot. - Tested with multihacks.
Answer: The correct information is:

First = +1x range
Second = +0.5x range
Third = +0.25x range
Fourth = +0.25x range
Total max is +2x (3x the original length)
Answer: According to the decodeingress article on linkamps one VR Linkamp does extend the portal's range to 3.5 times. (Deduced from the 10.5 times calculation for the max possible range calculation, 10.5/3=3.5) So a single VR Linkamp takes the range amplification about the same amplification where 4 rare Linkamps do stop which is 3x.
Again according to the same article the max available link range is now 655.36 km * 10.5 = 6881.28 km with 4 VR linkamps.


Jcrop Handle Destroy

Question: I'm am allowing multiple image uploads and because of that I need to destroy the handle on jcrop for a new image to appear in the image panes.  I'm using the following code.
I simply need a way for the handle to be released from its current image bindings and be freed up to run another image through this code.
    $scope.cropImage = function(file) {

    $scope.currentFile = file;
    $("#target").attr("src", file.url);
    $("#imageModal").modal("show");

    var jcrop_api,
        boundx,
        boundy,

        // Grab some information about the preview pane
        $preview = $('#preview-pane'),
        $pcnt = $('#preview-pane .preview-container'),
        $pimg = $('#preview-pane .preview-container img'),

        xsize = $pcnt.width(),
        ysize = $pcnt.height();

    $timeout(function () {
        if(jcropHandle != null) {
            jcropHandle.destroy();
        }
        jcropHandle = $('#target').Jcrop({
          onChange: updatePreview,
          onSelect: updatePreview,
          aspectRatio: xsize / ysize
        },function(){
          // Use the API to get the real image size
          var bounds = this.getBounds();
          boundx = bounds[0];
          boundy = bounds[1];
          // Store the API in the jcrop_api variable
          jcrop_api = this;

          // Move the preview into the jcrop container for css positioning
          $preview.appendTo(jcrop_api.ui.holder);
        });
    }, 0);

    function updatePreview(c)
    {
      $scope.coordinates.x1 = c.x;
      $scope.coordinates.x2 = c.x2;
      $scope.coordinates.y1 = c.y;
      $scope.coordinates.y2 = c.y2;
      if (parseInt(c.w) > 0)
      {
        var rx = xsize / c.w;
        var ry = ysize / c.h;

        $pimg.css({
          width: Math.round(rx * boundx) + 'px',
          height: Math.round(ry * boundy) + 'px',
          marginLeft: '-' + Math.round(rx * c.x) + 'px',
          marginTop: '-' + Math.round(ry * c.y) + 'px'
        });
      }
    };
};

$('.image-resize').each(function(i, item) {
    var img_height = $(item).height();
    var div_height = $(item).parent().height();
    if(img_height<div_height){
        //IMAGE IS SHORTER THAN CONTAINER HEIGHT - CENTER IT VERTICALLY
        var newMargin = (div_height-img_height)/2+'px';
        $(item).css({'margin-top': newMargin });
    }else if(img_height>div_height){
        //IMAGE IS GREATER THAN CONTAINER HEIGHT - REDUCE HEIGHT TO CONTAINER MAX - SET WIDTH TO AUTO
        $(item).css({'width': 'auto', 'height': '100%'});
        //CENTER IT HORIZONTALLY
        var img_width = $(item).width();
        var div_width = $(item).parent().width();
        var newMargin = (div_width-img_width)/2+'px';
        $(item).css({'margin-left': newMargin});
    }
});

Answer: This is how I remove Jcrop from element so I can use it with another image.
if ($('#target').data('Jcrop')) {
   $('#target').data('Jcrop').destroy();
}

Answer: If you need to resuse the JCrop, on destroy remove style attr from img, because style will remain and it will make an incorrect crop if new image has a different resolution.
Added to astrocrack solution (sorry, I can't comment on your response)
if ($('#target').data('Jcrop')) {
    $('#target').data('Jcrop').destroy();
    $('#target').removeAttr('style');
}

Jcrop Handle Destroy


Prove the inequality using the binomial theorem

Question: Prove $3^n \geq 2n^2 +1$ for $n = 1,2,\ldots$ using binomial theorem, applied to $(1+x)^n$ with $x=2$.
So I started with expanding $(1+2)^n$ = ${n \choose 0} + {n \choose 1}2  + {n \choose 2}2^2 + \cdots + {n \choose n} \geq 1 + 2n! + 2^n$
I'm not sure what I'm doing wrong or what the next step should be - any help/hints will be appreciated.
Answer: The key is that
$$
{n\choose2}2^2=\frac{4n!}{(n-2)!2!}=2n(n-1).
$$
Then you have, since all terms are positive,
$$
(1+2)^n=1+2n+2n(n-1)+\cdots=1+2n^2+\cdots\geq1+2n^2.
$$
Answer: $$\begin{align}
(2+1)^n & = \color{red}{1}+2n+2\color{red}n(\color{red}n-1)+\text{stuff} \\
& = 1+2n^2+2n-2n+\text{stuff} \\
& = 1+2n^2+\text{stuff} \\
\end{align}$$
Note that since we are binomial expanding for positive numbers, stuff is positive and greater than $0$, assuming the binomial expansion goes out that many terms.


PHP preg_replace string path given

Question: I have issue with preg_replace function in PHP. I cant figure out a pattern and a replacement.
I have this two strings and some code:
    $dirname1 = 'hdadas/dasdad/dasd/period_1min';
    $dirname2 = 'hdadas/dasdad/dasd/period_1min/abcdrfg.php';

    $pieces1 = explode('/', $dirname1);
    $pieces2 = explode('/', $dirname2);

    $dirname1 = end($pieces1);  // output will be period_1min
    $dirname2 = end($pieces2); // output will be abcdrfg.php

    $output = preg_replace($pattern, $replacement, $dirname1); // or (..,..,$dirname2

    echo $output; // i need 1min(without period_) or abcdrfg (without .php)

UPD:
   function Cat($dirname)
   {
      $name = explode('/', $dirname);

      $pattern = ???;
      $replacement = ???;

      return preg_replace($pattern, $replacement, $dirname1);
    }

    print(Cat('hdadas/dasdad/dasd/period_1min'))); // output need 1min only
    print(Cat('hdadas/dasdad/dasd/period_1min/abcdrfg.php'))); // output  need abcdrfg only

Comment: 1. The first 8 lines is the same as: `$dirname1 = basename($dirname1);` 2. Which pattern does this follow when you want `period_` for the first and `abcdrfg` for the second ?
Comment: i cant figure out what to write in $pattern and $replacement
Answer: This should work for you:
(Here I use basename() to get only the last part of the path, then I use pathinfo() to get the last part without the extension. After this I just use preg_replace() to replace everything before the underscore with an empty string)
<?php

    $dirname1 = "hdadas/dasdad/dasd/period_1min";
    $dirname2 = "hdadas/dasdad/dasd/period_1min/abcdrfg.php";

    $dirname1 = pathinfo(basename($dirname1))["filename"];
    $dirname2 = pathinfo(basename($dirname2))["filename"];

    echo $output = preg_replace("/(.*)_/", "", $dirname1);

?>

output:
1min
abcdrfg

Comment: @Undertaker `echo phpversion();` = ? <5.4 ?
Comment: @Undertaker Maybe you want to upgrade your php version, we live in 2015, so you can use array dereferencing
Comment: Yes 5.3.3 that why :)
Comment: I cant project run on < 5.4
Comment: @Undertaker Then you can change these lines from: `$dirname1 = pathinfo(basename($dirname1))["filename"];` to this: `$dirname1 = pathinfo(basename($dirname1)); $dirname1 = $dirname1["filename"]`
Comment: I agree your implementation are better in highest version in php, because it is smaller and effective.
Answer: How about this regex /^.+_|\.[^.]+$/:
$dirname1 = 'hdadas/dasdad/dasd/period_1min';
$dirname2 = 'hdadas/dasdad/dasd/period_1min/abcdrfg.php';

$pieces1 = explode('/', $dirname1);
$pieces2 = explode('/', $dirname2);

$dirname1 = end($pieces1);  // output will be period_1min
$dirname2 = end($pieces2); // output will be abcdrfg.php

$output = preg_replace('/^.+_|\.[^.]+$/', '', $dirname1); // or (..,..,$dirname2
echo $output,"\n"; // i need 1min(without period_) or abcdrfg (without .php)

$output = preg_replace('/^.+_|\.[^.]+$/', '', $dirname2); // or (..,..,$dirname2
echo $output,"\n"; // i need 1min(without period_) or abcdrfg (without .php)

Output:
1min
abcdrfg

Comment: @Undertaker: Sorry, typo I forget the `+` quantifier in the second example. See my edit, it works now.
Comment: @Undertaker: what do you want to keep?
Comment: @Yes, you're right, change the the regex to: `^[^_]+_|\.[^.]+$`
Comment: Thank you, but it outputs abcdrfg.php (with .php) on version 5.3.3
Comment: How the regex look like if it will be period_week_sunday?
Comment: I want to keep week_sunday
Comment: No, this /^.+_|\.[^.]+$/ regex for "period_weekly_sunday" ouput only "sunday"

PHP preg_replace string path given


How to fix Cannot convert value of type 'String?' to expected argument type 'URL'

Question: I am going to send data in formData format. However, an error such as the title occurred.
    func formData(_ api: URL, param: Parameters, img: String?) -> DataRequest {
            return AF.upload(multipartFormData: { (multipartFormData) in
                if img != nil {
                    multipartFormData.append(img, withName: "img", fileName: "image.jpg", mimeType: "image/jpg")
                }
                for (key, value) in param {
                    multipartFormData.append("\(value)".data(using: .utf8)!, withName: key, mimeType: "text/plain")
                }
            }, to: baseURL + api.path(), method: .post, headers: api.header())
        }

This is the code I wrote.An error occurs in the if statement. Can you tell me if my code is correct or what the problem is?
Answer:
multipartFormData.append() should have received a data type, but you gave it a String


Copy everything from one column to another in Apps Script

Question: I'm trying to programmatically copy everything (data, cells borders, format (%), color) from one set of columns to another.
function myFunction(){
    const ss = SpreadsheetApp.getActiveSpreadsheet();
    const sheet = sheet.getSheets()[1];
    const range = sheet.getRange('A1:C5').getValues();
    const newrange = sheet.getRange('D1:F5');

    sheet.insertColumnsAfter(3,3);
    newrange.setValues(range);
    [...]

Here the data as well as the color are copied correctly to the new location.
However, I could not figure out how to replicate:

The cell border lines (to draw a table)
The format of my cells in percentage (including the sign %).

I've tried the following for the percentage - but did not worked:
const percentageRange = sheet.getRange('A1:C5');
percentageRange.setNumberFormat('00.00"%"');

Not sure how should I do for the border
Answer: Try this:
range.copyTo(newrange);

this will copy range completely.
Reference: https://stackoverflow.com/a/44967382/555121
Comment: Thank you @Kos it works fine, except for the cells format. 2 of my columns are in % but it does not appear in % when I copy. For instance 17.00% becomes 00.17% in the newly created column
Comment: Let me know if you have any clue how to solve the % format not being displayed properly. I would really appreciate :)
Comment: just for the record: copyTo copies everything, including format. If you have any other questions, refer to official documentation


Why are my new Azure end points not working?

Question: I have two virtual machines hosted on Azure, and I'm trying to set up new endpoints for one of them. I've successfully created the end points but the connections won't go through. I've used tcpdump to verify that the SYN packets are not even reaching the VM. I don't have a firewall configured on the VM either. All my existing end points work fine, and if I delete one of them, it stops receiving connections. I just can't add any new, working endpoints.
So I tried the same with my second VM and everything works as expected there. The only difference between them is that VM #2 has end points 22, 80, 19000, 19001 while the problematic VM #1 has 80, 443, 19000 and 19001.
What could I be possibly doing wrong? How can I fix this?
Comment: This should be moved to ServerFault. That said: Please edit your question to show your complete endpoint mapping (external ip, internal ip, whether port-forwarded or load-balanced, protocol) for each.
Comment: I posted this same question on ServerFault: http://serverfault.com/questions/542535/why-are-my-new-azure-end-points-not-working
Answer: It seems it was a glitch in Azure. It was fixed during a maintenance run.
Answer: are you sure windows firewall isn't blocking your entry / exit for the endpoints? check it first, then if still having issue start analyzing with Microsoft Message Analyzer (http://www.microsoft.com/en-us/download/details.aspx?id=40308
) on both ends, just to make sure.
Comment: Windows isn't involved. It's a Ubuntu server, just like the other one.


Update Error in Ubuntu

Question: sudo apt-get update

leads me to:
http://ppa.launchpad.net trusty InRelease:
    The following signatures couldn't be verified because the public
    key is not available: NO_PUBKEY FCAE110B1118213C

How can I get the key?
Comment: try : `sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys FCAE110B1118213C`
Answer: I had the same issue with an other key. Like Serverus Tux already said, try to add the missing key. It solved my problem.
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys FCAE110B1118213C
Answer: I could reproduce the problem by deleting the GPG key 1118213C of the Graphics Drivers Team.
Adding ppa:graphics-drivers/ppa again should solve the issue.
Execute : sudo apt-add-repository ppa:graphics-drivers/ppa
Why does it work? While adding the Launchpad PPA back, you see :
gpg: requesting key 1118213C from hkp server keyserver.ubuntu.com

Update Error in Ubuntu


Almost everywhere convergence of a function of rv

Question: Let f(x) a continuous function on $\mathbb {\bar{R}^+}$(extended positive real line,  $x\in(0,\infty]$). Take $y\in \mathbb R^+$. We can say that $\lim_{y\to 0}\frac{x}{y}=\infty $  almost everywhere because the set on which $\lim_{y\to 0}\frac{x}{y}\ne\infty $ is a subset of $\mathbb Q$ which would have a Lebesgue measure zero. Does this make sense? is there a better way to say the same things?
Also, because $\lim_{y\to 0}\frac{x}{y}=\infty $  a.e. and $f$ is continuous on $\mathbb {\bar{R}}$ we can write $f(\lim_{y\to 0}\frac{x}{y})=\lim_{y\to 0}f(\frac{x}{y})$. Does this make sense as well?
Now, if instead of $x$ a real number, we have a random variable X. Can we say that $f(\lim_{y\to 0} \frac{X}{y})=\lim_{y\to 0 }f(\frac{X}{y})$ a.e., knowing that $f(\infty)=c$? If so, the motivation should involve a probability measure, right?
Any reference or hint is appreciated.
Thank you!
Answer: I'm going to answer your questions in order below. Note this is partially opinion-based so take these answers with a grain of salt.

I'd prefer to see you explicitly state the subset of $\mathbb{Q}$ you're referring to (the one for which $\lim_{y\to0}\frac{x}{y}\neq\infty$). In fact, you don't really need to point out that it's a subset of $\mathbb{Q}$ to conclude it has measure $0$, just that it is countable (or, in this case, a singleton). Otherwise I don't have a problem with your phraseology.
Yes, $f(\lim_{y\to0}\frac{x}{y}) = \lim_{y\to0}f(\frac{x}{y})$ makes sense here, so long as you add a.e. after the equation.
While probability theory/real analysis isn't my field, I'd say that this makes sense (or at least can be made precise). The only issues I have with it are that (a) I think you meant to write $\lim_{y\to0}$ not $\lim_y\to\infty$, (b) you should specify which type of random variable you're referring to, and (c) it's more common to say that the value of this limit is almost surely $\infty$, not $\infty$ a.e. (This is just special terminology used in probability theory.) Hopefully someone else will come along who can elaborate on this point or disagree with me!


Javascript / Ajax image gallery/retrieval

Question: I'm still new to js so please bear with me if this doesn't make sense.
I'm wondering if it's possible to generate a gallery that doesn't refresh the page based on already generated pages.
Example gallery: http://www.theaustralian.com.au/news/executive-lifestyle/gallery-fn697wf9-1226045027371?page=1
In the example above, is it possible to make it so the image retrieval is much smoother so that it doesn't look like it's a new page everytime you click next/previous?
All this is based on the assumption I can't change the mark-up/backend. So everything has to be done on the existing mark-up.
Thoughts?
Answer: I don't think you even need ajax.
You could do like do:
When the next button is clicked, change the attribute "src" of the image element and it should change your image.
Now you might want to use ajax to find whats the next image name; here comes ajax. You would probably want to use jQuery, Dojo, Prototype, MooTools.


How can I lower wall cabinets after fitting drywall?

Question: Before fitting a drywall, I measured 12cm from the ceiling and fitted battens (wall studs) across the length of the room to support wall cabinets.
I didn't leave enough room - the wall cabinets are now too high.
Does anything exist such as a metal piece that will act as a lowering mechanism to keep the existing support at the 12cm but allow the cupboard to hang lower e.g. at 24cm from the ceiling. I'm imagining a piece of metal that hooks to both the wall fixture and the cupboard but I'm not sure if it exists.
The battens are 1.5 inches because I needed to bring it in front of some pipes.
Also open to other suggestions.
Comment: Is there some reason you can't attach to studs like everyone else?
Comment: The studs (wooden battens) have already gone in and are incorrectly placed behind the wall
Comment: can you post a picture or a diagram?
Comment: Hey bib, no need - already have my answer below. Just sharing incase anybody else needs the same answer. Lesson learnt, measure your studs (battens) properly before putting on your plasterboard!
Answer: Work out the correct height the battens (studs) should be, cut the plasterboard using a sharp knife or angle grinder and neat as possible and place in the battens where you want them to be. Screw your plasterboard back onto your newly placed batten and polyfill the gaps if you care about tidyness. You can then safely attach your cupboard to the newly placed batten and the cut out will not be seen because it will be behind the cupboard. Hey Presto!
Credit: Father.


How can I turn off power to USB port?

Question: I am using Lubuntu 16.04.  I have analogue speakers that take their power from a USB socket.  I'd like them to turn off when I power down the pc and suspend it. I thought that would be pretty easy, but I have spent a lot of time googling and still do not have a solution.
My best bet seems to be uhubctl as this appears to run on my hardware (the author warns that not all hubcontrollers support the functionality).  I believe this because I have successfully turned off the USB keyboard.
So now I need to know what to specify to turn off power on the USB socket for the speakers.  This is bound to take some guesswork since they are not real USB devices and will not show in lsusb.  Looking at the back panel and the motherboard manual, I see that the group of four sockets where the speakers are plugged in are described as USB 2.0 ports 7-10. My mouse and webcam are plugged into the same group of sockets.
Running uhubctl with no arguments gives:
Current status for hub 2-1 [8087:8002, USB 2.00, 8 ports]
Port 1: 0100 power
Port 2: 0100 power
Port 3: 0100 power
Port 4: 0100 power
Port 5: 0100 power
Port 6: 0100 power
Port 7: 0100 power
Port 8: 0100 power
Current status for hub 1-1 [8087:800a, USB 2.00, 6 ports]
Port 1: 0100 power
Port 2: 0100 power
Port 3: 0100 power
Port 4: 0100 power
Port 5: 0100 power
Port 6: 0100 power
Current status for hub 4-5 [174c:3074 ASUS TEK. ASM107x, USB 3.00, 4 ports]
Port 1: 02a0 power 5gbps Rx.Detect
Port 2: 02a0 power 5gbps Rx.Detect
Port 3: 02a0 power 5gbps Rx.Detect
Port 4: 02a0 power 5gbps Rx.Detect
Current status for hub 3-9 [174c:2074 ASUS TEK. ASM107x, USB 2.10, 4 ports]
Port 1: 0100 power
Port 2: 0303 power lowspeed enable connect [047d:2043 NOVATEK Kensington U+P Keyboard]
Port 3: 0100 power
Port 4: 0100 power

That is not too helpful.  My keyboard shows up, but all my other USB devices - mouse, Seagate HDD, webcam - are not mentioned.
I tried various commands:
uhubctl -a off -p 2 -l 3-9     #Turns off keyboard as expected
uhubctl -a off -p 2 -l 4-5     #ALSO turns off keyboard. Why ?

uhubctl -a off -p 12345678 -l 2-1 #Does not turn anything off
uhubctl -a off -p 123456   -l 1-1 #Does not turn anything off
uhubctl -a off -p 134      -l 4-5 #Does not turn anything off.

So I can turn off the keyboard.  No other USB device is listed (although they are there) and they cannot be turned off.
I have no idea what the hub names represent i.e. 2-1, 1-1, 4-5, 3-9.  Nor does there appear to be any way to infer the hub names from lsusb.
lsusb gives:
Bus 002 Device 002: ID 8087:8002 Intel Corp.
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 008 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 007 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 006 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 005 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:800a Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 003: ID 174c:3074 ASMedia Technology Inc. ASM1074 SuperSpeed hub
Bus 004 Device 002: ID 0bc2:ab24 Seagate RSS LLC
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 007: ID 047d:2043 Kensington
Bus 003 Device 003: ID 174c:2074 ASMedia Technology Inc. ASM1074 High-Speed hub
Bus 003 Device 002: ID 0f62:1001 Acrox Technologies Co., Ltd Targus Mini Trackball Optical Mouse
Bus 003 Device 006: ID 046d:0994 Logitech, Inc. QuickCam Orbit/Sphere AF
Bus 003 Device 004: ID 0b05:180a ASUSTek Computer, Inc.
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

lsusb -t gives:
/:  Bus 08.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/2p, 10000M
/:  Bus 07.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/2p, 480M
/:  Bus 06.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/2p, 10000M
/:  Bus 05.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/2p, 480M
/:  Bus 04.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/6p, 5000M
    |__ Port 1: Dev 2, If 0, Class=Mass Storage, Driver=uas, 5000M
    |__ Port 5: Dev 3, If 0, Class=Hub, Driver=hub/4p, 5000M
/:  Bus 03.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/15p, 480M
    |__ Port 5: Dev 2, If 0, Class=Human Interface Device, Driver=usbhid, 1.5M
    |__ Port 9: Dev 3, If 0, Class=Hub, Driver=hub/4p, 480M
        |__ Port 2: Dev 7, If 0, Class=Human Interface Device, Driver=usbhid, 1.5M
        |__ Port 2: Dev 7, If 1, Class=Human Interface Device, Driver=usbhid, 1.5M
    |__ Port 10: Dev 4, If 1, Class=Vendor Specific Class, Driver=btusb, 12M
    |__ Port 10: Dev 4, If 2, Class=Vendor Specific Class, Driver=btusb, 12M
    |__ Port 10: Dev 4, If 0, Class=Vendor Specific Class, Driver=btusb, 12M
    |__ Port 10: Dev 4, If 3, Class=Application Specific Interface, Driver=, 12M
    |__ Port 14: Dev 6, If 0, Class=Video, Driver=uvcvideo, 480M
    |__ Port 14: Dev 6, If 1, Class=Video, Driver=uvcvideo, 480M
    |__ Port 14: Dev 6, If 2, Class=Audio, Driver=snd-usb-audio, 480M
    |__ Port 14: Dev 6, If 3, Class=Audio, Driver=snd-usb-audio, 480M
/:  Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M
    |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/8p, 480M
/:  Bus 01.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M
    |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/6p, 480M

I can see there is some relationship between the hub names and the bus/port numbers but I can't come up with a rule.
I noticed from lsusb that the USB 2.0 devices seem to use an Intel controller whereas the USB 3.0 and 2.1 devices seem to use an ASUS controller.  I wondered whether the Intel chips might not support power control so I tried the speakers in the USB 2.1 socket which I can turn off when it is attached to the keyboard.  No luck.
Does anybody have any idea why uhubctrl behaves as it does ?
Maybe uhubctl is a red herring and is not going to work.  I know there are other ways to switch power in Ubuntu but they seem to depend on being able to determine the directory which represents the usb socket.  This I have no idea how to do.
Comment: Can you plug in the USB device and watch syslog at the same time to see what is says is connected, and where?
Comment: @DrEval For plugging/unplugging event monitoring `udevadm monitor` is also a good resource.
Comment: My speakers are not real usb devices (they just use usb power).  I used a memory stick in the same slot and found it using lsusb and  lsusb -t.
Answer: uhubctl author here:

uhubctl is using the same addressing method for USB devices as Linux kernel: b-x.y.z, where b is USB bus number, then x, y, z are port numbers of hub chain starting from root USB hub for a given bus. This addressing is semi-stable - it will not change if you unplug and plug USB devices back into the same physical port(s).
To answer your second question, I need to quote this from uhubctl README:

If you have compatible USB 3.0 hub connected to USB3 upstream port, it will be detected as 2 independent virtual hubs: USB2 and USB3, and your USB devices will be connected to USB2 or USB3 virtual hub depending on their capabilities and connection speed. To control power for such hubs, it is necessary to turn off/on power on both USB2 and USB3 virtual hubs for power off/on changes to take effect. uhubctl will try to do this automatically (unless you disable this behavior with option -e).

And finally, uhubctl will only list USB hubs that claim to support PPPS (per-port power switching). However, there are hubs that claim support but don't really work (switching circuitry is physically missing). I am maintaining list of all hubs that are known to work for sure.

If you happen to find hub that works with uhubctl but is not listed, please report it here.
Comment: Thanks for this and I am sorry I did not see the part about USB3 ports showing as USB2 and  3. I think I finally have worked out how to relate the names and numers from lsusb, lsusb -t and uhubctl.  Sadly my conclusion is that only data gets turned off.  I have not managed to power down my speakers. uhubctl is a great little program.  I learned a lot about USB from the source,  Thanks for sharing it.
Comment: @user1759557: if you can find/purchase any USB hub from uhubctl supported list, you can plug your speakers to it and control power.

How can I turn off power to USB port?


Adding link class on href using jQUERY

Question: I researched quite a bit on onClick changes for links but couldn't quite figure out the solution I need. I have a side bar menu that contains multiple links. I have a default class added to the content I want to appear as default. However when I click another link in the sidebar, I want the previous link's "cur" class to be removed, replaced with nothing, then apply "cur" to the new link. Here's my code:

jQUERY :
$(function(){
    $('a').click(function(){
        $('a').removeClass('');
        $(this).addClass('cur');
    });
});

Comment: if you add a sample to your post like you did... you may should add it like an usable sample... in your sample there is no element with the class `cur`. So running this in a testcase would not bring up anything and causes "helpers" to guess if the answere/result is right :) (just as a hint)
Comment: You better add other neighbouring li elements too, it will help us to better uderstand what can be optimal for you.
Answer: $(function(){
    $('a').click(function(){
        $(this).parent('li').siblings().find('a').removeClass('cur');
        $(this).addClass('cur');
    });
});

Hope it will work :)
parent method
siblings method
Answer: Try this:
$(function(){
    $('a').click(function(){
        $('li.blank-2 a').removeClass('cur');
        $(this).addClass('cur');
    });
});

If your other lis also have the class blank-2
Answer: removeClass(className) takes the name of class you want to remove. So try this:
$('a').removeClass('cur');

Comment: OP sayed `I want the previous link's "cur" class to be removed` your source will remove all. So this is no solution
Comment: I point out why the OP's code isn't working at all. The OP should be able to go on from here on his own, judging on the code he already wrote.
Comment: But obviously he dont know `.parent()` and he still will deal with the same problem. :)
Answer: First you could change yout HTML to something like this
HTML

1

2

3

Jquery
$(function(){
    // find you're specific group you want to click
    $('a.child').click(function(event){
        // catch and stop the default action
        event.preventDefault();
        // find the specific parent (upstream the dom) (in this case ul with class parent)
        var $parent = $(this).closest("ul.parent");
        // search within your dom structure (downstream) for a child with a class that is active
        // and remove the class
        $parent.find("a.active").removeClass("active");
        // add the class to the clicked a
        $(this).addClass('active');
   });
});

Answer: i figure out whats the solution for this . I might wanna share it out .
HTML :

CSS :
.bank_list li a.cur {
            width: 198px;
            height: 48px;
            float: left;
            border: 1px solid #f0bebe;
            background: url(../images/zijin_icon.png) no-repeat -897px -188px;
        }

jQUERY :
 $(".bank").click(function(){
            $(".bank").removeClass('bankcur')
            $(this).addClass('bankcur')
    })

RESULT :

Adding link class on href using jQUERY


Mean and Variance Convergence with r.v.

Question: Let $(X_n)_{n\ge 1}$ be a sequence of random variables, with respective distributions being Gaussian, with respective mean $\mu_n \in \mathbb R$ and variance
$\sigma_n^2 > 0$. Prove that if $X_n$ converges in distribution, then $\mu_n$ and
$\sigma^2_n$ need to converge, and identify
the limiting random variable. fb
Answer: Hints Since $(X_n)_n$ is convergent in distribution (to some random variable $X$), the family of distributions $\{\mathbb{P}_{X_n}; n \in \mathbb{N}\}$ is tight. From this one can conclude that the sequences $(\mu_n)_n$ and $(\sigma_n^2)_n$ are bounded (see this post). Thus, there exist convergent subsequences, i.e. $$\mu := \lim_{k \to \infty} \mu_{n_k} \qquad \qquad \sigma^2 := \lim_{k \to \infty} \sigma_{n_k}^2 \tag{1}$$
Moreover, the weak convergence of $(X_n)_n$ implies the convergence of the characteristic functions, $$\mathbb{E}\exp \left( \imath \, \xi \cdot X_n \right) \to \mathbb{E}\exp \left( \imath \, \xi \cdot X \right) \qquad (n \to \infty)$$
Using the explicit formula for characteristic functions of Gaussian random variables and $(1)$, we conclude $X \sim N(\mu,\sigma^2)$.

Mean and Variance Convergence with r.v.


Ubuntu 12.04, mouse pointer(laptop touchpad) get stuck sometime?

Question: In my ubuntu 12.04 system, I faced this problem many times that my mouse pointer get stuck to its position, doesn't move anywhere, all other things works fine except the pointer and I had to restart my system to fix this. How can I fix this so that next time I don't have to restart my system?
Comment: plz add what hardware you have. What is the pointing device that you use, touchpad or a USB mouse? When does it get stuck, while does something specific or randomly anytime?
Comment: acer laptop,Intel Pentium P6200 processor, 2gb DDR3 RAM, and its touchpad. it happens sometime not randomely possibly bcoz of low RAM.
Comment: does it happen when some particular program is open, or happens even when there are no programs running? when the pointer gets stuck, if you do `top` in a terminal, is any process consuming a lot of cpu?
Comment: ya i think u are right..bcoz it happens when i opened lot of apps in my system,suddenly system get hanged for only few seconds say 5-6secs after that my mouse pointer gets stuck..it doesn't happens each time but sometimes, possibly when m running out of memory..
Answer: As per the comments in the question: this is the explanation:
When a lot of apps are opened, they would require more memory than the physical RAM of the system. This would prompt the system to use the swap partition, and write the "unrequired" data out on the swap (on disk). Now, if a lot of, or most of the apps are active, then the unrequired memory is very low, and in reality, the system keeps writing stuff to swap, takes it out and writes something else, and take it out again, and writes something else on swap. This would go on, and no real processing would happen. This situation would be indicated by a lot of disk activity (observable through iotop, or the constantly on LED for disk on the laptop).
The remedy for this is to get bigger RAM if you really want to use so many apps in general. Otherwise just be aware that hardware has some limitations and open just lesser number of apps in the system simultaneously.
If you must use so many apps at once, then try a lightweight ubuntu edition like Lubuntu or Xubuntu.
This answer is open ended, with a possibility of a google search for "techniques to reduce memory consumption of ubuntu".
Comment: ok..thanks for such a usefull information...and i have found another article with same problem http://askubuntu.com/questions/128265/mouse-pointer-touchpad-getting-stuck-often-in-12-04?rq=1 , where i found to use (ctrl+alt+f2 and then ctrl+alt+f7) as a solution, so m waiting for my mouse to get stuck again...
Answer: I found that answer given here https://askubuntu.com/a/184852/239257 works for me.
Step 1. CTRL+ALT+F2
Step 2. CTRL+ALT+F7
and problem solved!