text:
Q: How to make a design more independent of a particular silicon vendor? In many hardware projects it would be nice to have the freedom to switch between vendors easily, mainly microprocessors and microcontrollers.
I can see many reasons for wanting to have this freedom, one of them being the ability to easily switch to a cheaper company if one company decided to jack their prices up. Another situation is when a designer decides to change the project in a direction that the old microcontroller just can't handle, I can see this happening within a company that is trying to reuse hardware modules.
Is there any way of designing hardware to be modular enough to easily switch out these core components? What are the issues with designing this way?

A: There is no formal or 'only right' answer to this, but sensible guidelines can be suggested. These are essentially the same as a designer would seek to comply with if developing a product intended to have a long lifetime, international multi country manufacture and a desire for no design changes.
I've gone beyond just silicon as if you want to make your product buildable anywhere on earth & long term there are more issues than just the silicon.
In all of this a good working crystal ball and perfect 20-20 hindsight helps.
There is some redundancy and even contradiction here. The aim are guidelines which are each considered on their merits rather that a set of hard and fast rules. For example - the first two suggestions have purposefully been chosen to somewhat contradict each other as an example. These are all "out of my head" and on the fly - if I think of more I'll add them. Criticism welcome via comment system.

*

*Use only multiple vendor sourced parts.
This would tend to eliminate anything from eg Maxim who make superb products but who are frequently the sole source. They are also far from reliable in supply to other than larger customers.

*If using single sourced parts choose only vendors who have a solid history of maintaining old parts in stock for decades and/or who provide 100% backwards compatability between newer and legacy parts. Applies more to eg microcontrollers than AND gates.
A supplier who does very well at this is Microchip. You can (probably) still buy 16C16's.
A supplier who does badly at this is Atmel. This does not make them bad per se - just bad for this purpose. Old parts are taken out of production quite rapidly. Backwards compatability is not apparently a priority.

*Consider avoiding parts which are or are likely to be restricted in availability by regulations. A notable example is USA's ITAR which effectively classifies various components as if they were munitions and regulates or prevents their export from the US. I am informed that some manufacturers of certain niche products (eg European satellite systems) make every effort to avoid componentry which is or may be ITAR entangled. If a consistent internationally produced product is required then this may involve using parts from eg European sources in the US.

*Use parts which have potentially long lifetime families and which are part of formal or informal standards. eg the ARM processors offer a generic processor base which would allow a subset of parts to be chosen which have a good chance of being widely available and for a significant period,

*Choose logic families which are liable to remain mainstream or to be likely to offer backwards compatible families.

*For systems where it is not utterly essential that they be leading edge, highest performance, highest density, ... do not make them so. Today's leading edge gee whizz system can be tomorrow's bad idea. Cooling, reliability, longevity, quality, ... are not necessarily comfortable companions of the latest and greatest. But, they may be. Choose sensibly.

*Use industry standards where applicable.

*The following is more about longevity than long term buildability, but ...:
Do due diligence diligently.
Use reputable manufacturers who know their stuff, produce quality product invariably, provide good data sheets with accurate and detailed information.
Identify component groups that have longevity issues and design accordingly. eg wet electrolytic aluminum caps.
If you don't use Panasonics caps know why not.
If you don't use LEDs made by or licensed via the 6 or so major makers know that you've got it wrong.
Don't use tantalum capacitors (yes, I know).
Be aware of potential issues of technologies. eg LiIon vent with flame and calendar life. Beryllium ceramics die in pain. Tin whiskering.
When designing, understand maximum versus typical ratings (or minimum versus typical) - and realise that what usually works is not guaranteed to always work. Understand absolute max versus recommended max operating - and realise that what is guaranteed to survive is not guaranteed to operate. Design for manufacturers worst case specs. And then some.
Never allow protection diodes to conduct more than a few microamps (if that) under normal operating conditions. Realise that allowing protection diodes to conduct may produce no observed bad results ever - but may cause heartache and problems beyond imagining just as easily.
Buy batteries of any technology only from manufacturers and vendors whose capabilities, integrity and bona-fides are known beyond question. Test them anyway.
Understand what aspects of electrostatic protection are marketing hype and which are necessary. Know that unprotected LEDs care more than almost anything.
Understand solder.

A: For parts such as micro-controllers, CPLDs/FPGA, data converters, etc where different manufacturers produce similar but not drop-in-compatible offerings, you can try to limit the cost of changing by doing several things:

*

*Try to compartmentalize the uniqueness to a portion of the board and just a few source files in the software that do low-level peripheral interaction (the later can be useful also if you want to build a version of your code for a desktop PC with simulated peripherals, something that's often extremely useful if your hardware is late or you need to let those who don't have it evaluate software ideas)

*Avoid depending on really unique vendor-specific features and extensions - not just hardware but toolchain as well.

*Document any unique properties on which you rely ("this chip has a Vih compatible with the lower voltage driver"), or any odd things you do to work around unique bugs, so that anyone making an adaptation to different chips can take this into account up front and not rediscover it after a week of putting head-level dents in a cubical wall.
Obviously, abstracting things out to generic interface and avoiding unique features does limit the degree to which you can optimize a design to take fullest advantage of a given chip.  That's a judgment call based on the need for best performance vs. the likelihood of needing to change out one of the parts quickly.

A: These days it is very hard to find second source chips that are drop-in compatible.
CPUs:  It used to be that various manufacturers had agreements with other mfgs to be a second source.  That's how AMD got started back in the early 80's making Intel CPU's.  This is not done today.  You can find some ARM and 8052 CPU's made by several different companies but they are not usually drop-in compatible.  Other than that, you're out of luck-- especially with the mainstream chips.
RAM:  You can still find some pin compatible ones.
Flash:  While rare, pin compatible flash chips do exist.  It's harder with NOR flash than NAND, and easier with SPI flash that parallel flash.  There will be small software differences for programming the flash.
CPLDs:  There used to be pin compatible versions out there, but I haven't seen any in the past 10 years.
FPGAs:  Forget it.
Voltage Regulators:  You might find a second source for the simpler chips, but not so much for the more modern and complex chips.


text:
Q: JWPlayer : Video is not open in full view with Chrome version 71 in ANDROID Jwplayer full-screen view is not working from full-screen toggle button and Screen rotation in Android. It was working fine Previously.
It was not working with latest Chrome App version 71.
How we can resolve it?

A: me has solved dis issue. If any issue regarding jwplayer version
  please write here
Update JWPlayer dependency
app Gradle
implementation 'com.longtailvideo.jwplayer:jwplayer-core:3.4.1'
  implementation 'com.longtailvideo.jwplayer:jwplayer-common:3.4.1'
When you will update Jwplayer version some override method param needs to be the change
if you want to upgrade version 2.X to 3.X tan you TEMPhas to upgrade your JwPlayer licence key also and need 3.X licence key

redpajama_set_name: RedPajamaStackExchange


text:
Q: In Swift, is Key-Value Coding available for custom objects without subclassing NSObject? In Key-Value Coding Programming Guide it states NSObject subclasses are KVC compliant.

Swift objects that inherit from NSObject or one of its subclasses are key-value coding compliant for their properties by default

Can custom objects(struct, classes) adopt NSKeyValueCoding and be KVC compliant?
Also, how is KVC given to an object just by subclassing NSObject?

A: Unlike a formal protocol, that any object could technically conform to, NSKeyValueCoding is available to any NSObject via Informal Protocols:

An informal protocol is a category on NSObject, which implicitly makes
  almost all objects adopters of the protocol. (A category is a language
  feature that enables you to add methods to a class without subclassing
  it.) Implementation of the methods in an informal protocol is
  optional. Before invoking a method, the calling object checks to see
  whether the target object implements it. Until optional protocol
  methods were introduced in Objective-C 2.0, informal protocols were
  essential to the way Foundation and AppKit classes implemented
  delegation.

This is as opposed to simply implementing the KVC directly into NSObject, I think the main benefit of the informal protocol is to split up the functionality of NSObject into separate files.  But there may be other benefits of using Informal Protocols
And because NSKeyValueCoding is a category on NSObject, you unfortunately cannot just make any custom object support KVC


text:
Q: Mount Network Share to a folder With net use or regular ui "map network drive" I can mount network share to a drive letter (a volume) in Windows. But what if I want to mount it to a folder?
Say to d:\myUbuntuShares and not z:

A: I realize this question is old, but here is a proper answer for your question. I have only done this on Windows 7 so I have no idea if this will work on any of the other Windows versions.
Open a shell by writing cmd in the run field of the start button and enter the following command mklink /d  C:\path\to\your\directory \\Server\path\to\share.
You can also do this from powershell but powershell must be started with administrator rights and the command above has to be preceded by cmd /c

A: You can try using Symlinker.


text:
Q: How to delete one shape off of powerpoint using VBA I have a macro that deletes all of the tables in my powerpoint and then a different macro to import the new tables from excel. I'm having trouble figuring out how to only delete that shape, however. The code I have right now deletes the title of the slide and all of the comments too (see below for current). Any ideas how to only remove that one shape? OR is it possible to delete only pictures and not text??
    Dim sl As PowerPoint.Slide, sl_cnt As Long, pr As Object, pr_name As String, ppt As Object
    Dim i As Long, j As Long
    Set ppt = GetObject(, "PowerPoint.Application")
    Set pr = ppt.Presentations(1)
    For j = 10 To 1 Step -1
        Set sl = pr.Slides(j)
        For i = sl.Shapes.Count To 1 Step -1
            sl.Shapes(i).Delete
        Next i
    Next j

       'Record the date & time of procedure execution
    Range("DeletePreviousPPTData").Value = Format(Now(), "mm/dd/yy") & " - " & Format(TimeValue(Now), "hh:mm AM/PM")

End Sub

A: Your code is deleting all of the shapes on the slide.
Before deleting each shape, make sure that it's a table.
As @BigBen mentioned, .HasTable will identify shapes that are tables, but it'll miss tables contained in content placeholders.
This IsTable function will test for both. Use it like so:
Sub YourSubName()

Dim sl As PowerPoint.Slide, sl_cnt As Long, pr As Object, pr_name As String, ppt As Object
    Dim i As Long, j As Long
    Set ppt = GetObject(, "PowerPoint.Application")
    Set pr = ppt.Presentations(1)
    For j = 10 To 1 Step -1
        Set sl = pr.Slides(j)
        For i = sl.Shapes.Count To 1 Step -1

' ADD THIS TEST
If IsTable(sl.Shapes(i)) then
   sl.Shapes(i).Delete
End if

        Next i
    Next j

       'Record the date & time of procedure execution
    Range("DeletePreviousPPTData").Value = Format(Now(), "mm/dd/yy") & " - " & Format(TimeValue(Now), "hh:mm AM/PM")

End Sub

Function IsTable(oSh As Shape) As Boolean

    If oSh.Type = msoPlaceholder Then
        If oSh.PlaceholderFormat.ContainedType = msoTable Then
            IsTable = True
        End If
    Else
        If oSh.HasTable Then
            IsTable = True
        End If
    End If

End Function


text:
Q: How to generate simpler xml in c#? if there any way to generate xml file in c# with form like this:
<data>
<tableName fieldname="value" fieldname2="value2" fieldname3="value3" />
</data>

I tried
System.Data.DataTable datatable = new System.Data.DataTable("tableName");
datatable.Columns.Add("filename", typeof(string));
datatable.Columns.Add("time", typeof(string));
datatable.Columns.Add("message", typeof(string));
.
.
datatable.WriteXml("Raports.xml")

and my xml has body like:
<tableName>
<filename>Raport_1201_1</filename>
<time>15:21:11.343</time>
<message>START</message>
</tableName>

A: using XElement from LINQ to XML API is probably the simplest way:
XElement data =
    new XElement("data",
        new XElement("tableName",
            new XElement("fieldname", "value"),
            new XElement("fieldname", "value2"),
            new XElement("fieldname", "value3")
        )
    );

Microsoft has great tutorial on LINQ to XML or specifically Creating XML Trees with bunch of examples.

A: You can use XDocument to create a new xml:
XDocument doc = new XDocument(
    new XElement("data",
        new XElement("tableName",
            new XElement("filename", yourfilename),
            new XElement("time", yourTime),
            new XElement("message", yourMessage)
        )
    ));
doc.Save(yourFileName);

A: The answer is, to use XAttributes inside Xelement:
XElement data = new XElement("data");
data.Add( new XElement("tableName",
new XAttribute("fieldname", "value"),
new XAttribute("fieldname", "value2"),
new XAttribute("fieldname", "value3")
)
);
data.save("some.xml");

Thanks for help everyone! ^^


text:
Q: A dependency job for cryptsetup.target failed. See 'journalctl -xe' for details I am trying to encrypt swap file in 20.04 post-installation (i successfully conducted home dir encryption). I have a swap file created, with an UUID, and these are my
fstab:
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/sda3 during installation
UUID=3b76b7a1-8e02-439b-982f-39f8954c4e6e /               ext4    errors=remount-ro 0       1
# /boot/efi was on /dev/sda1 during installation
UUID=FEFC-8940  /boot/efi       vfat    umask=0077      0       1
UUID=684f3c6e-907a-4a35-95b4-7b6cde21440b none swap sw 0 0

crypttab (before starting):
# <target name> <source device>     <key file>  <options>

/dev/mapper is just control
blkid:
dev/sda3: UUID="3b76b7a1-8e02-439b-982f-39f8954c4e6e" TYPE="ext4" PARTUUID="6a8896ab-92bb-4bd7-a405-7650cca8d9e6"
/dev/loop0: TYPE="squashfs"
/dev/loop1: TYPE="squashfs"
/dev/loop2: TYPE="squashfs"
/dev/loop3: TYPE="squashfs"
/dev/loop4: TYPE="squashfs"
/dev/loop5: TYPE="squashfs"
/dev/loop6: TYPE="squashfs"
/dev/loop7: TYPE="squashfs"
/dev/sda1: UUID="FEFC-8940" TYPE="vfat" PARTLABEL="EFI System Partition" PARTUUID="305bb9b1-cde6-4fa5-9702-491a4dcd71f4"
/dev/loop8: TYPE="squashfs"
/dev/loop9: TYPE="squashfs"
/swapfile: UUID="684f3c6e-907a-4a35-95b4-7b6cde21440b" TYPE="swap"

following commands are run:
sudo swapoff -a
sudo /etc/init.d/cryptdisks start
sudo swapon -a
sudo swapon -s

output:
/swapfile                               file        16777212    0   -2

/dev/mapper still just control. Now lets encrypt with: sudo ecryptfs-setup-swap!
output:
WARNING:
An encrypted swap is required to help ensure that encrypted files are not leaked to disk in an unencrypted format.

HOWEVER, THE SWAP ENCRYPTION CONFIGURATION PRODUCED BY THIS PROGRAM WILL BREAK HIBERNATE/RESUME ON THIS SYSTEM!

NOTE: Your suspend/resume capabilities will not be affected.

Do you want to proceed with encrypting your swap? [y/N]: y

INFO: Setting up swap: [/swapfile]
WARNING: Commented out your unencrypted swap from /etc/fstab
A dependency job for cryptsetup.target failed. See 'journalctl -xe' for details.

---journalctl -xe LOG---
https://pastebin.com/yqJZ9tQj
New crypttab is:
cryptswap1 /swapfile /dev/urandom swap,offset=1024,cipher=aes-xts-plain64

and new fstab is:
#UUID=684f3c6e-907a-4a35-95b4-7b6cde21440b none swap sw 0 0
/dev/mapper/cryptswap1 none swap sw 0 0

There is only one RED error in logs and it repeats itself:
-- The unit UNIT has successfully entered the 'dead' state.
Mai 23 20:51:32 icbosk-X556UV systemd[1]: dev-disk-by\x2duuid-684f3c6e\x2d907a\x2d4a35\x2d95b4\x2d7b6cde21440b.device: Job dev-disk-by\x2duui>
Mai 23 20:51:32 icbosk-X556UV systemd[1]: Timed out waiting for device /dev/disk/by-uuid/684f3c6e-907a-4a35-95b4-7b6cde21440b.
-- Subject: A start job for unit dev-disk-by\x2duuid-684f3c6e\x2d907a\x2d4a35\x2d95b4\x2d7b6cde21440b.device has failed
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- A start job for unit dev-disk-by\x2duuid-684f3c6e\x2d907a\x2d4a35\x2d95b4\x2d7b6cde21440b.device has finished with a failure.
--
-- The job identifier is 1992 and the job result is timeout.

A: This issue is easily fixed by running sudo cryptdisks_start cryptswap1 when everything is orderly configured. Remember encrypted swap is ok if you dont use it extensively. It requires more CPU power if it is to be used as a regular swap.


text:
Q: Cassandra on multi node cluster -- nodes not linking to Seed Below mentioned is my Cassandra set up:

*

*192.168.80.115 (Seed)

*192..168.80.116 (Node1)

*192..168.80.117 (Node2)

*192..168.80.118 (Node3)
I have installed the Cassandra in all the nodes
below mentioned is the configuration of the cassandra.yaml
cassandra.yaml - 192.168.80.115 (Seed)
======================================

    cluster_name: 'Test Cluster'
    initial_token: 0
    seed_provider:
        - seeds:  "192.168.80.115"
    listen_address: 192.168.80.115
    rpc_address: 0.0.0.0
    endpoint_snitch: RackInferringSnitch

cassandra.yaml - 192.168.80.116 (Node1)
========================================
cluster_name: 'Test Cluster'
initial_token: -4611686018427387904
seed_provider:
    - seeds:  "192.168.80.115"
listen_address: 192.168.80.116
rpc_address: 0.0.0.0
endpoint_snitch: RackInferringSnitch

cassandra.yaml - 192.168.80.117 (Node2)
========================================

    cluster_name: 'Test Cluster'
    initial_token: 4611686018427387904
    seed_provider:
        - seeds:  "192.168.80.115"
    listen_address: 192.168.80.117
    rpc_address: 0.0.0.0
    endpoint_snitch: RackInferringSnitch

cassandra.yaml - 192.168.80.118 (Node3)
========================================
cluster_name: 'Test Cluster'
initial_token: -9223372036854775808
seed_provider:
    - seeds:  "192.168.80.115"
listen_address: 192.168.80.118
rpc_address: 0.0.0.0
endpoint_snitch: RackInferringSnitch

When I start Cassandra and check the node status in the seed I am able to see only my localhost and not other nodes
192.168.80.115 Seed
Datacenter: datacenter1
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address    Load       Tokens       Owns    Host ID                               Rack
UN  127.0.0.1  96.98 KB   256          ?       deb3f882-1886-4e09-be08-21ebd7e99c8d  rack1

And status in the nodes are as bellow
192.168.80.116 Node 1
Datacenter: datacenter1
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address    Load       Tokens       Owns    Host ID                               Rack
UN  127.0.0.1  116.33 KB  256          ?       21a310ee-5652-4179-8b59-d1c7dcd538ee  rack1
Note: Non-system keyspaces don't have the same replication settings, effective ownership information is meaningless

192.168.80.117 Node 2
Datacenter: datacenter1
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address    Load       Tokens       Owns    Host ID                               Rack
UN  127.0.0.1  156.95 KB  256          ?       b64a5a17-21d0-4cf6-bbd6-1eff8d8feb93  rack1

Note: Non-system keyspaces don't have the same replication settings, effective ownership information is meaningless

192.168.80.118 Node 3
Datacenter: datacenter1
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address    Load       Tokens       Owns    Host ID                               Rack
UN  127.0.0.1  157.04 KB  256          ?       43a24dea-26cc-4094-9da7-2b26b8c5f7e5  rack1
Note: Non-system keyspaces don't have the same replication settings, effective ownership information is meaningless

Why I am not able to see  worker nodes in seed node status


text:
Q: 'ddpJobType' has a SelectedValue which is invalid because it does not exist in the list of items im trying to bind the data from database to dropdownlist and i want to set the default value as "select". but i got this error.
My Code is:
<asp:DropDownList ID="ddpJobType" runat="server" Width="226px" Height="26px"
                    onselectedindexchanged="ddpJobType_SelectedIndexChanged">
            <asp:ListItem Selected="True" Value="0" Text="--Please Select Type--"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
                    ErrorMessage="Please Select JobType "  Font-Size="Small"
                    ForeColor="Red" ControlToValidate="ddpJobType"
                    ValidationGroup="VGPJobPost"></asp:RequiredFieldValidator>

A: If you are banding data using DataSource, then your default item will not be available after the call of DataBind function. You need to add it manually after calling databind something like below
dropDownList.DataSource= yourdataSource;
dropDownList.DataBind();
dropDownList.Items.Insert(0, new ListItem("--Please Select Type--", "0"));

Another option is in the designer you need to specifiy
AppendDataBoundItems=true

This will make sure your designtime list items are present after databind


text:
Q: Can i put a box in half over another box (without px)? Is there an optimal solution for my problem? I have a green box with position: relative; and a white box with position: absolute;
The absolute box has top: 0; I only wish that the white box is exactly centered (with one half over the green box and the other half outside). Is there a solution for this in CSS, regardless of the height of the box in px?
Thank you in advance!

A: Translate is your friend:
.white-box {
  position: absolute;
  top: 0;
  transform: translateY(-50%);
}


text:
Q: Install an Electron app without code sign and Smart Screen I need some information ,i need to install a Electron app in another computer but i have the problem with the Smart Screen on Windows because the app isn't sign.
The question is if can i install my Electron app without the Smart Screen without paying for code sign ?

A: Yes, on the "Windows Defender Smartscreen" click the "more info" link then the "Run anyway" button.


text:
Q: Accessing a 2D array which is returned as a pointer in C I'm trying to return a 2D array from a function. I've tried some ways mentioned in some websites. But they are helpless. So finally I'd assigned a pointer to the 2D array and returned it from the function. And the sample function's code is given below
float *test(int *x, int *y)
{
    static float res[2][3];
    float[] temp = {1,2,3};
    for(int i=0;i<3;i++) res[0][i] = temp[i];
    for(int i=0;i<3;i++) res[1][i] = temp[i]*-1;
    float *ptr = &res[0][0];
    return ptr;
}

Now I have a problem that how to access this 2D array in main function to print all of it's elements.
Could anyone give a solution? Thanks in advance:)

A: You could return a pointer to static variable:
char (*modify(char input))[3]
{
  static char variable[3][3];
  variable[0][0] = input;
  variable[1][1] = input+1;
  return variable;
}

int main() {
    char (*result)[3] = modify(a);
}

However, this is not a reentrant function. Another option is using dynamic memory (i.e. malloc), but memory leaks are quite common when returning pointers to allocated memory.

Another approach it's to pass the array to the function, already allocated, so you don't have to be worried about releasing memory or using statics:
void modify(char variable[][3], char input) {
    variable[0][0] = input;
    variable[1][1] = input+1;
}

int main(void) {
    char result[3][3];
    modify(result,a);
}

A better approach it's to create a typedef to highlight the purpose, length and making easier working with it:
typedef struct { char x[3][3]; } my2D_t;

void modify(my2D_t *variable, char input) {
    variable->x[0][0] = input;
    variable->x[1][1] = input+1;
}
int main() {
    my2D_t result;
    char a = 1;
    modify(&result,a);
}

Also returning by value as tstanisl noticed. It creates another my2D_t, but the compiler will probably end up with something similar to the previous idea for the sake of optimization known as the "as-if" rule:
typedef struct { char x[3][3]; } my2D_t;

my2D_t modify(char input) {
    my2D_t variable;
    variable.x[0][0] = input;
    variable.x[1][1] = input+1;

    return variable;
}
int main() {
    char a = 1;
    my2D_t result = modify(a);
}

A: You have to go through dynamic allocation malloc is used for this.
Consider this code:
float **result = NULL; // if you want to return 2D array you need double pointer
result = (float **)malloc(2 * sizeof(float *)); // allocating assuming that the allocating will not fail otherwise it return NULL
for(int i = 0; i < 2; i++)
    result[i] = (float *)malloc(3 * sizeof(float));

for(int i = 0; i < 3; i++) result[0][i] = i;
for(int i = 0; i < 3; i++) result[1][i] = i * -1;
return result;

Important part is also in main function where you should deallocate the memory to prevent memory leak. Is's done through free function and you should do this revere to the allocation to free all the memory you allocated.
for(int i=0;i<3;i++) free(result[i]); //done in main
free(result);

A: Declare the return type of your function properly, then just return the static array:
float (*test(int *x, int *y))[3]
{
    static float res[2][3];
    float temp[] = {1,2,3};
    for(int i=0;i<3;i++) res[0][i] = temp[i];
    for(int i=0;i<3;i++) res[1][i] = temp[i]*-1;
    return res;
}

Note that returning a static array has the problem that all calls to the function will (re)use that same array, so the second call will clobber the array returned by the first call.  You could instead malloc the array:
float (*test(int *x, int *y))[3]
{
    float (*res)[3] = malloc(2 * sizeof *res);
    float temp[] = {1,2,3};
    for(int i=0;i<3;i++) res[0][i] = temp[i];
    for(int i=0;i<3;i++) res[1][i] = temp[i]*-1;
    return res;
}

but then the caller will need to remember to call free on the returned pointer when it is no longer needed.


text:
Q: ANDROID: attempt to re-open an already-closed object? I am trying a delete data from my table(s) however it seems that I am getting an error. So basically in my database contains two tables that are connected through an "exercise ID". So to delete data from my database, I would need to first get an exercise ID from the row I want deleted, then, use that as a reference against my second table and delete everything that is associated with it. So heres what I have so far that does not seem to want to work...
public void deleteRowFromDatabase(String exerciseName, String bodyPart) {

    SQLiteDatabase db = myDBHelper.getWritableDatabase();

    int exerciseID = getExerciseID(exerciseName, bodyPart);
    String query = "SELECT " + myDBHelper.COLUMN_EXERCISENAME_ID + " FROM " + myDBHelper.TABLE_EXERCISES_VALUE +
                    " WHERE " + myDBHelper.COLUMN_EXERCISENAME_ID + "=\"" + exerciseID + "\";";

    Cursor c = db.rawQuery(query, null);

    while (c.getCount()>0){
        c.moveToFirst();
        db.execSQL("DELETE FROM " + myDBHelper.TABLE_EXERCISES_VALUE + " WHERE " + myDBHelper.COLUMN_EXERCISENAME_ID +
                    "=\"" + exerciseID + "\";");
        c.moveToNext();
    }

    db.execSQL("DELETE FROM " + myDBHelper.TABLE_EXERCISES + " WHERE " + myDBHelper.COLUMN_BODYPARTNAME +
                "=\"" + bodyPart + "\"" + " AND " + myDBHelper.COLUMN_EXERCISENAME + "=\"" + exerciseName + "\";");

    c.close();
    db.close();
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LOW LEVEL METHODS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
public static class MyDBHelper extends SQLiteOpenHelper{

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "exercises.db";
    public static final String TABLE_EXERCISES = "exercises";
    public static final String TABLE_EXERCISES_VALUE = "exercises_value";

    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_BODYPARTNAME = "bodypartname";
    public static final String COLUMN_EXERCISENAME = "exercisename";

    public static final String COLUMN_EXERCISENAME_ID = "exerciseid";
    public static final String COLUMN_NUMSETS = "numsets";
    public static final String COLUMN_NUMWEIGHT = "numweight";
    public static final String COLUMN_NUMREPS = "numreps";

    public MyDBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        //used for debugging
       // context.deleteDatabase(DATABASE_NAME);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String query = "CREATE TABLE " + TABLE_EXERCISES + "(" +
                COLUMN_ID  + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_BODYPARTNAME + " TEXT NOT NULL," +
                COLUMN_EXERCISENAME + " TEXT NOT NULL" +
                ");";

        db.execSQL(query);

        query = "CREATE TABLE " + TABLE_EXERCISES_VALUE + "(" +
                COLUMN_ID  + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_EXERCISENAME_ID + " INTEGER NOT NULL," +
                COLUMN_NUMSETS + " INTEGER NOT NULL," +
                COLUMN_NUMWEIGHT + " DOUBLE NOT NULL," +
                COLUMN_NUMREPS + " INTEGER NOT NULL" +
                ");";

        db.execSQL(query);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXIST " + TABLE_EXERCISES);
        db.execSQL("DROP TABLE IF EXIST " + TABLE_EXERCISES_VALUE);
        onCreate(db);
    }

}

LOG DATA
   07-29 02:04:44.748    9539-9539/com.example.edwardlim.workoutlogs E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.edwardlim.workoutlogs, PID: 9539
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.example.edwardlim.workoutlogs/databases/exercises.db
        at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
        at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1312)
        at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
        at com.example.edwardlim.workoutlogs.MyDBAdapter.deleteRowFromDatabase(MyDBAdapter.java:120)
        at com.example.edwardlim.workoutlogs.ExercisesSection$3.onClick(ExercisesSection.java:182)
        at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5257)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)


text:
Q: Is there any equivalent for gluScaleImage function? I am trying to load a texture with non-power-of-two (NPOT) sizes in my application which uses OGLPlus library. So, I use images::Image to load an image as a texture. When I call Context::Bound function to set the texture, it throws an exception. When the size of the input image is POT, it works fine.
I checked the source code of OGLPlus and it seems that it uses glTexImage2D function. I know that I can use gluScaleImage to scale my input image, but it is dated and I want to avoid it. Is there any functions in newer libraries like GLEW or OGLPLUS with the same functionality?

A: It has been 13 years (OpenGL 2.0) since the restriction of power-of-two on texture sizes was lifted. Just load the texture with glTexImage and, if needed, generate the mipmaps with glGenerateMipmap.
EDIT: If you truly want to scale the image prior to uploading to an OpenGL texture, I can recommend stb_image_resize.h — a one-file public domain library that does that for you.


text:
Q: dialogbox in a MFC program i have written the following application using MFC in visual c++ that includes two resources (a menu and a dialogbox) (created using the resource editor)...the program works absolutely fine except that it displays only one resource ie. it displays only the menu but it does not display the dialogbox...
what to do??
this is the code...
#include<afxwin.h>
#include"stdafx.h"
#include"resource.h"

class mydialog:public CDialog
{
private:
    int id;

public:
    mydialog(int n):CDialog(n)
    {
        id=n;
    }

    int OnInitDialog()
    {
        CDialog::OnInitDialog();
        if(id==IDD_DIALOG1)
            CenterWindow(GetDesktopWindow());
        else
            CenterWindow();
        return TRUE;
    }

    void OnOK()
    {
        CDialog::OnOK() ;
        MessageBox(TEXT("You have Pressed the OK Button"),TEXT("OnOK handler"));
    }
};
class myframe:public CFrameWnd
{
public:
    myframe()
    {
        Create(0,TEXT("Simple Dialog Box"),WS_OVERLAPPEDWINDOW,rectDefault,0,MAKEINTRESOURCE(IDR_MENU1));
    }
    void about()
    {
        mydialog d(IDD_DIALOG1);
        d.DoModal();
    }
    DECLARE_MESSAGE_MAP()
};

BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_COMMAND(101,about)
END_MESSAGE_MAP()

class myapp:public CWinApp
{
public:
    int InitInstance()
    {
        myframe *p;
        p=new myframe;
        p->ShowWindow(3);
        m_pMainWnd=p;
        return 1;
    }
};
myapp a;

A: Hey, without compiling the code and running it I can see a problem here:
myframe()
{
    Create(0,TEXT("Simple Dialog Box"),WS_OVERLAPPEDWINDOW,rectDefault,0,MAKEINTRESOURCE(IDR_MENU1));
}

Where you are creating a window using IDR_MENU1 resource which is a menu. This means that the main window of your app is the menu.
Also, the whole code does not look MFC-ish at all. I would suggest creating an MFC app from Visual Studio template - it will set up the main window properly for you.

A: The dialog will only be displayed when the command with id 101 is executed. Presumably this would be a menu item which is associated with the main window. If your menu is defined as:
IDR_MENU1 MENU
BEGIN
    POPUP "HELP"
    BEGIN
        MENUITEM "About",  ID_HELP_ABOUT
    END
END

And ID_HELP_ABOUT is defined with the value 101, then your about function will get called when you select that menu item, showing the dialog.
I'm not sure exactly what you are trying to achieve here, and would echo the other suggestions here by saying to start out with the MFC wizard generated code and take it from there.


text:
Q: Image doesn't show in voyager admin panel Laravel the added images are not showing in the bread of the VOYAGER ADMIN PANEL

Anybody help ?

A: *

*delete storage short-link in public directory if it exists.

*remake a new link with artisan command (php artisan storage:link)

*confirm that the APP_URL={your domain}

*php artisan config:cache

*re-run the server

A: Did you tried this command php artisan storage:link


text:
Q: Error adding array elements to a form: Uncaught SyntaxError: missing ) after argument list I´m working on a academic php/javascript web project and I´m having some problems.
In this project´s arquitecture, data is always sent to the server by POST using 'hidden forms'. This forms are built by the followings functions:
function crearform(name, method){
    var formu = document.createElement('form');
    document.body.appendChild(formu);
    formu.name = name;
    formu.method = method;
    formu.action = 'index.php';
}

function insertacampo(form ,name, value){
    formulario = form;
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = name;
    input.value = value;
    formulario.appendChild(input);
}

function enviaform(form){
    form.submit();
}

A example use:
 <a class="btn-get-started i18n-cancelar" id="btn-cancel" type="button" onclick="
                                        crearform('formenviar','post');
                                        insertacampo(document.formenviar,'document_id', '<?php echo $this->document['document_id'] ?>');
                                        insertacampo(document.formenviar,'controller','ImpDoc');
                                        insertacampo(document.formenviar,'action','show');
                                        enviaform(document.formenviar);">
                                        Return

This works perfectly fine! but for the next step I added a stack so the application can store all the POSTs received. In this way, for the return action I just have to get the last POST of the stack and I already have the params 'controller', 'action' ... availables.
And... here is the problem. The last POST stored on the stack is accessible through a php variable.
var_dump output: Last POST stored
array(2) { ["controller"]=> string(6) "Portal" ["action"]=> string(8) "_default" }

I created a javascript function that receives the array with the POST values and adds them to a 'hidden form'.
function multiple_addfield(form, params) {
    for(let key in params) {
        let input = document.createElement('input');
        input.type = 'hidden';
        input.name = key;
        input.value = params[key];
        form.appendChild(input);
    }
}

And built the form like this:
<a class="btn-get-started i18n-back" type="button" onclick="
                            crearform('formenviar','post');
                            multiple_addfield(document.formenviar, <?php echo json_encode($this->previousShow); ?>);
                            enviaform(document.formenviar);">
                            Volver

But when I click on the button it doesn´t work.
In the firefox console I receive this error:
Uncaught SyntaxError: missing ) after argument list

And in the chrome console:
Uncaught SyntaxError: Unexpected end of input

Inspecting the button element in Chrome:
Volver

Someone could help me?
Thanks!!

A: It would appear this is an issue of mixing php and JavaScript and HTML attribute content, in general when dealing with many different factors it's a good idea to test one thing at a time in order to determine where the error is
For example you are now trying to test a JavaScript function, but instead of only testing it within attribute text, from code generated from a server, maybe first test it with basic JavaScript that you can write yourself to make sure the Javascript works, then if so, try calling the same code from within the attribute manually, and see if it works, and if so then try outputting the server code to static text, then copying it manually and try entering it into the function, then if all of those individual steps work, if you put it all together and still didn't work, at least you know all of the individual parts are good, and the problem is only all together
In this case
Volver

Is simply invalid html, because it contains double quotations within other double quotations without being escaped, which is kind of hard to tell if it's all being generated from the server directly and placed within an attribute
To simply things, instead of outputting the php code into inline JavaScript, try outputting the php into a JavaScript variable that would be defined in a separate script tag, and once you've done that, you can simply reference that JavaScript variable in the inline JavaScript, or better yet, just create a completely custom function in the script tag and simply set the onclick to the name of that function
So for example on the server side you can add somewhere

Volver


text:
Q: Cannot run picovoice on linux alpine I am trying to run picovoice voice detection engine on linux alpine. I am running the python version using the python binding provided by picovoice. I am running the python demo on the linux alpine distribution. I have a docker container running on linux alpine. When I run the command
python demo/python/porcupine_demo.py --keyword_file_paths resources/keyword_files/linux/blueberry_linux.ppn

I see the error
OSError: Error relocating demo/python/../../lib/linux/x86_64/libpv_porcupine.so: __vfprintf_chk: symbol not found

Anyone else faced this situation? Is there a way to run picovoice on alpine or is it not supported at all?

A: It seems libpv_porcupine.so depends on GNU's C runtime library, glibc (judging by the __vfprintf_chk symbol).
Alpine uses a different, minimalistic libc implementation, called musl libc.
Binaries linked against glibc will normally fail to link against musl libc.
You'll need Alpine with glibc - try using a glibc-enabled Alpine as your base image, such as https://github.com/frol/docker-alpine-glibc.


text:
Q: Replace failing LVM disk with root This was my first setup so it's a bit messy. Extremely small root volume (3.9GB) which I'd like to increase but the problem right now is that the disk is failing and I need to replace it.
root@boxboxbox:/data# df -h
Filesystem                         Size  Used Avail Use% Mounted on
udev                               903M     0  903M   0% /dev
tmpfs                              187M  1.1M  186M   1% /run
/dev/mapper/ubuntu--vg-ubuntu--lv  3.9G  3.7G  1.2M 100% /
tmpfs                              934M     0  934M   0% /dev/shm
tmpfs                              5.0M     0  5.0M   0% /run/lock
tmpfs                              934M     0  934M   0% /sys/fs/cgroup
/dev/sdc2                          976M  228M  682M  26% /boot
/dev/mapper/vg01-lv01              5.4T  3.9T  1.3T  77% /data
tmpfs                              187M     0  187M   0% /run/user/1000
/dev/loop0                          94M   94M     0 100% /snap/core/9066
/dev/sdd1                          466G  403G   63G  87% /temp
/dev/loop1                          97M   97M     0 100% /snap/core/9665

root@boxboxbox:/data# sudo lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT,LABEL
NAME                      FSTYPE        SIZE MOUNTPOINT      LABEL
loop0                     squashfs     93.9M /snap/core/9066
loop1                     squashfs       97M /snap/core/9665
sda                                     1.8T
└─sda1                    LVM2_member   1.8T
  └─vg01-lv01             ext4          5.5T /data
sdb                                     1.8T
└─sdb1                    LVM2_member   1.8T
  └─vg01-lv01             ext4          5.5T /data
sdc                                     1.8T
├─sdc1                                    1M
├─sdc2                    ext4            1G /boot
└─sdc3                    LVM2_member   1.8T
  ├─ubuntu--vg-ubuntu--lv ext4            4G /
  └─ubuntu--vg-sdc3       LVM2_member   1.8T
    └─vg01-lv01           ext4          5.5T /data
sdd                                   465.8G
└─sdd1                    ntfs        465.8G /temp

sdc is the one failing and I'd like to replace it with a 4TB drive. The thing is can I just pvmove it or will I mess everything up?

A: You can just pvmove the root file system, that is the easy bit.
What you also need to take care of is booting, because the /boot partition is not inside LVM, which is easier done from a rescue system.


text:
Q: Does Paperclip automatically clean up filenames? I'm using Thoughtbot's Paperclip gem to handle file uploads.
I'm finding that when I upload a file with spaces in the filename, it gets stored with the spaces replaced with underscores.
That's good.
I also tried uploading a file with special characters like ~ and so on and they all got replaced with underscores.
Great. Exactly what I want.
But why is it happening?
All I'm doing in my model is...
has_attached_file(
    file_somefile,
    :path => ":rails_root/public/system/other/path/elements/:basename.:extension"
)

Is this Paperclip's default behavior?

A: OK, after a little more searching, I found this blog post that says, down at the bottom, that Paperclip actually does some minimal processing of filenames.

A: To add a little more information, this happens in Paperclip::Attachment#cleanup_filename in which the default restricted_characters /[&$+,/:;=?@<>[]{}\|\\^~%# ]/ are replaced with underscores.
It's not documented, but you can specify the :restricted_characters option to paperclip to change what gets replaced, e.g.
class User < ActiveRecord::Base
  attr_accessible :avatar
  has_attached_file :avatar, :restricted_characters => /@/ # only replaces '@'
end


text:
Q: Most robust way to store api keys (client side)? I have created a java daemon program that collects data from social network accounts. I use a lot of services including Flick, S3, GeoCoding, etc. Currently I have the program set up to read all these API keys from a properties file. I also have a similarly formatted properties file in my test folder that contains different keys for testing purposes. These property files are not committed to source obviously. This collection program writes to a mongo db. I am also building a web app that also works with mongo and will be deployed along side the collection.  During my development I am reading that it is best to store keys as environment variables on the production side. It got me think; which leads me to my question...
I am wondering if there is a better way to handle these keys in my java program (from a deployment standpoint) or some possible routes that people have tried in doing something similar to this. Can someone shed some light on this?

A: I would recommend a database. If you are only storing API keys for personal use, then the size of the database isn't probably a major concern. Personally, I would suggest MySQL (or alternatively SQLite) as they are both quite well-supported.
If you encrypt your keys then it shouldn't matter too much where you store your database, although of course I still wouldn't make it openly downloadable. Just pick a good encryption tool and do not try developing your own encryption algorithm!

A: The latest hotness (in a world of containers) is to use zookeeper, etcd or consul as a distributed configuration store. The confd tool is capable of ensuring that application configuration files are kept in sync with changes to configuration.
My personal preference is Consul which has a similar template tool called consul-template, and another called envconsul if you would prefer your program to consume environment variables.
Finally Hasicorp, the makers of consul, have an encryption product called vault. It works well with consul and is also supported by consul-template.


text:
Q: Placing TabControl vertically How do I make a Silverlight TabControl arrange the tabs vertically?

A: TabControl Formatting (Right Justified and Vertical Text)
<Controls2:TabControl HorizontalContentAlignment="Right" HorizontalAlignment="Right" TabStripPlacement="Left"></Controls2:TabControl>

A: Make sure you have install the silverlight toolkit and then use the rotate layout to turn the tab header.
<UserControl xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
x:Class="SilverlightApplication18.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Layout.Toolkit"
Width="400″ Height="300″>
<Grid x:Name="LayoutRoot" Background="White">
    <controls:TabControl Margin="10″ TabStripPlacement="Left">
        <controls:TabItem  >
            <controls:TabItem.Header>
                <toolkit:LayoutTransformer >
                    <TextBlock Text="Tab1″/>
                    <toolkit:LayoutTransformer.LayoutTransform>
                        <RotateTransform Angle="-90″></RotateTransform>
                    </toolkit:LayoutTransformer.LayoutTransform>
                </toolkit:LayoutTransformer>
            </controls:TabItem.Header>
            <TextBlock  Margin="10″ Text="some content in Tab1″/>
        </controls:TabItem>

The result will like:
!
May be I can't upload a picture, the result will like this, but all the text is rotated -90 in the real result.
+--+------------------------------
|l |
|a |
|c |
|i |
|t |
|r |
|e |
|v |
+--+
|
|
+--------------------------------

The relative article is here


text:
Q: Prove that $q$ divides (${}_q \mathrm{C}_x$) where $q$ is an odd prime and $x \in \Bbb{Z}$ is such that $1\lt x \lt q$. I believe I need to show that $\frac{q!}{x!(q-x)!} = aq $ where  $a\in \mathbb{Z}$
How can I show this?

A: There is the identity ${n \choose k } = {n \choose n-k}$, which means we may assume without loss of generality that $q - x \leq x$.  Then clearly the fraction is $\dfrac{q(q-1)\cdots (q-x+1)}{(q-x)(q-x-1) \cdots (1)}$.
Since $q$ is a prime number, you cannot write it as a multiple of two proper factors greater than $1$.  Notice that since $q-x \lt q$ (because by assumption $x \gt 1$), the only way to "divide out" the factor of $q$ in the numerator would be to assemble (compositely) $q$ from a number of smaller factors, but this can't be done by our first sentence in this paragraph.
$\square$


text:
Q: Spring Data Rest - Bean Validation is not applied to integer field? I have the following class defined with bean validation annotations.
@Data
@Entity
public class Contact{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Min(value=7,message = "Mobile number must have at least 7 digits")
    private int contactNumber;

    @Min(value=7,message = "Mobile number must have at least 7 digits")
    private int mobileNumber;
}

However when I post the following JSON to the endpoint http://localhost:8080/contacts, it does not throw a constraint violation exception. The post is successful.
{
    "contactNumber": 77,
    "mobileNumber" : 77

}

So how do I fix this validation?


text:
Q: How to resume last activity that was open? I used android:clearTaskOnLaunch="true" for the main activity of my application before. Now I decided to change it to the default behaviour, so I simply deleted this line from manifest. It works as expected when I install the app from Android Studio by usb connection, but when I generate signed apk and install it manually, or download from Google Play, the application works as clearTaskOnLaunch="true" is still active, it is not reverted.
I did try to add clearTaskOnLaunch="false" but that didn't work, so I have no idea how to revert this to default. Thanks for any suggestions.


text:
Q: How do I push a new branch without pulling So I've worked on new features and I realized that it would be too complicated to commit locally to master branch. Thus, I created a new branch as follows:
$ git stash branch project_0.2 stash@{0}

The problem of course is that when I try to push the new branch to the server I get:
$ git push origin master
To https://svn.tudelft.nl/git/project.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://svn.tudelft.nl/git/project.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

I've been looking on the internet and everywhere I see that I should git pull and merge the changes. I tried this (before I made a backup), and I get:
$ git pull
remote: Counting objects: 1105, done.
remote: Compressing objects: 100% (304/304), done.
remote: Total 725 (delta 501), reused 552 (delta 382)
Receiving objects: 100% (725/725), 5.29 MiB | 0 bytes/s, done.
Resolving deltas: 100% (501/501), completed with 165 local objects.
From https://svn.3me.tudelft.nl/git/project
   5d6516c..fd424b5  master     -> origin/master
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.

    git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

    git branch --set-upstream-to=origin/<branch> project_0.2

I'm not sure what I should do here so I stopped. Also, the changes are so deep that it will take me forever to merge. I thought there may be a smarter way to just push the branch to the server. In this way, I can get help from the other members of my team in fixing the code. Is this possible?

A: Create new branch first using
git checkout -b NewBranchName

It will create a new branch on your local machine, now push this new branch.
git push origin NewBranchName

A: If you want to isolate your new features from what you have been doing in your master branch, you have to do what @UniCoder says. Create a new branch with:
git branch NewBranchName

Activate it with:
git checkout -b NewBranchName

Do your developments, Add the objects you need, commit the work you have done on this feature and then create the new branch as:
git push origin --set-upstream NewBranchName

For later pushes you only have to put "git push origin"


text:
Q: I killed Petrus, what do I do now? I found out that Petrus, the guy who sells miracles in firelink, will kill the other miracle trainer. I had just started my paladin playthrough and so decided to buy out all the miracles I didnt have and then kill him, my reasoning being that when the other trainer appears I could continue to buy Miracles without worry, but now that she and her bodyguards have appeared they attack me.
Is there a way to stop them attacking me?
Ps. I just tried to absolve my sin with the guy at the bell tower. 20,000 souls and they still attack me.
Pps. Yeah so i just restarted it and haven't had any problems since.an annoying setback though it is i cant see a way around it.
Thanks to both who answered, you tried your hardest to help and i respect that. Your some cool dudes. (Or dudettes)

A: The reason that the other NPCs are attacking you is because you killed "another member of their order".
Normally, going to Oswald to "absolve your sins" should clear the slate, but I'm not sure why or if this should have worked.
Petrus has his own story line with the other three NPCs. Once you collect the Lordvessel, they will venture into the Tomb of the Giants, and get trapped. You can find them, kill the two guards (as they have gone hollow), then Reah will return to the Undead Chapel.
She will stay there for a short time (2 or 3 bosses), so you can buy miracles from her then. After that Petrus will kill her.
Source
The issue is that you unfortunately killed Petrus too early, so you have unfortunately ruined the story line for these characters. Ideally, you should kill Petrus after you rescue Reah from the Tomb of the Giants.
Unfortunately, I believe that since you killed Petrus before they arrived, they will be permanently aggro'd. The only way to resolve this is start the game over or enter ng+; or kill them.

A: You can make this NPC friendly again - you need to request an Absolution from Oswald of Carim.
Or you can just continue your game as is. Some Miracles are indeed only available from this NPC, but there are many others you can find somewhere else, see Miracles. And if you want to collect all of them, you can always go to New Game Plus and complete your collection there.


text:
Q: Incorrect SUM of column from JOINed table occurs when JOINing another table I want to get every record from table ProductItem, and for each of them, get the summation of field units_in_stock from the table ProductAttrsInfo, with the main table joined to some parent and child tables.
The complete fields I want to retrieve are:

*

*ProductItem.id AS product_item_id

*ProductItem.name AS product_item_name

*SUM(ProductAttrsInfo.units_in_stock) AS units_in_stock

*IFNULL(SUM(TransOrderItem.quantity), 0) AS total_ordered_items
Of course, to get total_ordered_items, I need to join with TransOrderItem, but when I join it, the sum results are incorrect.
Here is the diagram of the table relation:
  +-----------+
  |ProductType|
  +-----+-----+
        | 1-M
        v
 +--------------+       +----------+
 |ProductSubtype|       |TransOrder|
 +------+-------+       +-----+----+
        | 1-M                 | 1-M
        v                     v
  +-----------+       +--------------+
  |ProductItem|       |TransOrderItem|
  +-----+-----+       +-------+------+
        | 1-M                 | 1-M
        v                     |
  +-----------+               |
  |ProductAttr|<--------------+
  +-----+-----+
        | 1-1
        v
+----------------+
|ProductAttrsInfo|
+----------------+

Here is the query without joining table TransOrderItem:
SELECT
    ProductSubtype.id AS product_subtype_id,
    ProductItem.id AS product_item_id,
    ProductItem.name AS product_item_name,
    SUM(ProductAttrsInfo.units_in_stock) AS units_in_stock
FROM
    product_items AS ProductItem
LEFT JOIN product_attrs AS ProductAttr ON
    ProductItem.id = ProductAttr.product_item_id
LEFT JOIN product_attrs_infos AS ProductAttrsInfo ON
    ProductAttr.id = ProductAttrsInfo.product_attr_id
RIGHT JOIN product_subtypes AS ProductSubtype ON
    ProductSubtype.id = ProductItem.product_subtype_id
RIGHT JOIN product_types AS ProductType ON
    ProductType.id = ProductSubtype.product_type_id
GROUP BY
    ProductItem.id
ORDER BY
    ProductSubtype.id ASC,
    ProductItem.id ASC

The results of above query, which is correct:
    +------------------------------------------------------------------------------+
    | product_item_id | product_item_name                         | units_in_stock |
    +------------------------------------------------------------------------------+
    |               1 | Kaos Pria O-Neck                          |           6935 |
    |               2 | Kaos Pria Two-Tone                        |           1999 |
    |              10 | Kaos Pria - Gildan 63000 Soft Style       |           1163 |
    |              30 | Kaos Pria | Gildan 64V00 - VNeck          |             48 |
    |              31 | Kaos Pria - Gildan 76400 - Lengan Panjang |            522 |
    |             130 | Kaos Pria V-Neck                          |            574 |
    |             ... | ...                                       |            ... |
    +------------------------------------------------------------------------------+

Here is the query with the TransOrderItem table joined:
SELECT
    ProductSubtype.id AS product_subtype_id,
    ProductItem.id AS product_item_id,
    ProductItem.name AS product_item_name,
    SUM(ProductAttrsInfo.units_in_stock) AS units_in_stock,
    IFNULL(SUM(TransOrderItem.quantity), 0) AS total_ordered_items
FROM
    product_items AS ProductItem
INNER JOIN product_attrs AS ProductAttr ON
    ProductItem.id = ProductAttr.product_item_id
INNER JOIN product_attrs_infos AS ProductAttrsInfo ON
    ProductAttr.id = ProductAttrsInfo.product_attr_id
LEFT JOIN trans_order_items AS TransOrderItem ON
    ProductAttr.id = TransOrderItem.product_attr_id AND
    (TransOrderItem.created BETWEEN '2017-12-01' AND '2017-12-31') AND
    EXISTS (
        SELECT 1 FROM trans_orders AS TransOrder
        WHERE
            TransOrderItem.trans_order_id = TransOrder.id AND
            TransOrder.status = 'TRS_SHP_FNS'
    )
INNER JOIN product_subtypes AS ProductSubtype ON
    ProductSubtype.id = ProductItem.product_subtype_id
INNER JOIN product_types AS ProductType ON
    ProductType.id = ProductSubtype.product_type_id
GROUP BY
    ProductItem.id
ORDER BY
    ProductSubtype.id ASC,
    ProductItem.id ASC

The results of above query, which has incorrect units_in_stock sums:
    +-----------------+-------------------------------------------+----------------+
    | product_item_id | product_item_name                         | units_in_stock |
    +------------------------------------------------------------------------------+
    |               1 | Kaos Pria O-Neck                          |          51285 |
    |               2 | Kaos Pria Two-Tone                        |           6175 |
    |              10 | Kaos Pria - Gildan 63000 Soft Style       |           9532 |
    |              30 | Kaos Pria | Gildan 64V00 - VNeck          |             48 |
    |              31 | Kaos Pria - Gildan 76400 - Lengan Panjang |           3047 |
    |             130 | Kaos Pria V-Neck                          |            937 |
    |             ... | ...                                       |            ... |
    +-----------------+-------------------------------------------+----------------+

Is there any wrong operation in my query that results in the incorrect sum? The correct query with the explanation will be accepted as the answer. Thank you.
--
EDITED: Added table structures:
`product_attrs` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `product_item_id` int(10) unsigned NOT NULL DEFAULT '0',
  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_product_attrs_product_items` (`product_item_id`),
  CONSTRAINT `fk_product_attrs_product_items` FOREIGN KEY (`product_item_id`) REFERENCES `product_items` (`id`)
)

`product_attrs_infos` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `product_attr_id` int(10) unsigned NOT NULL DEFAULT '0',
  `units_in_stock` int(10) NOT NULL DEFAULT '0',
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `product_attr_id` (`product_attr_id`),
  CONSTRAINT `fk_product_attrs_info_product_attr_id` FOREIGN KEY (`product_attr_id`) REFERENCES `product_attrs` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
)

`product_items` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT '',
  `product_subtype_id` int(10) unsigned NOT NULL DEFAULT '0',
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `product_subtype_id` (`product_subtype_id`),
  CONSTRAINT `product_items_ibfk_1` FOREIGN KEY (`product_subtype_id`) REFERENCES `product_subtypes` (`id`)
)

`trans_orders` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `status` enum('TRS_OPN','TRS_PAID','TRS_RFD','TRS_EXPR','TRS_INPROCESS','TRS_SHP_OPN','TRS_SHP_FNS','TRS_HOLD') DEFAULT 'TRS_OPN',
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
)

`trans_order_items` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `trans_order_id` int(10) unsigned NOT NULL,
  `product_attr_id` int(10) unsigned NOT NULL DEFAULT '0',
  `status` enum('TRS_OPN','PRNT_OPN','PRNT_FNS','QA_OPN','QA_PASS','QA_FAIL','PRNT_FAIL_OPN','PRNT_FAIL_FNS') NOT NULL DEFAULT 'TRS_OPN',
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_trans_order_items_trans_order_id` (`trans_order_id`),
  KEY `fk_to_items_product_attr_id` (`product_attr_id`),
  CONSTRAINT `fk_to_items_product_attr_id` FOREIGN KEY (`product_attr_id`) REFERENCES `product_attrs` (`id`),
  CONSTRAINT `fk_trans_order_items_trans_order_id` FOREIGN KEY (`trans_order_id`) REFERENCES `trans_orders` (`id`)
)

A: You need to calculate quantity from total_ordered_items in separate sub-clause and then do a left join with your main query, to avoid such issue
SELECT
    st.id AS product_subtype_id,
    i.id AS product_item_id,
    i.name AS product_item_name,
    SUM(ai.units_in_stock) AS units_in_stock,
    IFNULL(oi.total_ordered_items, 0) AS total_ordered_items
FROM
    product_items AS i
INNER JOIN product_attrs AS a ON
    i.id = a.product_item_id
INNER JOIN product_attrs_infos AS ai ON
    a.id = ai.product_attr_id
INNER JOIN product_subtypes AS st ON
    st.id = i.product_subtype_id
INNER JOIN product_types AS t ON
    t.id = st.product_type_id
LEFT JOIN (
    SELECT toi.product_attr_id,
           SUM(toi.quantity) total_ordered_items
    FROM trans_order_items as toi
    WHERE toi.created BETWEEN '2017-12-01' AND '2017-12-31'
    AND EXISTS (
        SELECT 1
        FROM trans_orders AS o
        WHERE toi.trans_order_id = o.id
        AND o.status = 'TRS_SHP_FNS'
    )
    GROUP BY toi.product_attr_id
) as oi ON a.id = oi.product_attr_id
GROUP BY
    st.id,
    i.id,
    i.name
ORDER BY
    st.id ASC,
    i.id ASC


text:
Q: emacs beginning-of-buffer slow I began experiencing a couple of days ago a very slow beginning-of-buffer command in emacs, especially with long files (60k+ lines). Oddly, using goto-line 1 or even end-of-buffer operate normally.
How can I troubleshoot this problem?
Thanks!


text:
Q: Mass text manipulation? I have a text file of a couple of hundred thousand words. E.g.:
word1
word2
etc

I want to know what program I can use to easily:

*

*Add "FRONT" to the front of the text, and

*Add "BACK" to the end of the text

So I would end up with:
FRONTword1BACK
FRONTword2BACK
FRONTetcBACK

I can easily do this by coding it in PHP, but I want to know if there is a faster way, with the correct tool? Perhaps this can be done in something like notepad++, or scite, or worst case scenario, linux command line.
Note: I would prefer a WINDOWS based visual editor.

A: In NotePad++ do a regular expression replace:

Find what: ^(.*)$
Replace with: FRONT\1BACK

What's going on in regex terms?
^ - matches start of line
$ - matches end of line
.* - matches everything in between (in brackets to mark it as a group)
The replace is simply what you want to pre and post fix and the value of the first regex group (ie everything on the line) sandwiched in the middle.

A: VIM works on Windows. If you never used it you may have problems starting, but if you learn the basics all the magic is available.
1) Add something in front of first character in every line:

*

*Go to first line, first column.

*Ctrl+v Ctrl+q to enter visual block mode.

*Ctrl+g to go to last line.

*Shift+i to enter visual inserting mode.

*Enter the text and press Esc. Text should appear in all lines.

2) Add something at the end. If all words have same length you can do as described above. If not use macros.

*

*Go to first line.

*Press 'q' twice. First starts recording, second chooses a buffer to record to (can be any letter).

*Shift+a to start inserting text at the end of the line.

*Type desired text.

*Esc to stop inserting.

*Down arrow or 'j' to go to next line.

*'q' again to stop recording.

*Now you can replay recorded action typing '@@' or '@q'. '@@' replays last record, '@q' replays the one under 'q' buffer (same thing in this example).

*Type '1000@@' to replay macro 1000 times.


text:
Q: Simple HTML DOM Parser PHP I am trying to select a particular part of a html page using 'Simple HTML DOM Parser'.
My code so far works but it returns the complete text which is great, but I only want to display the single P BARCODE[pb] line.
My (working) PHP code is as follows;
$homepage = file_get_html('http://example.com/SomeTextPage');

foreach($homepage->find('text') as $element)
       echo $element->innertext . '
'; // line 29

This returns the following on my page (this is the view source display);

EXP DATE[p43]=12-31-97

PCODE1[p44]=-

PCODE2[p45]=-

PCODE3[p46]=0

P TYPE[p47]=1

TOT CHKOUT[p48]=56

TOT RENWAL[p49]=17

CUR CHKOUT[p50]=3

HOME LIBR[p53]=0000

PMESSAGE[p54]=

MBLOCK[p56]=-

REC TYPE[p80]=p

RECORD #[p81]=110220

REC LENG[p82]=1126

CREATED[p83]=01-09-97

UPDATED[p84]=06-05-97

REVISIONS[p85]=139

AGENCY[p86]=1

CL RTRND[p95]=0

MONEY OWED[p96]=$1.35

BLK UNTIL[p101]=  -  -

CUR ITEMA[p102]=0

CUR ITEMB[p103]=0

PIUSE[p104]=0

OD PENALTY[p105]=0

ILL CHKOUT[p122]=3

PATRN NAME[pn]=Jackson, Richard

ADDRESS[pa]=322 San Diego St

ADDRESS2[ph]=El Cerrito, CA 99999

TELEPHONE[pt]=510-555-1212

UNIV ID[pu]=111111111

P BARCODE[pb]=21913000482538

I suppose I need to select the 32nd
 line or more importantly the [P BARCODE[pb]] line - is this possible?
The [P BARCODE[pb]] line isn't always the 32nd line, but the [P BARCODE[pb]] text never changes.
Perhaps I am approaching this the wrong way?
Any help or suggestions are welcome.

A: It doesn't work like that, wrap every line of text in a  so you can access them individually.
Apperantly there is another option, I'd like to refer to this answer

A: $var = $element->innertext;
$array = explode('
', $var);
echo $array[31];

A: Would you like to try to use regexp?
$subject = 'P BARCODE[pb]=21913000482538
';
$pattern = '/P\sBARCODE\[pb\]=([0-9]*)
/';
preg_match($pattern, $subject, $matches);
print_r($matches);


text:
Q: Sum the series to 'n' Just trying to sum the series 1/(1 + 3n) for a given n.  I've used the code below and get an "invalid syntax" message, but I can't understand why as other examples seem to do the same. Returning a value rounded to two decimal places
def series_sum(n):
    ans = 0
    for i in range(0, n+1):
        ans = ans + (1/(1+3i))
    return round(ans, 2)

A: just do :
def series_sum(n):
    ans = 0
    for i in range(0, n+1):
        ans = ans + (1.0/(1.0+3.0*i))
    return round(ans, 2)

you should use * for multiplication and have float in your equation to get your result as float.
Also the indentation is really important in python.

A: Here is an identation corrected version of your code showing the error
$ cat d.py
def series_sum(n):
    ans = 0
    for i in range(0, n+1):
        ans = ans + (1/(1+3i))
    return round(ans, 2)

$ pyflakes d.py
d.py:4:28: invalid syntax
        ans = ans + (1/(1+3i))
                           ^

And here is how to fix it
def series_sum(n):
    ans = 0
    for i in range(0, n+1):
        ans = ans + (1/(1+3*i))
    return round(ans, 2)

Writing "3i" is not valid syntax for "3 times i" so use the * operator to multiply
$ python
Python 3.5.3 (default, Jun 22 2017, 11:09:36)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from d import series_sum
>>> series_sum(2)
1.39


text:
Q: How to get file_id from StickerSet in pyrogram? To send sticker with pyrogram I need to use:
await message.reply_sticker(sticker_file_id)

So I need get random file_id of sticker pack to send sticker.
sticker_set = await client.invoke(
    GetStickerSet(
        stickerset=InputStickerSetShortName(short_name="HotCherry"),
        hash=0
    )
)

sticker = random.choice(sticker_set.documents)
print(sticker)

But I have sticker object without file_id:
{
    "_": "types.Document",
    "id": 1391391008142393351,
    "access_hash": -4097529056751820472,
    "file_reference": "b'\\x00c\\xaf.7.O3 \\x04\\x81\\xf00y\\xbd\\x82\\x1bV\\x7f\\xc8n'",
    "date": 1561820428,
    "mime_type": "application/x-tgsticker",
    "size": 9526,
    "dc_id": 2,
    "attributes": [
        {
            "_": "types.DocumentAttributeImageSize",
            "w": 512,
            "h": 512
        },
        {
            "_": "types.DocumentAttributeSticker",
            "alt": "",
            "stickerset": {
                "_": "types.InputStickerSetID",
                "id": 1391391008142393345,
                "access_hash": 3354279076546271904
            },
            "mask": false
        },
        {
            "_": "types.DocumentAttributeFilename",
            "file_name": "AnimatedSticker.tgs"
        }
    ],
    "thumbs": [
        {
            "_": "types.PhotoPathSize",
            "type": "j",
            "bytes": "b'\\x14\\x05\\xae\\t\\xdc|\\x81K\\x08NO\\t|F\\x06G\\x05jS\\x00\\xabW\\t\\x93K\\xaaR\\x86\\x04U\\x86\\x81\\x8d\\x81\\x92A\\x85C\\x86W\\x86[\\x80]Qum|DAgBaM\\x81C\\x86F\\x88H\\x9f`\\x87\\x02\\x8a\\x88\\x08\\xa5\\x86\\x8b\\x98\\x86\\x08\\x9c\\x87\\x01\\x8d\\x8b\\x9e\\x8a\\xaf\\x8f\\xa4\\x8b\\x86\\x06\\xa1\\x88\\x05\\x86\\x06\\xbe\\x8a\\t_\\x98\\x02O\\x00\\x98\\x00'"
        },
        {
            "_": "types.PhotoSize",
            "type": "m",
            "w": 128,
            "h": 128,
            "size": 4218
        }
    ],
    "video_thumbs": []
}

How I can send random sticker from sticker pack if I know only sticker pack name(sticker_set)?

A: Thanks, to @Muhammadyusuf answer in comment I solve this problem by using this code(which is not recommended as is using protected method):
from pyrogram.types import Sticker
from pyrogram import raw, Client, errors

bot = Client(...)

async def parse_a_pack(shortName):
    try:
        info = await bot.invoke(raw.functions.messages.GetStickerSet(stickerset=raw.types.InputStickerSetShortName(short_name=shortName),hash=0))
    except errors.StickersetInvalid:
        return []

    documents = info.documents
    final = []
    for stk in documents:
        sticker = await Sticker._parse(bot, stk, {type(i): i for i in stk.attributes})
        final.append(sticker)
    return final


text:
Q: Cannot import XLSX file I am trying to import an XLSX file into R to begin my class project. It is giving me issues, as it returns a result with 0 variables. I have tried to rework the pathway to the file multiple times with no different result. Anyone have an idea of what I'm doing wrong?
My input:
customer_data <- fread("~C:\\matly\\Desktop\\Grad School\\Class 4\\Customer.xlsx", stringsAsFactors=FALSE)

The output:
The filename, directory name, or volume label syntax is incorrect.
Warning messages:
1: In (if (.Platform$OS.type == "unix") system else shell)(paste0("(",  :
  '(~C:\matly\Desktop\Grad School\Class 4\Customer.xlsx) > C:\Users\matly\AppData\Local\Temp\RtmpGs4FDg\file434f8231' execution failed with error code 1
2: In fread("~C:\\matly\\Desktop\\Grad School\\Class 4\\Customer.xlsx",  :
  File 'C:\Users\matly\AppData\Local\Temp\RtmpGs4FDg\file434f8231' has size 0. Returning a NULL data.table.

A: At least two issues here:

*

*you have a bogus-looking tilde (~) at the beginning of your file name

*data.table::fread() reads "delimited" files (i.e., space or whitespace or tab or comma-separated), not XLSX files

Try e.g.
readxl::read_excel("C:/matly/Desktop/Grad School/Class 4/Customer.xlsx")

Other style points:

*

*read_excel automatically uses stringsAsFactors=FALSE; it returns a "tibble", which is almost (but not quite!) the same as a data frame

*using / as a path separator works cross-platform and is a little easier to read

*I'd strongly encourage you to change your working directory and use relative path names, e.g.

setwd("C:/matly/Desktop/Grad School/Class 4/")
readxl::read_excel("Customer.xlsx")


text:
Q: How do I access Rundeck Job execution number inside script? Similar to accessing job options like:
#!/bin/bash
my_var=@option.my_var@

is there a way to access general job execution properties?
Specifically, I am deploying a docker container and would like to leverage the execution number to inject a link back to the rundeck job execution that was responsible for deploying said container

A: For that use
echo @job.execid@

You can see all options putting @job. in the inline script and Rundeck shows you all the options (autocomplete).


text:
Q: hibernate count distinct values I try to do something like
SELECT count(*) from (select distinct(col1, col2) from table);

using hibernate and mysql.
I know that I can't use subqueries in FROM clause.
Is there any way except query.list().size() or native sql?
Thanks


text:
Q: How to make CharSink respect file permissions? I would expect exception to be thrown in this code at line: charSink.write("hi world");  since the file is set to be non writable. But this code executes without any exceptions. How to make CharSink respect file permissions?

public class CharSinkWritingNonWritableFile {
    public static void main(String[] args) throws Exception {

        final File file = getNewFile();

        file.setWritable(false, false);

        val charSink = Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);

        file.setWritable(false, false);

        charSink.write("hi world");

        Files.readLines(file, Charsets.UTF_8).forEach(line -> {
            System.out.println(line);
        });

    }

    private static File getNewFile() {

        final File file = new File("/tmp/hi-world");
        if (file.exists()) {
            file.delete();
        }
        return file;
    }
}

Edit:
OS: MacOS 12.4


text:
Q: How can I insert the original matched pattern (OLD STRING) into the result (NEW STRING) Using Microsoft Word's Find/Replace Feature? Microsoft Word's find/replace feature seems like it is many-to-one.
Suppose that we have a word document numbers surrounded by parentheses, such as (6)
and we want to remove the parentheses and place a dot at the end, such as 6.
Suppose we open up find/replace. We then enter in the following options:
FIND WHAT:     (^#)
REPLACE WITH:  5.

The above will have the following effect:
.--------.-------.
| BEFORE | AFTER |
.--------.-------.
| (1)    | 5.    |
.--------.-------.
| (2)    | 5.    |
.--------.-------.
| (3)    | 5.    |
.--------.-------.
| (4)    | 5.    |
.--------.-------.

How can we insert the matched pattern in the output/result?
I want to do something like this:
##             (5)
##             becomes
##             AAAA(5).1234

FIND WHAT:     (^#)
REPLACE WITH:  AAAA^MATCHED_PATTERN.1234

##             AAAA(5).1234
##             becomes
##             5).1234

FIND WHAT:     AAAA(
REPLACE WITH:

##             5).1234
##             becomes
##             5.

FIND WHAT:     ).1234
REPLACE WITH:

A: I don't really understand your examples, so I'm not sure if this is what you're asking, but if you want to make it 5. you would do find (5) replace with 5.

A: Rather than separate find and replaces as shown in your example above to delete the brackets, you can instead do a wildcard find and replace. The trick is to separate out the parts - for the find, the first part is the opening round bracket, the second part is any digit(s), and the third part is the closing round bracket. Then in your replace, you just keep the second part and add the full stop.
A part in the find is enclosed in round brackets.
For the "range" of characters to search for, enclose them in the square brackets.
The / is to "escape" the special character so you can search for the opening and closing round brackets.
So the find is: ([/(])([0-9]@)([/)])
And the replace is:  \2.
Remember to select the option for Use wildcards.
This will find (5) or (11) for example, and replace with 5. and 11. respectively.


text:
Q: Change UniformGrid child item during runtime I'm currently trying to populate a UniformGrid in WPF.
Some context: I'm trying to build a 2D Sidescroller (I know, WPF is not the best solution to that and I should use Unity or something else. I'd like to try it though). Now, for the map I was thinking about using a UniformGrid and using the children as tiles for my map.
So far, I'm adding empty children to the UniformGrid using this piece of code:
private void CreateMapTiles() {
    for (int i = 0; i < 30; i++) {
        for (int j = 0; j < 45; j++) {
            this.MapGrid.Children.Add(new Image());
        }
    }
}

Where MapGrid is my UniformGrid.
So, in the end, I want to have 30x45 children.
Now I want to dynamically edit those children in CodeBehind, i.e. make those children an image. Or put another way, I want to update, let's say, the child at index 5 to display another image from my resources, than it did before.
I was thinking about using something like this:
this.MapGrid.Children[1] = new Image() { Source = ReturnSomeSource() };

But for obvious reasons, this doesn't work.
Is there any way i can assign a value to the children during runtime?
I've also played around with this.MapGrid.Children[1].SetCurrentValue() a bit, but neither did I really understand what I was doing, nor did it work in any way.
Does the possibility even exist, to change the UniformGrid children during runtime?
Would a normal Grid do a better job? I wanted to avoid that, because the UniformGrid children are arranged and sized automatically the way i need them without any more effort.

A: Rather than replacing Imagewith a new Image, change the source on the already existing image.
var tileImage = this.MapGrid.Children[1] as Image;
tileImage.Source = ReturnSomeSource();


text:
Q: HybridAuth "Tiny Social Hub" example redirecting to /hybridauth/?hauth.start=Facebook&hauth.time I'm trying to figure out how HybridAuth works. I've installed it on my server as per instructions, added my developer key for Facebook, Google etc, however when i go to the "Tiny Social Hub" example:
www.mysite.org/inc/examples/social_hub/login.php

and click "Sign-in with Facebook", i get redirected to:
www.mysite.org/inc/hybridauth/?hauth.start=Facebook&hauth.time=1362314218

Similar with "Sign-in with Google":
www.mysite.org/inc/hybridauth/?hauth.start=Google&hauth.time=1362314279

And i just see the directly listing of /inc/hybridauth/ which includes:
index.php
config.php
Hybrid/

What am i missing?

A: I was able to solve this. For anyone who might run into this problem, the fix was based on a response to the question Hybrid auth with Yii causing a redirect loop, specifically the following point:

Your base_url in configuration file "hybridauth.php" should be set to "/hauth/endpoint" i.e. it must point to the endpoint. If you have removed index.php through .htaccess then use "/index.php/hauth/endpoint".

I needed to adjust my base url from:
"base_url" => "http://mysite.org/inc/hybridauth/"

to:
"base_url" => "http://mysite.org/inc/hybridauth/index.php"

My guess is that the first url would work in most instances because index.php is usually the default directory page. Whereas I've configured Apache to use home.php on my server.

A: Assuming you're using Apache, another solution would have been for you to tell it to recognize index.php as an index file.
Add the following in the relevant /etc/(httpd|apache2)/sites.enabled/ or httpd.conf file

DirectoryIndex index.php

Or, assuming apache is configured to allow .htaccess files, simply create an .htaccess file and put the above line in there.


text:
Q: ¿Como reconectar un cliente wasync (atmosphere) cuando cae el servidor? Estoy desarrollando un proyecto para el que debo implementar notificaciones PUSH con un servidor atmosphere. Para ello estoy utilizando un cliente wasync. En el proyecto original, se trata de un cliente Android, sin embargo he aislado tanto el código del servidor como el del cliente para aíslar la problemática.
El problema en sí, tal como indico en el título, es que cada vez que hay una caída de conexión con el servidor (por el motivo que sea), el cliente no reconecta.
Pila de software:

*

*Servidor: Atmosphere 2.4.2

*Servidor: Jersey 1.19

*Tomcat 7.0.62

*Cliente: wasync 2.1.2

Para el envío de notificaciones estoy utilizando el modelo de canales @Subscribe / @Publish proporcionado por Atmosphere. Aunque también he probado con el modelo @Suspend / @Broadcast y tampoco me ha funcionado.
Servidor
@Path("metallica")
public class MetallicaService {

    @GET
    @Path("/suscripcion")
    @Subscribe(value = "metallica", timeout = -1)
    public String handshake() {
        return null;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Track getTrackInJSON() {

        Track track = new Track();
        track.setTitle("Enter Sandman");
        track.setSinger("Metallica");

        return track;

    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Publish("metallica")
    public String createTrackInJSON(Track track) {

        String result = "Metallica -- Track saved : " + track;
        //return Response.status(201).entity(result).build();
        return result;

    }
}

Cliente
public class MetallicaClient {

    public static void main(String[] args) {

        final Client client = ClientFactory.getDefault().newClient();

        final RequestBuilder request = client.newRequestBuilder()
                .method(Request.METHOD.GET)
                .uri("http://localhost:8080/metallica/suscripcion")
                .encoder(new Encoder<String, Reader>() {        // Stream the request body
                    @Override
                    public Reader encode(String s) {
                        System.out.println("Encode: " + s);
                        return new StringReader(s);
                    }
                })
                .decoder(new Decoder<String, Reader>() {
                    @Override
                    public Reader decode(Event type, String s) {
                        if (type.equals(Event.MESSAGE)) {
                            System.out.println("---- Message received ----");
                            System.out.println("---- Date and time: " + Calendar.getInstance().getTime().toString() + " ----");
                        }
                        System.out.println("Decode: " + s);
                        return new StringReader(s);
                    }
                })
                .transport(Request.TRANSPORT.WEBSOCKET)                        // Try WebSocket
                .transport(Request.TRANSPORT.LONG_POLLING);                    // Fallback to Long-Polling

        final OptionsBuilder<DefaultOptions, DefaultOptionsBuilder> clientOptions = client.newOptionsBuilder()
                .reconnect(true)
                .reconnectAttempts(10)
                .pauseBeforeReconnectInSeconds(10);

        final Socket socket = client.create(clientOptions.build());

        try {
            socket.on("message", new Function<String>() {
                @Override
                public void on(String s) {
                    System.out.println("Respuesta: " + s);
                }
            }).on(new Function<IOException>() {

                @Override
                public void on(IOException e) {
                    e.printStackTrace();
                }
            }).on(Event.CLOSE.name(), new Function<String>() {

                @Override
                public void on(String s) {
                    System.out.println("Se ha perdido la conexión con el servidor.");
                }
            }).on(Event.REOPENED.name(), new Function<String>() {

                @Override
                public void on(String s) {
                    System.out.println("Reconexión.");
                }
            }).open(request.build());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Del cliente me gustaría destacar el siguiente bloque de código, en el que se supone que estoy configurando la reconexión (aunque en algún punto debo estar metiendo la pata):
    final OptionsBuilder<DefaultOptions, DefaultOptionsBuilder> clientOptions = client.newOptionsBuilder()
            .reconnect(true)
            .reconnectAttempts(10)
            .pauseBeforeReconnectInSeconds(10);

    final Socket socket = client.create(clientOptions.build());

Para facilitar el trabajo, he creado un proyecto en github: https://github.com/hecnabae/jerseyAtmosphere

A: Dos cosas que he visto en la documentación:
Puedes probar a crear el cliente utilizando la clase especifica para tu protocolo de la forma:
AtmosphereClient client = ClientFactory.getDefault().newClient(AtmosphereClient.class);

La otra cosa que he visto es que el método reconnect(boolean) restablece la conexión si es cerrada por el servidor, pero el método reconnect() hace lo mismo que el anterior y también si existe un fallo de red
No se si esto sera la solución pero es curioso que la documentación detalle la direfencia entre los dos métodos


text:
Q: ERROR 2026 (HY000): SSL connection error: Unable to get private key I need help with mysql replication with ssl. I got a problem when i'm turn on ssl on my slave - error connecting to master 'replica@1.2.3.4:3306' - retry-time: 60  retries: 1
Here is my setup
Master
mysql> show variables like "%ssl%";
+---------------+--------------------------------------+
| Variable_name | Value                                |
+---------------+--------------------------------------+
| have_openssl  | YES                                  |
| have_ssl      | YES                                  |
| ssl_ca        | /etc/mysql/ssl-mysql/ca-cert.pem      |
| ssl_capath    |                                      |
| ssl_cert      | /etc/mysql/ssl-mysql/server-cert.pem |
| ssl_cipher    |                                      |
| ssl_key       | /etc/mysql/ssl-mysql/server-key.pem  |
+---------------+--------------------------------------+

Certs created on Gentoo with OpenSSL 1.0.2d    2015-07-09
Here's the interesting part. if I connect from Ubuntu 12.04 client instance specifying a client key, I get the standard error:
$ mysql -h 1.2.3.4 --ssl-ca=/etc/mysql/ssl-mysql/ca-cert.pem --ssl-cert=/etc/mysql/ssl-mysql/client-cert.pem --ssl-key=/etc/mysql/ssl-mysql/client-key.pem -u root -p
Enter password:
ERROR 2026 (HY000): SSL connection error

In logs
SSL error: Unable to get certificate from '/etc/mysql/ssl-mysql/client-cert.pem'
[ERROR] Slave I/O: error connecting to master 'replica@1.2.3.4:3306' - retry-time: 60  retries: 1, Error_code:2026

However, if I only specify the CA certificate and do not specify a client key or certificate, I can connect correctly with SSL:
mysql -h 1.2.3.4 --ssl-ca=/etc/mysql/ssl-mysql/ca-cert.pem -u replica -p

mysql> \s
--------------
mysql  Ver 14.14 Distrib 5.6.27, for Linux (x86_64) using  EditLine wrapper

Connection id:      6873
Current database:
Current user:       replica@1.2.3.5
SSL:            Cipher in use is DHE-RSA-AES256-SHA

A: You are trying to connect to the remote host using the server file of the master.
The reason it is working with only the CA is presumably the SSL configuration on the slave has it's own certificate signed by the same CA.
What you seem to be trying to do is use client certificate authentication.  If that is the case you need an additional client certificate that is recognised on the slave to be used as the certificate you use when trying to do a client connection.
IN simple terms, the server-cert is used to provide the SSL negotiation and is provided by the server to clients to allow the clients to encrypt their traffic in a way that the server can decrypt.
Each server would have its own server-cert that identifies its hostname and allows clients to connect and verify they are connecting to the expected server.
A client certificate is normally a separate certificate and is unrelated to the server certificate on either the master or the slave.


text:
Q: Can I configure Unity search result behavior? I wanted to ask if it were possible to configure the unity search results in this way:

*

*installed programs are always shown expanded.

*programs "ready for installation" are removed and not included in the search.

I am sure ŕemoving the search and display for not installed programs will speed up the search and save valuable screenspace (I'm on a Dell Mini here).
Why installed programs aren't shown in the first place is a mystery to me.

A: Both of these are currently unconfigurable in Unity in 11.10 and 11.04, sorry.


text:
Q: How to convert the CODEC : AAC to AIFF in cocoa application? I'm exporting the audio file(AIFF) from .mov using AVExportSession. The movie format is in AAC codec
format. I would like to convert and write the audio file in AIFF Codec format ( i.e AAC codec to AIFF).
I have tried to implement using AVExportSession but it's not helpful.
Please anyone advice on the API to implement the conversion of codec AAC to AIFF.


text:
Q: unique element/s for array in every row I have a question on how to show unique elements in an array. The program consists of two nested loops. The first counter is for rows and the other is for the letters, and the second counter outputs the letters in the array in the order.
The issue I am having, is that after the first and second row some elements start to repeat themselves(C primer plus 6th edition 241pg num 4)
#include <stdio.h>

    int main(void){

    char lets[29] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    for(int i =0; i<6; i++)
    {
        for(int j=0; j<=i; j++)
        {
            printf("%c", lets[j+i]);
        }

        printf("\n");
    }
    }

My Output
A
BC
CDE
DEFG
EFGHI
FGHIJK

Required Output
A
BC
DEF
GHIJ
KLMNO
PQRSTU

A: You need an extra offset or you never reach the end of the alphabet:
char lets[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // no need to give array size, automatic size is OK

int start = 0;

for(int i =0; i<6; i++)
{
    for(int j=0; j<=i; j++)
    {
        printf("%c", lets[j+i+start]);
    }
    start += i;  # shift letters

    printf("\n");
}

result:
A
BC
DEF
GHIJ
KLMNO
PQRSTU

A: Try this:
#include <stdio.h>

int main(void){

char lets[29] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

int k=0;
for(int i =0; i<6; i++)
{
    for(int j=0; j<=i; j++)
    {
        printf("%c", lets[k]);
        k++;
    }

    printf("\n");
}
}

Output:
A
BC
DEF
GHIJ
KLMNO
PQRSTU

A: For starters you declared the array lets as having 29 elements though initialized it explicitly only with 27 elements including the terminating zero.
char lets[29] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         ^^^

Secondly it is not clear why are you using this magic number 6
for(int i =0; i<6; i++)
              ^^^

If you will take another alphabet your code will be invalid.
Take into account that you should check whether the current outputted symbol is outside the terminating zero.
The program can look the following way
#include <stdio.h>

int main(void)
{
    char lets[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    for ( size_t i = 0, j = 0; lets[j]; i++ )
    {
        for ( size_t k = i + 1; lets[j] && k; --k ) putchar( lets[j++] );
        putchar( '\n' );
    }

    return 0;
}

Its output is
A
BC
DEF
GHIJ
KLMNO
PQRSTU
VWXYZ

Its work does not depend on the size of the character array. It can work with any alphabet.
Consider for example
#include <stdio.h>

int main(void)
{
    char lets[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    for ( size_t i = 0, j = 0; lets[j]; i++ )
    {
        for ( size_t k = i + 1; lets[j] && k; --k ) putchar( lets[j++] );
        putchar( '\n' );
    }

    return 0;
}

In this case the output will look like
A
BC
DEF
GHIJ
KLMNO
PQRSTU
VWXYZab
cdefghij
klmnopqrs
tuvwxyz


text:
Q: vertical scrollable CCLayerColor issue i'm trying to do a scrollable layer with cocos2d
what i want is for the layer to start scrolling from the top to bottom but no matter what i do when it enters the scene the layer is positioned at (0,0) aka..bottom
i've tried a couple of things but nothing seems to work
-(id) init
{
    if( (self=[super init] )) {
        self.isTouchEnabled = YES;
        isDragging = NO;
        yvel = 0.0f;
        contentHeight = 1000.0f;

        scrollLayer = [CCLayerColor layerWithColor:ccc4(200, 200, 200, 240)];
        scrollLayer.contentSize = CGSizeMake(320,contentHeight);
        scrollLayer.anchorPoint = ccp(0,1);
        scrollLayer.position = ccp(0, 480);
        [self addChild: scrollLayer];

        CCLabelTTF *label = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"test label"]
                                                   fontName:@"Marker Felt"
                                                   fontSize:24];

        label.position=ccp(100, 100);

        [scrollLayer addChild:label];

        [self scheduleUpdate];
    }
    return self;
}

the other methods are update and touches handlers so the problem couldn't be there
with this code...shouldn't it initialize with the content at the top left of the screen?

A: after a painful few hours i finally solved the problem...but i still dont know why it works
instead of   scrollLayer.position = ccp(0, 480);  i replaced with  scrollLayer.position =ccp(0,-contentHeight); and deleted scrollLayer.anchorPoint = ccp(0,1); cuz it wasnt doing anything
and i have absolutely no idea why it works
can someone explain this?


text:
Q: JavaScript functions referenced from external JS file using a
A: I am only guessing at the issue you're having, but if your functions are wrapped in an IIFE, using var would not make those variables global.
I think the best idea would be to add a global namespace for your code. Each file should have the following template code:
(function(){

  if ( !window.myNamespace ) {
    window.myNamespace = {};
  }

  myNamespace.function01 = function(){ /* add code here */ };
  myNamespace.function02 = function(){ /* add code here */ };

})();

In your case, use getAuthInfo instead of function01, etc... and then when you call a function, make sure to include that namespacing. For example:
myNamespace.getAuthInfo();

A: OK, I figured out what was causing the issue... turned out to be an NGINX problem.
Quoted from http://www.webreference.com/programming/javascript/external/2.html, in order to use external JS files...Your Web server must be set up to map the ".js" file extension to the MIME type "text/javascript."
I noticed by clicking on the file name in the Network tab of the dev tools, that the server was actually returning Content-Type: application/x-javascript.
Also, seeing elsewhere that application\javascript was the most current MIME-type to use, I made this change...
Editing the /etc/nginx/mime.types file on the server, and changing application/x-javascript js; to application/javascript js; fixed the problem.  All external files getting fetched are returning as Content-Type: application/javascript now, and they're working :)
Looks like I have some reading to do, as I've always just ignored MIME-type... not even really sure what it is, exactly... But problem fixed!