text:
Q: c# RijndaelManaged 10 times sower than Java equivalent (AES/CFB8/NoPadding) While debugging the performance of my C# application I noticed that it's a lot slower than it's Java equivalence. After looking into it the problem seems to be caused by the encryption/decryption methods.
I am forced to use AES encryption with mode set to CFB8 and no Padding. For Java this is quite straight forward as I can use Cipher.getInstance("AES/CFB8/NoPadding");. In C# I found out that I need to use new RijndaelManaged(). After running tests with the same keys and same data it here are the results:
Java:

*

*Encrypt: 0.402s

*Decrypt: 0.480s

C#:

*

*Encrypt: 4.201s

*Decrypt: 3.671s

C# Cipher code:
    public ICryptoTransform enc;
    public ICryptoTransform dec;

    public AesCrypto(byte[] key)
    {
        enc = Generate(key).CreateEncryptor();
        dec = Generate(key).CreateDecryptor();
    }

    private SymmetricAlgorithm Generate(byte[] key) {
        RijndaelManaged cipher = new RijndaelManaged();
        cipher.Mode = CipherMode.CFB;
        cipher.Padding = PaddingMode.None;
        cipher.KeySize = 128;
        cipher.FeedbackSize = 8;
        cipher.Key = key;
        cipher.IV = key;
        return cipher;
    }

    public byte[] Crypt(byte[] buffer, int offset, int count) {
        return enc.TransformFinalBlock(buffer, offset, count);
    }

C# Test code:
 static void Test() {
        // Init
        var AesCrypto = new AesCrypto(Encoding.UTF8.GetBytes("aaabbbccaaabbbcc"));
        var testData = Encoding.UTF8.GetBytes(createDataSize(9000000)); // 9mb test.

        // Timer
        var stopWatch = new Stopwatch();
        stopWatch.Start();
        AesCrypto.Crypt(testData, 0, testData.Length);
        stopWatch.Stop();
        Console.WriteLine("AesCrypto.Crypt took: " + stopWatch.ElapsedMilliseconds);
 }
 static string createDataSize(int msgSize)
    {
        StringBuilder sb = new StringBuilder(msgSize);
        for (int i = 0; i < msgSize; i++)
        {
            sb.Append('a');
        }
        return sb.ToString();
    }

Result: "AesCrypto.Crypt took: 3626"
JAVA Cipher code:
public Cryptor(boolean reader) throws CryptingException {

    keySpec = new SecretKeySpec(secretKey.getBytes(CHARSET), "AES");
    ivSpec = new IvParameterSpec(iv.getBytes(CHARSET));
    try {
        cipher = Cipher.getInstance("AES/CFB8/NoPadding");
        if (reader) cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        else cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException(e);
    } catch (NoSuchPaddingException e) {
        throw new SecurityException(e);
    }catch (InvalidKeyException e) {
        throw new SecurityException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new SecurityException(e);
    }
}

public byte[] decrypt(byte[] input) throws CryptingException {
        return cipher.update(input);
}

public byte[] encrypt(String input) throws CryptingException {
    return cipher.update(input.getBytes());
}

Java Test code:
private static void Test() {
    // Init
    String data = createDataSize(9392963);
    Cryptor writer = new Cryptor(false);

    // Timer
    Instant starts = Instant.now();
    byte[] encrypted = writer.encrypt(data);
    Instant ends = Instant.now();
    System.out.println("Java Encryption took: " + Duration.between(starts, ends));
}
private static String createDataSize(int msgSize) {
      StringBuilder sb = new StringBuilder(msgSize);
      for (int i=0; i<msgSize; i++) {
        sb.append('a');
      }
      return sb.toString();
}

Result: "Java Encryption took: PT0.469S"
Possible solution:
After researching this quite a bit it seems that AesCryptoServiceProvider() has around the same performance as Java's equivalence and has a mostly identical results. The problem with this is however that it requires padding, whereas Java's equivalence does not require padding. For example this means if I want to encrypt "abcdab" it would only encrypt "abcd" and return the result for that and keep the rest ("ab") internally. If I use padding I can get it to return the full "abcdab" encrypted, however then it has additional data appended and the symmetric algorithm is de-synced, because in java I could encrypt "abcdab" without any padding.
Question
So finally my question is how would could I make the C# encryption/decryption process just as fast as Java's? Am I doing something wrong with AesCryptoServiceProvider, maybe it's possible for it to not require padding?


text:
Q: Adding Nodes to a graph displays object instead of string (adjacency list) I'm learning how to create a graph using an adjacency list on Python. My current problem is when trying to add a node to the list, it displays the Node object at 0x0000.... instead of a string. When I try to print out the list, I get TypeError: list indices must be integers or slices, not Node".
I can't seem to figure out a way to fix this. Any help would be appreciated!
class Node:
    def __init__(self, name):
        self.name = name
        self.visited = False
        self.adjacency = []

    def addNeighbor(self, v):
        if v not in self.adjacency:
            self.adjacency.append(v)

class DGraph:
    def __init__(self, size=20):
        self.size = size
        self.numNodes = 0
        self.nodeList = [0] * size

    def addNode(self, name):
        """adds new node to graph"""
        if self.numNodes >= self.size:
            raise OverflowError("Graph Size Exceeded")
        newNode = Node(name)
        newNode.name = name
        newNode.addNeighbor(name)
        self.nodeList[self.numNodes] = newNode
        self.numNodes += 1

    def listNodes(self):
        theList = "Nodes: "
        for i in self.nodeList:
            theList += self.nodeList[i]
            theList += ""
        return theList

tree = DGraph()
tree.addNode("A")
tree.addNode('C')
tree.addNode('T')

What the list looks like in the debugger

A: You can specify string representation of your object by implementing __repr__
See details in the docs and this question
Here is a working example (nodeList is fixed too)
class Node:
    def __init__(self, name):
        self.name = name
        self.visited = False
        self.adjacency = []

    def addNeighbor(self, v):
        if v not in self.adjacency:
            self.adjacency.append(v)

    def __repr__(self):
        return self.name

    def __str__(self):
        return self.name

class DGraph:
    def __init__(self, size=20):
        self.size = size
        self.numNodes = 0
        self.nodeList = [0] * size

    def addNode(self, name):
        """adds new node to graph"""
        if self.numNodes >= self.size:
            raise OverflowError("Graph Size Exceeded")
        newNode = Node(name)
        newNode.name = name
        newNode.addNeighbor(name)
        self.nodeList[self.numNodes] = newNode
        self.numNodes += 1

    def listNodes(self):
        theList = "Nodes: "
        for i in self.nodeList:
            theList += str(i)
            theList += " "
        return theList

tree = DGraph()
tree.addNode("A")
tree.addNode('C')
tree.addNode('T')
print(tree.listNodes())

Now debugger will show node names (using__repr__)

Such implementation of __repr__ is probably not a good idea unless you enforce uniqueness of node names.
As a side note, it's nice to follow naming convention in Python

redpajama_set_name: RedPajamaStackExchange


text:
Q: failed to run the server that generated by swagger codegen I am learning to develop restful api for machine learning service. I used openapi spec to define my api specification, and I tried to use flask rest for this. However, I find this medium post is relevant to my intention, so I downloaded source code and tried to run the server locally, but server endpoint failed. I could able to run my other flask app on the same endpoint, but this project is not working even I followed its instruction. I created my open api spec file so I want to learn and understand this medium post by run server locally. Can anyone point me out what's going on this medium post source code? any quick solution to figure out how to run server locally? thanks
for me, a simple flask app works and can run it on server endpoint.
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello World!"

if __name__ == '__main__':
    app.run()

I want to run the server from this APIs with OpenAPI, because I want to use same structure for developing my api. Can anyone point me out why I can't run a server? any idea?
update
in this medium post, all artifacts generated by openapi code generator, and structured out by openapi spec file, so able to run the server from its source code will help me understand how to proceed my workflow.

A: The examples in the repository you mention come with docker files. You could use Docker to quickly spin up the server.
cd api_tutorial/openapi/photo_album/codegen_server
docker build . -t codegen_server
docker run codegen_server

However, this does not work.
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/local/lib/python3.8/runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "/usr/src/app/openapi_server/__main__.py", line 3, in <module>
    import connexion
  File "/usr/local/lib/python3.8/site-packages/connexion/__init__.py", line 3, in <module>
    from .apis import AbstractAPI  # NOQA
  File "/usr/local/lib/python3.8/site-packages/connexion/apis/__init__.py", line 1, in <module>
    from .abstract import AbstractAPI  # NOQA
  File "/usr/local/lib/python3.8/site-packages/connexion/apis/abstract.py", line 16, in <module>
    from ..operations import OpenAPIOperation, Swagger2Operation
  File "/usr/local/lib/python3.8/site-packages/connexion/operations/__init__.py", line 1, in <module>
    from .abstract import AbstractOperation  # noqa
  File "/usr/local/lib/python3.8/site-packages/connexion/operations/abstract.py", line 11, in <module>
    from ..decorators.response import ResponseValidator
  File "/usr/local/lib/python3.8/site-packages/connexion/decorators/response.py", line 12, in <module>
    from .validation import ResponseBodyValidator
  File "/usr/local/lib/python3.8/site-packages/connexion/decorators/validation.py", line 9, in <module>
    from werkzeug import FileStorage
ImportError: cannot import name 'FileStorage' from 'werkzeug' (/usr/local/lib/python3.8/site-packages/werkzeug/__init__.py)

As pointed out on this Github issue, this issue is related to connexion and does not happen with version 2.6.0. So, let's update requirements.txt to use this version instead.
connexion == 2.6.0

Build and run again with docker and voilá, it should work.
docker run codegen_server
 * Serving Flask app "__main__" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)

You could also run the server without Docker by cd-ing into the root directory and doing.
python -m openapi_server

Which in fact, is exactly what docker does, as we can see in the Dockerfile.
...

ENTRYPOINT ["python3"]
CMD ["-m", "openapi_server"]


text:
Q: Using multiple neural nets in sequence on one classification problem I'm working on a time-series (comm signals) classification problem that has 25 possible classes. I have one fairly deep CNN that can perform fairly well on this problem, but I'm hoping to make better. So I'm wondering if there's merit in using a few CNN's to solve the same classification problem instead.
Specifically, the 25 classes can be naturally divided into one group of 8 classes (group 1) and another of 17 (group 2). If there's reason to believe that:

*

*The binary classification problem of determining whether the signal is a part of group 1 or group 2 can be solved with high accuracy

*The classification problem of finding the right class given the group, is significantly easier than the classification problem of finding the right class out of all 25 possible classes
If I were to instead use three classifiers that solve the problem above, is it possible for this architecture to leverage more information than the 1 classifier approach, or is the approach baseless.

A: Yes, this is done all the time.  Improved results are often found when splitting features up into different groups, applying a neural net to each different set of features, and then inputting the results from each network into a final network for either classification or function approximation.  As an example case, see Figure 2 for which multiple networks are tied together.


text:
Q: Add new data to a text file without overwriting it in python Right, I'm running a while loop that does some calculations, and, at the end, exports the data to a .txt file. The problem is, rather than appending the data to the end of the file, it seems to overwrite it and create a brand new file instead. How would I make it append to the old file?
Here's my code:
turn = 1
while turn < times:
    dip1 = randint(1,4)
    dip2 = randint(1,4)
    dip = (dip1 + dip2) - 2

    adm1 = randint(1,4)
    adm2 = randint(1,4)
    adm = (adm1 + adm2) - 2

    mil1 = randint(1,4)
    mil2 = randint(1,4)
    mil = (mil1 + mil2) - 2

    with open("Monarchs Output.txt", "w") as text_file:
        print("Monarch{}, adm: {}, dip: {}, mil: {}\n".format(turn, adm, dip, mil), file=text_file)

    turn = turn + 1

Just to note, it runs just fine, all the required imports are at the top of the code.

A: You should use open("Monarchs Output.txt", "a") instead of open("Monarchs Output.txt", "w")
link: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

A: Open the file before the loop starts. Every time you open the file for writing, it creates a new file (it deletes whatever is in it).
with open("Monarchs Output.txt", "w") as text_file:
    turn = 1
    while turn < times:
        dip1 = randint(1,4)
        dip2 = randint(1,4)
        dip = (dip1 + dip2) - 2

        adm1 = randint(1,4)
        adm2 = randint(1,4)
        adm = (adm1 + adm2) - 2

        mil1 = randint(1,4)
        mil2 = randint(1,4)
        mil = (mil1 + mil2) - 2

        print("Monarch{}, adm: {}, dip: {}, mil: {}\n".format(turn, adm, dip, mil), file=text_file)

        turn = turn + 1


text:
Q: In Rails when using the Devise gem, how to log failed logins and lockups? I use the Devise to handle the authentications in my app and have public_activity to record things and have a log. Now I need to add a record to the log when a failed login occurs and when a account gets locked. How can I do this?

A: You can use Warden's after_authentication hook as devise is built on warden. Put this in an config/initializers/devise_hooks.rb:
Warden::Manager.after_authentication do |user, auth, opts|
  # do something with user
end

Read details in wardens wiki


text:
Q: iOS 7 presented nav controller nav bar height 64 px after frame change I am presenting a UINavigationController from a UIViewController, I then want the container to move downward, hence shrinking the UINavigationController, merely to present a view at the top such as an error message, the problem is now on iOS7 the NavBar height is 64px and doesnt look right, also when I shift the UINavigationController frame back to full height and to 0 Y-origin, sometimes its shifting back to 44px. It seems like odd behavior. Any obvious solutions to this?

The black bar is the navigation bar, the gray is the UIViewController (parent)
I am also using:
if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
}

A: I didn't understand  your question quite clearly, but it seems to me that you should try self.edgesForExtendedLayout = UIRectEdgeBottom; instead of self.edgesForExtendedLayout = UIRectEdgeNone;


text:
Q: cannot access DialogStyle After updating android-support library to 22.2.0 project stopped compiling.
error: cannot access DialogStyle
  class file for android.support.v4.app.DialogFragment$DialogStyle not found
  Consult the following stack trace for details.
  com.sun.tools.javac.code.Symbol$CompletionFailure: class file for android.support.v4.app.DialogFragment$DialogStyle not found

Can't find how to work around this issue.
Previously used version was 22.1.1

A: Here is a couple workarounds that worked for us:
Workaround 1 (some people see a NPE with this, some don't)
I just found a TEMPORARY workaround... till appcompat  fixes this issue:

*

*Create the following package in your project src/main/java

android.support.v4.app

*Create the following new file:

DialogFragment$DialogStyle.java

*Contents
package android.support.v4.app;
// todo remove this file when fixed in appcompat (https://code.google.com/p/android/issues/detail?id=175086)
public @interface DialogFragment$DialogStyle {
    }
Workaround 2 (bit more ugly, but less potential for a build issue)
I found another work-around.... a bit more ugly... but has gotten us around this issue (including the NPE on the above work-around) till appcompat 22.2 is fixed.

*

*Create the following package in your project src/main/java

android.support.v4.app

*Copy the Google v4 FragmentDialog.java code

https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v4/java/android/support/v4/app/DialogFragment.java

*Rename the class (to something like TempFragmentDialog).  You will get a "Duplicate" class error if you don't rename the class.

*Any FragmentDialog, in your project, that has @Inject will need to extend your copy of the FragmentDialog (example: public class MyFragmentDialog extends TempFragmentDialog)

A: Try this, it resolved my issue:
compile ('com.android.support:appcompat-v7:22.2.0') {
        exclude module: 'support-v4' }
compile ('com.android.support:recyclerview-v7:22.2.0') {
        exclude module: 'support-v4' }
compile ('com.android.support:cardview-v7:22.2.0') {
        exclude module: 'support-v4' }
compile ('com.android.support:design:22.2.0') {
        exclude module: 'support-v4' }
// and exclude support-v4 from other dependencies as well that might include it
// finally add it, but avoid version 22.2.0...
compile ('com.android.support:support-v4:22.1.1')

There is no need to manually add the support-v4 library to your libs directory, the last import ensures that the right version is included in your project.
BTW all of this workaround is not your fault, blame others :)

A: @takoli's answer works in most cases but if you have other dependencies that silently include support-v4 or if you are too lazy to explicitly exclude support-v4 everywhere here is another solution.
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.android.support:recyclerview-v7:22.2.0'
compile 'com.android.support:mediarouter-v7:22.2.0'
// Force stable version of support-v4
compile ('com.android.support:support-v4:22.1.1') {
    force = true
}

Update:
AndroidAnnotations released a new version 3.3.2 that resolves this issue. If you are using AndroidAnnotations update to 3.3.2 and use the 22.2.0 support libraries without forcing the old version of support-v4. For more information see this thread

A: I am using the work around found here https://code.google.com/p/android/issues/detail?id=175086#c9
I modified my build.gradle file to say the following in the dependencies section:
compile fileTree(include: ['*.jar'], dir: 'libs')
compile ('com.android.support:appcompat-v7:22.2.0') {
    exclude module: 'support-v4'
}
compile ('com.android.support:gridlayout-v7:22.2.0') {
    exclude module: 'support-v4'
}
compile ('com.android.support:cardview-v7:22.2.0') {
    exclude module: 'support-v4'
}
compile ('com.android.support:design:22.2.0') {
    exclude module: 'support-v4'
}

You will also have to exclude it from any other dependencies that use the support library like dagger or facebook.
Then, I added the android-support-v4.jar file found in $ANDROID_HOME/extras/android/support/v4 to my libs directory, as that file does seem to have DialogFragment$DialogStyle.
Now, my build is fully working again, but I still hope this can get fixed soon.

A: Simply put, this is a bug in support library version 22.2.0
Just upgrade to the next update 22.2.1, works like a charm.

A: Just in case to not to skip an answer: here is also a discussion about this problem https://github.com/excilys/androidannotations/issues/1435
BTW, do you use Android Annotations in a project where this problem exists ?

A: It happens if you are using android.support.v4.app.DialogFragment.
Try to use android.app.DialogFragment instead.


text:
Q: How to convert a list of tuples into a regular list in haskell? I'd like to convert a list of tuples (a,a) into just a list of as. This is what i have so far
map (\(x,y) -> [x,y]) [(1,4),(2,5)]
> [[1,4],[2,5]]

but what i want is
> [1,4,2,5]

A: What you are describing is a common Haskell pattern!

*

*Take a list

*Use a function that generates lists for each element

*Join into a single list.

It doesn't have to be a list,

*

*Take a container

*Use a function that generates a new container for each element

*Join the containers.

For the list case, this function's type would be
[a] -> (a -> [a]) -> [a]

Let's call a container of a's m a, where m is the container type. In this case, we would have
m a -> (a -> m a) -> m a

This function is >>=! We use it as an infix operator.
Prelude> [(1,4),(2,5)] >>= \(x,y) -> [x,y]
[1,4,2,5]

... where the container has to support "collapsing" two layers into one layer. This is a monad :)
a >>= f is the same as concatMap f a, as suggested by Willem Van Onsem.

A: The only extra step you need to take is to concatenate the lists, with:
concat (map (\(x,y) -> [x,y]) [(1,4),(2,5)])

here concat :: [[a]] -> [a] thus concatenates the list of lists together into a single list.
Since such constructions occur often, there is a function that makes it more convenient: concatMap :: (a -> [b]) -> [a] -> [b]:
concatMap (\(x,y) -> [x,y]) [(1,4),(2,5)]

You can also use list comprehension, and write it like:
[z | (x,y) <- items, z <- [x,y]]

where data is your list of initial data.


text:
Q: Get projects from Teamweek in jQuery I'm trying to get the planning from Teamweek in my js app. (API)
function get_teamweek_planning()
{
    var api_url     = 'https://teamweek.com/api/v2/',
        api_key     = '1234567',
        object_type = 'projects';

    $.ajax(
    {
        url: api_url + api_key + '/projects.json',
        type: 'GET',
        dataType: 'jsonp',
        cache: false,
        data: {},

        success:function(response){
            console.log('response:', response);
        }
    });
}

This returns a 403 (forbidden). This is documented and means authentication fails. But how do i fix it?

A: function get_teamweek_planning()
{
    var api_url     = 'https://teamweek.com/api/v2/',
        account_id  = '<your account id>';

    $.ajax(
    {
        url: api_url + account_id + '/projects.json',
        beforeSend: function (request)
        {
         request.setRequestHeader('Authorization', 'Bearer ' + btoa('<your api token>'))
        },
        type: 'GET',
        dataType: 'jsonp',
        cache: false,
        data: {},

        success:function(response){
            console.log('response:', response);
        }
    });
}

If your're using this on a page that isn't only for yourself then do not hard code your token...

A: You forgot the authentication part, you need to authenticate on every request (as is documented on github).
Include the following vars for in the data object:
data: {
    auth_token: [your token],
    name: [client name]
}

https://github.com/toggl/teamweek_api_docs/blob/master/chapters/authentication.md


text:
Q: Reported CPU frequency is lower than what the hardware specs are My Linux computer with custom kernel configuration seems slow. Even make menuconfig of Linux kernel is as slow as I can see redrawing of the menu. When I run cpupower frequency-info, frequency is below 150 MHz. But the minimum frequency on this CPU is 500 MHz. This is an Intel® Pentium® quad core processor N3540 (up to 2.66 GHz). I have never seen something like this.
Why is the frequency so low? I did not touched cpu-freq configuration since boot. The computer is resumed from sleep-to-ram.
I can set the frequency manually but it is fixed at (about) 64 MHz.
$ LANG= cpupower frequency-info
analyzing CPU 0:
  driver: intel_pstate
  CPUs which run at the same hardware frequency: 0
  CPUs which need to have their frequency coordinated by software: 0
  maximum transition latency:  Cannot determine or is not supported.
  hardware limits: 500 MHz - 2.67 GHz
  available cpufreq governors: performance powersave
  current policy: frequency should be within 500 MHz and 1.07 GHz.
                  The governor "powersave" may decide which speed to use
                  within this range.
  current CPU frequency: Unable to call hardware
  current CPU frequency: 129 MHz (asserted by call to kernel)
  boost state support:
    Supported: yes
    Active: yes

lscpu output is created when the computer is OK.
$ LANG= lscpu
Architecture:        x86_64
CPU op-mode(s):      32-bit, 64-bit
Byte Order:          Little Endian
Address sizes:       36 bits physical, 48 bits virtual
CPU(s):              4
On-line CPU(s) list: 0-3
Thread(s) per core:  1
Core(s) per socket:  4
Socket(s):           1
Vendor ID:           GenuineIntel
CPU family:          6
Model:               55
Model name:          Intel(R) Pentium(R) CPU  N3540  @ 2.16GHz
Stepping:            8
CPU MHz:             618.821
CPU max MHz:         2665.6001
CPU min MHz:         499.8000
BogoMIPS:            4331.60
Virtualization:      VT-x
L1d cache:           24K
L1i cache:           32K
L2 cache:            1024K
Flags:               fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology tsc_reliable nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 movbe popcnt tsc_deadline_timer rdrand lahf_lm 3dnowprefetch epb pti tpr_shadow vnmi flexpriority ept vpid tsc_adjust smep erms dtherm ida arat

A: The CPU frequency can be outside the limits, because the processor itself will slow
itself down if the load is light enough, regardless of the parameters.
You should only worry if the CPU frequency does not go up very quickly when
there is actual work to do. But if it does not, below are some possibilities:

*

*A battery issue, when the battery is really low and not charging.

*General OS confusion that may be fixed by unplugging the power cord and plugging
it back in again (or reboot).

*Issues with CPU cooling, which may happen even when the laptop case is not
even warm. So check sensors.

*A serious problem requiring a repair-shop.


text:
Q: How can I tell that a particular planet is under an embargo? In several playthroughs now I've managed to accidentally cause a faction to become extremely angry at me for violating their embargo.  However, I can't seem to figure out ahead of time that there is one until after I make the trade.  Is there any way of finding out?

A: I haven't played this in a while, but I believe there's a News option or something like that. Someone to talk to who will give you information on what's going on in the galaxy. They will sometimes inform you of an embargo on a planet. I've had the same issue, and it's extremely annoying.

A: Hiring a political officer seems to be the only way to know for sure that there is currently an embargo on the planet.  They will warn you when before you attempt to purchase goods from an embargoed planet.
Also, if you go to the rumors tab and click on the white button near the top, you will be taken to the Faction Conflicts tab where you can see a list of all current trade embargos that are going on.


text:
Q: CUrL PHP 7 : installed but not detected or loading I work on a Debian Linux 8 PHP 5 / PHP 7 / PHP 7.1
I installed CUrL extension but it's not detected.

curl --version
  curl 7.38.0 (x86_64-pc-linux-gnu) libcurl/7.38.0 OpenSSL/1.0.1t zlib/1.2.8 libidn/1.29 libssh2/1.4.3 librtmp/2.3
  Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp scp sftp smtp smtps telnet tftp
  Features: AsynchDNS IDN IPv6 Largefile GSS-API SPNEGO NTLM NTLM_WB SSL libz TLS-SRP

Do you know from where could come the issue?
Many thanks


text:
Q: match_parent is not working in custom toolbar I have made custom toolbar with search and setting icon . when i click on search icon edittext should apper with match_parent and should occupy available space till the search icon . However it is not happening . it just appear with very small space at the top-left side . Please help where i am wrong

I would like to share my whole code with xml
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="0dp"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="myresolver.faisal.home.com.myresolver.MainActivity">

<include
    android:id="@+id/toolbar"
    layout="@layout/my_toolbar"></include>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/toolbar"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="1dp"
        android:weightSum="4"

        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:weightSum="3">

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96"></ImageView>

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:weightSum="3">

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:weightSum="3">

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:weightSum="3">

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:weightSum="3">

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:weightSum="3">

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />

            <ImageView
                style="@style/icon"
                android:background="@drawable/fear_96" />
        </LinearLayout>

    </LinearLayout>
   </ScrollView>

 </RelativeLayout>

mytoolbar.xml
<?xml version="1.0" encoding="utf-8"?>
   <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/orange"
    app:titleTextColor="@color/white"></android.support.v7.widget.Toolbar>
my main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<item
    app:showAsAction="always"
    android:title="@string/search"
    android:icon="@drawable/ic_search_white_24dp"
    android:id="@+id/search"
    ></item>
<item
    app:showAsAction="always"
    android:title="@string/setting"
    android:icon="@drawable/ic_settings_white_24dp"
    android:id="@+id/setting"></item>
</menu>

my search_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<EditText
    android:id="@+id/searchEditText"
    android:layout_width="match_parent"   // THIS IS NOT WORKING
    android:layout_height="wrap_content"
    android:imeOptions="actionSearch"
    android:inputType="text" />

</LinearLayout>

My activity
EditText searchEditText;
boolean isSearchBoxOpen = false;
Toolbar toolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.search:
            onSearchedHandler();
            break;

        case R.id.setting:
            Toast.makeText(this, "Setting is UnderConstruction", Toast.LENGTH_LONG).show();
            break;
    }

    return super.onOptionsItemSelected(item);
}

public void onSearchedHandler() {
    if (isSearchBoxOpen) {

        String word = searchEditText.getText().toString();

        if (word != null) {
            Toast.makeText(this, "Searching for ..." + word, Toast.LENGTH_LONG).show();
        }
    } else {

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setCustomView(R.layout.search_layout);
        actionBar.setDisplayShowTitleEnabled(false);

        searchEditText = (EditText) actionBar.getCustomView().findViewById(R.id.searchEditText);

        searchEditText.requestFocus();
        InputMethodManager keyboard = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        keyboard.showSoftInput(searchEditText, InputMethodManager.HIDE_IMPLICIT_ONLY);

        isSearchBoxOpen = true;

    }

}

@Override
public void onBackPressed() {

    if (isSearchBoxOpen) {

        ActionBar actionBar = getSupportActionBar();

        actionBar.setDisplayShowCustomEnabled(false);
        actionBar.setDisplayShowTitleEnabled(true);
        isSearchBoxOpen = false;

        return;

    }

    super.onBackPressed();
}

A: When the custom view is inflated as a result of calling setCustomView(resId), wrap_content is forced upon it (if you look into the view dump, you can see that the wrapping LinearLayout is shrunk, not the EditText).
You can set the custom view in the following way:
    View customView = LayoutInflater.from(this).inflate(R.layout.search_layout, null);
    ActionBar.LayoutParams params = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
    actionBar.setCustomView(customView, params);

A: Use the below code for toolbar xlm layout :
<android.support.v7.widget.Toolbar
    xmlns:app="schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/primaryColor"
    android:contentInsetLeft="0dp"
    android:contentInsetStart="0dp"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"
    android:contentInsetRight="0dp"
    android:contentInsetEnd="0dp"
    app:contentInsetRight="0dp"
    app:contentInsetEnd="0dp" />

A: just add this line to take full width
app:contentInsetStart="0dp"

A: The padding in the RelativeLayout in main_activity.xml is preventing it from taking the full space so instead of having
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="0dp"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="myresolver.faisal.home.com.myresolver.MainActivity">

you move the paddings to the scrollview such that
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/toolbar"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:fillViewport="true">


text:
Q: how to call completion block? How do I call this Swift based completion block in ObjectiveC?
public var completionBlock: IMGLYEditorCompletionBlock?
public typealias IMGLYEditorCompletionBlock = (IMGLYEditorResult, UIImage?) -> Void

This is how I call it in Swift but never work in Objective C.
func callEditorViewController() {
   var editorViewController = IMGLYMainEditorViewController()
   editorViewController.highResolutionImage = image
   editorViewController.initialFilterType = .None
   editorViewController.initialFilterIntensity = 0.5
   editorViewController.completionBlock = editorCompletionBlock
}

func editorCompletionBlock(result: IMGLYEditorResult, image: UIImage?) {
   ...
}

This is my objective C code with syntax error.
-(void) editorCompletionBlock:(IMGLYEditorResult*)result img:(UIImage*)image{

}
 IMGLYMainEditorViewController *editor = [[IMGLYMainEditorViewController alloc]init];
editor.highResolutionImage = image;

 editor.completionBlock = [self editorCompletionBlock:r img:image];

A: Calling blocks is straight forward:
editor.completionBlock(result, image);

Still feeling you'd rather like to set it:
editor.completionBlock = ^(IMGLYEditorResult result, UIImage *image) {
        // do something meaningful here
};

A: first create new type in .h file
typedef void (^TableViewCellConfigureBlock)(id cell, id item);

then define your block in .m file like this in viewDidLoad
TableViewCellConfigureBlock configureCell = ^(id cell, id object) {
            [cell configureCellForObject:object];
        };

and finally call it from somewhere
UITableViewCell *cell;
NSString *item = @"my test string";

self.configureCellBlock(cell, item);


text:
Q: Why won't my contact form email me after submission? I am very new to PHP, so please bear with me here.
It seems like the form goes through, I don't get any errors, but I never receive an email.
Thank you in advance!!
Here is my html
<form class="form-horizontal" role="form" method="POST" id="contact-form" action="contact-form/form.php" style="padding-bottom: 5em;">

                            Name

                                <input type="text" class="form-control" name="name" id="name" placeholder="Enter Name">

                            Email

                                <input type="email" class="form-control" name="email" id="email" placeholder="Enter Email">

                            Message

                                <textarea class="form-control" name="message" rows="10"></textarea>

                            <input type="hidden" name="save" value="contact">
                            <button type="submit" class="btn btn-default">Submit</button>

                    </form>

Here is my php
<?php
// check for form submission - if it doesn't exist then send back to contact form
if (!isset($_POST["save"]) || $_POST["save"] != "contact") {
    header("Location: ../index.php"); exit;
}
// get the posted data
$name = $_POST["name"];
$email_address = $_POST["email"];
$message = $_POST["message"];
$headers = 'From: '.$email_address."\r\n" .
    'X-Mailer: PHP/' . phpversion();
    // write the email content
$email_content = "Name: $name\n";
$email_content .= "Email Address: $email_address\n";
$email_content .= "Message:\n\n$message";
    // send the email
mail ("myEmail", "Someone Wants a Website!", $email_content, $headers);

$to = $_POST['email'];
$subject = 'Thank you for contacting me!';
$msg = 'I have recieved your correspondence and will get back to you as soon as I can. Best regards, Mike Wilcox Designs';
mail($to, $subject, $msg);
header("Location: ../index.php"); exit;
?>

I am also using jquery validate


text:
Q: Summing up a related table's values in PowerPivot/DAX Say I have two tables. attrsTable:
file | attribute | value
------------------------
A    | xdim      | 5
A    | ydim      | 6
B    | xdim      | 7
B    | ydim      | 3
B    | zdim      | 2
C    | xdim      | 1
C    | ydim      | 7

sizeTable:
file | size
-----------
A    | 17
B    | 23
C    | 34

I have these tables related via the 'file' field. I want a PowerPivot measure within attrsTable, whose calculation uses size. For example, let's say I want xdim+ydim/size for each of A, B, C. The calculations would be:
A: (5+6)/17
B: (7+3)/23
C: (1+7)/34

I want the measure to be generic enough so I can use slicers later on to slice by file or attribute. How do I accomplish this?
I tried:
dimPerSize := CALCULATE([value]/SUM(sizeTable[size])) # Calculates 0
dimPerSize := CALCULATE([value]/SUM(RELATED(sizeTable[size]))) # Produces an error

Any idea what I'm doing wrong? I'm probably missing some fundamental concepts here of how to use DAX with relationships.

A: Hi Redstreet,
taking a step back from your solution and the one proposed by Jacob, I think it might be useful to create another table that would aggregate all the calculations (especially given you probably have more than 2 tables with file-specific attributes).
So I have created one more table that contains (only) unique file names, and thus the relationships could be visualized this way:

It's much simpler to add necessary measures (no need for calculated columns). I have actually tested 2 scenarios:
1) create simple SUM measures for both Attribute Value and File Size. Then divide those two measures and job done :-).
2) use SUMX functions to have a bit more universal solution. Then the final formula for DimPerSize calculation could look like this:
=DIVIDE(
   SUMX(DISTINCT(fileTable[file]),[Sum of AttrValue]),
   SUMX(DISTINCT(fileTable[file]),[Sum of FileSize]),
   BLANK()
)

With [Sum of AttrValue] being:
=SUM(attrsTable[value])

And Sum of FileSize being:
=SUM(sizeTable[size])

This worked perfectly fine, even though SUMX in both cases goes over all instances of given file name. So for file B it also calculates with zdim (if there is a need to filter this out, then use simple calculate / filter combination). In case of file size, I am using SUMX as well, even though it's not really needed since the table contains only 1 record for each file name. If there would be 2 instances, then use SUMX or AVERAGEX depending on the desired outcome.
This is the link to my source file in Excel (2010).
Hope this helps.

A: You look to have the concept of relationships OK but you aren't on the right track in terms of CALCULATE() either in terms of the structure or the fact that you can't simply use 'naked' numerical columns, they need to be packaged in some way.
Your desired approach is correct in that once you get a simple version of the thing running, you will be able to slice and dice it over any of your related dimensions.
Best practice is probably to build this up using several measures:
[xdim] = CALCULATE(SUM('attrstable'[value]), 'attrstable'[attribute] = "xdim")
[ydim] = CALCULATE(SUM('attrstable'[value]), 'attrstable'[attribute] = "ydim")
[dimPerSize] = ([xdim] + [ydim]) / VALUES('sizeTable'[size])

But depending on exactly how your pivot is set up, this is likely to also throw an error because it will try and use the whole 'size' column in your totals. There are two main strategies for dealing with this:

*

*Use an 'iterative' formula such as SUX() or AVERAGEX() to iterate individually over the 'file' field and then adds up or averages for the total e.g.
[ItdimPerSize] = AVERAGEX(VALUES('sizeTable'[file]), [dimPerSize])
Depending on the maths you want to use, you might find that produce a useful average that you need to use SUMX but devide by the number of cases i.e. COUNTROWS('sizeTable'[file]).

*You might decide that the totals are irrelevant and simply introduce an error handling element that will make them blank e.g.
[NtdimPerSize] = IF(HASONEVALUE('sizeTable'[file]),[dimPerSize],BLANK())
NB, all of this assumes that when you are creating your pivot that you are 'dragging in' the file field from the 'sizetable'.


text:
Q: Load TFS WorkItemDocument Doing some tfs automation and have been retrieving WorkItemDocument objects with the GetWorkItem call however on a workitem that is retrieved I get the error in the title. Where can I find the description for the error or why its generating the error?
_COMPlusExceptionCode = -532462766
I have googled around and no definitions for this exception.
foreach (int i in (doc2 as IResultsDocument).SelectedItemIds)
{
    _lockToken1 = new object();
    IWorkItemDocument widoc = docsrv2.GetWorkItem(tfscoll, i, _lockToken1);
    if (widoc == null) continue;

    Debug.Print("Project name: {0}", widoc.Item.Project.Name);
    if (!widoc.IsLoaded) // Does not load and errors
    {

Thanks

A: Got it working now Thanks! It was a resource lock on the object within the loop not allowing the second or more items to load. Upon each iteration I now properly release and dispose of the lock and also in any exit iteration scenarios. Needed a dastardly DoEvents but its working great now.
//...
//...
foreach (int i in (doc2 as IResultsDocument).SelectedItemIds)
{
    _lockToken1 = new object();
    IWorkItemDocument widoc = docsrv2.GetWorkItem(tfscoll, i, _lockToken1);
    if (widoc == null) continue;

    if (!widoc.IsLoaded)
    {
        widoc.Load();
        DateTime startTime = DateTime.Now;
        while (!widoc.IsLoaded && DateTime.Now.Subtract(startTime).TotalSeconds <= 2.0)
        {
            Application.DoEvents();
        }
        //...
        //...
        //...
    }
    widoc.Item.Close();
    widoc.Release(_lockToken1);
    //...
//...


text:
Q: how to dynamic linking for the .ane files I created a native extension. I can debug this application as an desktop application. Working well, there is no problem while using native extension classes. But When I debug for Premiere Pro, I get "

Class com.extenison.samples.ANESample::myClass could not found

" error.
Do you have any idea what I'm missing while debugging for Premiere Pro extension ?
- I added .ane file on Native Extensions tab of Properties
- Also added .swc file on Library Path tab
- checked Package in Flex Build Packaging tab
- I can see .ane file on Package Contents section of Flex Build Packaging
Thanks
Edit : this issue is about linking native extensions. Any helps appreciated about this

A: If we are creating .ane files for application that runs on some devices, that means we are gonna package our project and device will read files from package.
My native extension (.ane) file was working on local, as desktop application because there was no packaging process.
was not working on Adobe Premiere because ;

*

*put .ane file under yourproject/src/ directory to some folder

*go to project/properties/Flex Build Packaging and checked your .ane file

*on same directory above,Click Package Contents tab and ensure that your .ane file is in the list
I didn't do this:) But you do this.

A: You can ignore this error and move on with creating an .ipa with you adt commands. The error is because of cross platform.
Though check with the points, You make the .swc as external reference from the properties.


text:
Q: Backup server components I am trying to build a backup server which will make ... backups... :) Since I have never built a server like this what would you say should I look for?
Components I have been looking at:

*

*Intel E2220

*Enermax Modu82+ 425 Watt

*2x Corsair 1 GB DDR2 Ram at 533

I still need a Motherboard and some good drives.. I would like to get 3 TB of space.
Hope you guys can help. I have looked at the Asus P5Q VM because it has 6 SATA ports and a built in grafics card and 6 500 GB Drives by Western Digital 5002ABYS RE3
What are things I should look for? I am not planing on putting the backup server in raid though.

A: I'm going to assume from your mention of 3TB storage that you're looking at backup-to-disk.  This is essentially just "dumb storage", so the box really needs to be powerful enough to run your OS and backup tool(s) of choice, and nothing more.  Bearing that in mind, the factors you need to consider are getting the data from source to destination (and back again) as quickly as possible, and ensuring that your backup is still going to be there for you when the time comes that you need it.
So we're looking at minimum gig ethernet and - yes - RAID.  Storage is so cheap these days that I seriously believe there is NO excuse for skimping on RAID, and in fact I would say that RAID 10 is now the RAID level of choice for most scenarios.  Edit: per Oskar's comment, you don't need RAID 10 for this however, go RAID 5 or 6 and it will do the job (see Oskar's own post for further info here).  (End edit).  You don't want to be in a situation where one of those disks fails and you lose some data that you need to get back, do you?
If budget allows I would also include a tape unit.  I like tape; it's robust, cheap, high capacity, portable, and will provide you with a second line of defence in case the server lets you down.  Make it an external one so that you can connect it to another box if the worst does happen.
Working from there you're looking at a scenario where you do a full backup each weekend (making certain to backup everything, not just what you think you need), daily differentials, and also run the last full off to tape as your second line.  So figure how much data you have, how much of it changes, how many weeks you want to keep, and calculate your storage requirements from that.  Double the result because storage used is going to grow, and I think you'll be doing good.

A: 3TB of space, I'd say get 4 or 5 1TB drives and build a RAID5 with optional (highly recommended) hot spare (or go RAID6). As 1TB drives are as close to twice the price of 500GB drives you can get - there's little use going for 500GB drives in my opinion.
Get a separate (or if possible two) smaller drives for running the OS, would be best to run those in a mirror/RAID1.
You do not want to loose data and every disk WILL break sooner or later. The question is when...
...doing RAID5 is normally easy within the OS itself - no need for a card.
Lastly, if you're going to protect company data no matter how small the company is - you do not want to build the machine yourself. Buy a preconfigured server by a big-name manufacturer instead like Dell or HP.

A: I'd go with a pre-integrated server for backups. Something with support.  Unless I was only backing up my personal stuff at home.  You don't want to have anybody looking at you a little sideways when they get to figuring out there's something gone wrong with the backups and how it might have been your integration.
If you're going to build your own: Mirror the OS/Applicaion drives.  RAID 5 the volumes you're using for backups, preferably with a nice hot spare.
Don't totally dismiss tape, as an option for your long term data storage needs.  If you're doing quarterly, year end, or month end backups.  Also it's way easier to get tape off site than disks. Backups aren't good backups if they can be destroyed in the same incident that destroys the originals.  So contemplate the placement of your backup server closely.  Will a single lightening strike, spilled coffee, contractor with a carpet steamer (yeah it happened to me) destroy the server, and the backup server?  If yes, then you should think about if that is good enough backup.

A: one thing that i think is essential for a backup machine like this (especially if you're not going to have a tape drive, which would be a really bad decision IMO) is to have hot-swap bays for the drives.
this would allow you to quickly swap drives if any die (essential if you use RAID).
it would also allow you to upgrade the drives easily as larger drives become affordable - e.g. a quick and easy upgrade to 2TB drives.
and finally it would allow you to use disk drives in a similar fashion to tapes - as "data cartridges" that can be installed in the machine, written to, and removed to place in a safe or off-site.  you'd be trading off the extra fragility of hard disks versus the cost of a tape-backup drive (external LTO-4 drives start from around $1500 AUD - which would buy a LOT of 1TB drives)
oh, and look for a motherboard with 8 sata ports rather than 6.  2 for the operating system drives (RAID-1 mirror), and 6 for the data drives whether they're in RAID or not.  8 is quite common these days (at least on AMD chipset boards which i'm more familiar with than intel boards)


text:
Q: Wrapping Ruby With An Anonymous Module There are several Ruby C API functions for running some Ruby code. Most just run the code in an isolated binding like require does. But some of them first wrap the code in an anonymous module before running it. For example, rb_load takes an argument for whether you want this wrapping, rb_eval_string_wrap is just rb_eval_string_protect but with wrapping.
In C, the wrapping looks like this:
/* load in anonymous module as toplevel */
th->top_self = rb_obj_clone(rb_vm_top_self());
th->top_wrapper = rb_module_new();
rb_extend_object(th->top_self, th->top_wrapper);

What is the point of doing this? I've tested these functions alongside their unwrapped equivalents and the result is always the same. Is there some use-case I'm not seeing?

A: I should've done some more testing. It looks like this is a bug.
The point of wrapping code in an anonymous module is to not pollute the toplevel namespace with constants/methods defined in the code. rb_load does this wrapping properly, rb_eval_string_wrap does not.


text:
Q: How to reduce I/O on EC2 micro instance running wordpress I have been running a very small wordpress site on Amazon EC2 for about 2 months, using the free tier micro instance.
I have been getting billed a few dollars each month for going over the disk I/O allowance.
I have looked into how I can reduce the disk I/O, and made some changes such add allowing browser caching of images by changing apache.conf, minimising images and plugins, etc.
I then added APC module to PHP.  I expected this to reduce I/O a lot, but it seems to be making no difference.
APC status (apc.php):
http://oi41.tinypic.com/30t5gud.jpg
vmstat output during the load of a single webpage:

It seems that there is I/O going on during the load of the webpage.  I don't understand why, since the PHP should be in the APC cache and the images are already cached in my browser.
My goal is to simply reduce I/O, and therefore cost. Is there anything I can do to achieve this?  For example, is APC setup incorrectly or is there some other technique to avoid I/O?
(PS: W3TC wordpress plugin didnt work for me.  I probably didn't install it correctly - it locked me out of the site, overloaded the CPU and brought the site down.)

A: We can see that your instance is running very low on memory, and is actually swapping. This is disk I/O for which you'll get billed, and also causes your site to run slower.
Free up some memory by stopping unnecessary processes and tuning your web server to run fewer workers (e.g. Apache or php-fpm).

A: A few things...

*

*Try something like batcache for Wordpress, as it only caches the pages that are hit frequently and thus reduces some overhead from pre-caching everything

*I'd recommend switching to NGINX for your HTTP server if you have very little memory available. It's super efficient.

*Check the resource utilization of MySQL. In 99% of cases, it is configured too generously and eats all available server memory.


text:
Q: Saving json as an array of objects I have an angular app that looks like this:
(function (){
    var app = angular.module('world', []);

    app.controller('WorldController', function(){
        this.tabs = tabs;
    });

    var tabs =[
    {
        id: "1",
        name: "first tab name",
        title: "first tab title",
        content: "first tab cont"
    },
    {
        id: "2",
        name: "orci, consectetuer",
        title: "sem elit, pharetra ut,",
        content: "augue scelerisque mollis. Phasellus"
    },
    {
        id: "3",
        name: "rhoncus. Nullam velit dui, semper et, lacinia vitae,",
        title: "Nam porttitor",
        content: "tellus eu augue porttitor interdum. Sed auctor odio a purus."
    },
    {
        id: "4",
        name: "nulla magna, malesuada vel, convallis in, cursus et, eros. Proin",
        title: "montes, nascetur ridiculus mus.",
        content: "Sed eget lacus. Mauris non dui nec urna suscipit nonummy."
    }
    ];

})();

I want to load the whole tabs array from a json. I have no problem to generate a json and fetch it, but I don't know how to convert it into the format as shown above.
When I try to do var tabs=jQuery.getJSON('myJson.json');,  the json is fetched, but it's not loaded in the format that I want.
How can I convert a json into the format of the array shown above?
While my json looks like that -
[
    {
        "id": "1",
        "name": "mus. Proin vel arcu eu odio tristique pharetra.",
        "title": "faucibus",
        "content": "Donec dignissim magna a tortor. Nunc commodo auctor"
    },
    {
        "id": "2",
        "name": "orci, consectetuer",
        "title": "sem elit, pharetra ut,",
        "content": "augue scelerisque mollis. Phasellus"
    },
    {
        "id": "3",
        "name": "rhoncus. Nullam velit dui, semper et, lacinia vitae,",
        "title": "Nam porttitor",
        "content": "tellus eu augue porttitor interdum. Sed auctor odio a purus."
    },
    {
        "id": "4",
        "name": "nulla magna, malesuada vel, convallis in, cursus et, eros. Proin",
        "title": "montes, nascetur ridiculus mus.",
        "content": "Sed eget lacus. Mauris non dui nec urna suscipit nonummy."
    }
];

A: Use the $http service in angular.  For example, if you have a data.json file in the same folder that contains the json data then use
app.controller('MainCtrl', function($scope, $http) {
  $http.get('data.json').success(function(data){
    $scope.fetched = data;
  })
});

Here is a plunker example.


text:
Q: In Kotlin, how do I create an instance of a class where the class name is a variable? I am writing a Graph class in Kotlin. Here's my code so far:
import java.util.*

class Graph<Class>(connectionProb: Double) {
    // a general network class
    val nodes = mutableListOf<Class>()
    val connectionProb = connectionProb
    val connections = hashMapOf<Class, MutableList<Class>>()

    var nextID = 0

    private fun createNode() {
        // Here is where I need help
    }
}

I want to be able to specify the node type for each Graph. The code above will compile, but I'm unsure how to initialize new nodes. The only argument I want to pass into each node, regardless of its type, is nextID.
Thanks!

A: First thing you should do is define a class for your graph node, and instead of maintaining a map for connections, let every node maintain a list of its connections.
So your code would look like this
class Graph<T>(connectionProb: Double) {

var nextId = 0
val nodes = mutableListOf<Node<T>>()

// Define a node class, so if you have graph of Integer then you want a node of Integer
class Node<T>(var id: Int){
    val connections = mutableListOf<Node<T>>()

    fun addConnection(newConnection: Node<T>){
        connections.add(newConnection)
    }

    override fun toString() = "$id"
    /** add other functions, such as remove etc */
}

fun createNode(){
    var newNode = Node<T>(nextId++)
    nodes.add(newNode)
}

}
Now to use this graph you will do followig
fun main(){
    var myGraph = Graph<Integer>(10.9)
    myGraph.createNode()
    myGraph.createNode()
    myGraph.nodes[0].addConnection(myGraph.nodes[1])

    /* Print all nodes in graph */
    for(node in myGraph.nodes) print("  $node")

    /* Print connections of first node */
    for(node in myGraph.nodes[0].connections) print("\n\nConnection id: $node")
}

Please note that this will give you a general idea of how to go about implementing graph and there are many things that you can improve in the implementation. To learn more I suggest you read a good book, such as Data Structures and Algorithms in Java


text:
Q: How to perform multiple comparison for microarray data in R I'm new to R and multiple comparison tests for diferentially expressed genes. I'm reading this book called Bioinformatics and Computational Biology Solutions using R and Bioconductor by Robert Gentleman, Rafael A. Irizarry, Vincent J. Carey, Sandrine Dudoit, Wolfgang Huber. I'm currently in chapter 15 and working on the example in the book. I think I understood most of it, but what I didn't understand is how is MTP package performing multiple tests. Here's the code from the book
library("ALL")
library("hgu95av2")
data(ALL)

runMTP <- function()
ffun <- filterfun(pOverA(p = 0.2, A=100), cv(a=0.7, b=10))
filt <- genefilter(2^exprs(ALL), ffun)
filtALL <- ALL[filt, ]
filtX <- exprs(filtALL)
pheno <- pData(filtALL)
Bcell <- rep(0, length(pData(ALL)$BT))
Bcell[grep("B", as.character(pData(ALL)$BT))] <- 1
seed <- 99
cache(BT.boot <- MTP(X=filtX, Y=Bcell, alternative ="greater", B=100, method = "sd.minP", seed = seed))

So, I understand filtX has 431 different genes and 128 different patients. But Y=Bcell contains 128 1s and 0s (1 for B-cell, and 0 for T-cell). Can anyone please help me understand how it's doing the multiple comparison test with adj p value? Are they just using pairwise.t.test(X, Y, p.adjust.method="bonferroni")? or are they doing something diffent? And if they're using the above code to get the adj. P-value, what goes in X and Y and how is it determined from the matrix filtX? Also, the MTP is also bootstrapping, but what is it bootstrapping? Can you give me an example of one genetype and tell me how to do this for all the other ones?
I'd really appreciate if someone can help me understand this in simple words.
Thank you.

A: I figured it out myself. I was looking at it in completely unrelated manner. There's no need to do pairwise t test. What I found out is that MTP function is taking the data set and performing the t test on each row based on the cell types. This will produce n t-tests and n p-values, which is then used to create adjusted p-values using step-down minP procedure for which bootstrapping is used.

A: I use JMP trial software to run the PCA implemented therein with nicely performed correlations. If you have data less than 300X300 try SPSS and STATISTICA. Mev, Genesis, Mayday and Expander software have many usefull functions too.


text:
Q: ignore option of jquery validate crashes my bootstrap wizard This is my first question, so please be patient with me.
Im using a combination of jquery-validate and bootstrap wizard.
Everything works fine except the ignore options. I need to use it for including hidden checkboxes. If you put just anything in the ignore option the whole bootstrap wizard isnt working anymore. But no errors are displayed.
See my fiddle: https://jsfiddle.net/danzhtyn/1/
HTML:

    <form name="ad" method="post" action="" id="ad_form" role="form" enctype="multipart/form-data">

Test 1

Test 2

                      Anzeigentext
                      <textarea id="ad_adtext" name="ad[adtext]" required="required" rows="15" class="form-control"></textarea>

                        <input type="checkbox" id="ad_categories_14" name="ad[categories][]" class="hidden" value="14" /> Computer
                        <input type="checkbox" id="ad_categories_14" name="ad[categories][]" class="hidden" value="15" /> Greets

    </form>

JS:
        $(document).ready(function() {

    var $form = $("#ad_form"),
    $validator = $form.validate({
        ignore: ":disabled",
      rules: {
        "ad[adtext]": {
          required: true
        },
        "ad[categories][]": {
          required: true,
          minlength: 1
        },
      },
      messages: {
        "ad[adtext]": "Dies ist ein Pflichtfeld! Bitte geben Sie einen Wert an.",
        "ad[category][]": "Dies ist ein Pflichtfeld! Bitte wählen Sie mindestens eine Rubrik aus.",
      }
    });
  $('#rootwizard').bootstrapWizard({
    onNext: function(tab, navigation, index) {

      var $valid = $form.valid();
      if (!$valid) {
        $validator.focusInvalid();
        return false;
      }

    },
    onTabShow: function(tab, navigation, index) {

      var $total = navigation.find('li').length;
      var $current = index + 1;
      var $percent = ($current / $total) * 100;
      $('#rootwizard .progress-bar').css({
        width: $percent + '%'
      });

    },
    onTabChange: function(tab, navigation, index) {

      var $valid = $form.valid();
      if (!$valid) {
        $validator.focusInvalid();
        return false;
      }

    }
  });
});

Remove ignore: ":disabled" and everything works fine.
Any suggestions?


text:
Q: How to Create a Disposable class I have this 'PlayerClass' class and every time I instantiate it I need to dispose of it, including the fields inside that class. Is there a way to do it? This is my class:
internal class PlayerClass
{
    public WindowsMediaPlayer _wplayer;
}

How do I get to dispose of the class after using it?
I have tried to find a way on the internet but none of them are working after testing it.
I've tried this:
internal class PlayerClass : IDisposable
{
    public WindowsMediaPlayer _wplayer;
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    /// <summary>
    /// Is this instance disposed?
    /// </summary>
    protected bool Disposed { get; private set; }

    /// <summary>
    /// Dispose worker method. See http://coding.abel.nu/2012/01/disposable
    /// </summary>
    /// <param name="disposing">Are we disposing?
    /// Otherwise we're finalizing.</param>
    protected virtual void Dispose(bool disposing)
    {
        Disposed = true;
    }
}

What am I doing wrong?

A: It looks as if you're implementing IDisposable just for the heck of it which is not necessary for managed code. The garbage collector will automatically clean up behind you.
You may need to clarify in your post why you are implementing IDisposable.
However I believe your mistake is that Dispose() is not automatically called by the garbage collector. If you do implement IDisposable you must make sure that the code using your class either instantiates inside a using() statement or manually calls .Dispose. Otherwise your dispose method will never fire.
using(var player = new PlayerClass()){
    // Do something with player
    // player.Dispose() is called automatically when you exit this using statement.
}

Since you're relying on the caller to make sure Dispose is called you may also want to look into a SafeHandle (preferred) or Finalize.

Because the IDisposable.Dispose implementation is called by the
consumer of a type when the resources owned by an instance are no
longer needed, you should either wrap the managed object in a
SafeHandle (the recommended alternative), or you should override
Object.Finalize to free unmanaged resources in the event that the
consumer forgets to call Dispose.

Source: IDisposable Interface
Using Statement
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

A: Contrary to the advice of the other answers, it is necessary and essential to Dispose of all created objects that implement a Dispose() method (ie implement IDisposable). These objects are unmanaged resources, and thus are invisible to the GC. Not disposing of them is a guaranteed memory leak.(Note that some terminology prefers a Close() method to a Dispose method, in which case the Close() method should be identical.)
Here is a best practice implementation of the IDisposable interface.
#region IDisposable implementation with finalizer
private bool isDisposed = false;
public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
protected virtual void Dispose(bool disposing) {
  if (!isDisposed) {
    if (disposing) {
      if (_wplayer != null)     _wplayer.Dispose();
   }
  }
  isDisposed = true;
}
#endregion

Here are the Best Practices Dos and Donts from the MSDN link above:

*

*DO declare a protected virtual void Dispose(bool disposing) method to
centralize all logic related to releasing unmanaged resources.

*DO implement the IDisposable interface by simply calling Dispose(true) followed by GC.SuppressFinalize(this).

*DO NOT make the parameterless Dispose method virtual.

*DO NOT declare any overloads of the Dispose method other than Dispose() and Dispose(bool).

*DO allow the Dispose(bool) method to be called more than once. The method might choose to do nothing after the first call.

*AVOID throwing an exception from within Dispose(bool) except under critical situations where the containing process has been corrupted (leaks, inconsistent shared state, etc.).

*CONSIDER providing method Close(), in addition to the Dispose(), if close is standard terminology in the area.

A: From the MSDN documentation.

Provides a mechanism for releasing unmanaged resources.

You do not need to dispose managed objects. .Net will lead with this for you. It is usefull when you create a interop classes which will lead with unmanaged resources, then you can dispose all objects.


text:
Q: Check if a list contains any value from a vector in R I want to create a binary column that shows whether another column, which is a list of characters, contains any value from a vector.
Specifically, I want to create a column that says whether one has experienced their manager leaving a company in the past year. For this, I have a all_manager column that is a list of all managers one had in the last year. And then, I have a terminated_managers vector that has all names of managers who have terminated in the past year.
df$all_manager

[[1]]
[1] John Mary

[[2]]
[1] Paul John

[[3]]
[1] Mary Tom Lilly

terminated_managers <- c("Mary", "Bill")

And I want to create manager_termed_yn column such that:
df$manager_termed_yn

[1]TRUE
[2]FALSE
[3]TRUE

I'll appreciate your help! First time posting, so apologies that the example is not the best.

A: all_manager <- list(c("John", "Mary"), c("Paul", "John"), c("Mary", "Tom", "Lilly"))
terminated_managers <- c("Mary", "Bill")

We can use
colSums(sapply(all_manager, "%in%", x = terminated_managers)) > 0
#[1]  TRUE FALSE  TRUE

A: Let list l as
l <- list("John Mary","Paul John", "Mary Tom Lilly")
l

[[1]]
[1] "John Mary"

[[2]]
[1] "Paul John"

[[3]]
[1] "Mary Tom Lilly"

Then
sapply(l, function(x) {sum(match(str_split(x, " ", simplify = T), terminated_managers), na.rm = T) == 1}, simplify = T)

[1]  TRUE FALSE  TRUE

A: Let's first create some example data to work with that looks similar to your own.
# Example data
set.seed(123)
data <- replicate(5, list(paste0(sample(letters, size = 5, replace = T), collapse = "")))
data
#> [[1]]
#> [1] "osncj"
#>
#> [[2]]
#> [1] "rvket"
#>
#> [[3]]
#> [1] "nvyze"
#>
#> [[4]]
#> [1] "syyic"
#>
#> [[5]]
#> [1] "hzgji"

# Example vector
vec <- c("osn", "rvket", "foo")

Your data are currently stored as a list. From the looks of it, each element of the list has 1 name in it stored as a character vector. My guess about this is because for every row of the output you showed that starts with DOUBLE brackets (e.g. [[1]], [[2]], etc.), there is only one row below it that starts with single brackets (and the index of those are always [1]).
class(data)
#> [1] "list"

Given you have this data structure, you can convert this into a vector:
df2vec <- unlist(data)
df2vec
#> [1] "osncj" "rvket" "nvyze" "syyic" "hzgji"

We can determine if the values in df2vec exactly match values in vec:
df2vec %in% vec
#> [1] FALSE  TRUE FALSE FALSE FALSE

And here are the values that appear in both:
df2vec[df2vec %in% vec]
#> [1] "rvket"

If we want to look for partial matches instead that would, for example, return TRUE when matching "Rob" to "Robert Frost", we need substring pattern matching:
partials <- grepl(df2vec, pattern = paste(vec, collapse = "|"))

partials
#> [1]  TRUE  TRUE FALSE FALSE FALSE

df2vec[partials]
#> [1] "osncj" "rvket"

A: Here is a tidyverse solution:
library(tidyverse)

df %>%
  rowwise %>%
  mutate(manager_termed_yn = any(unlist(all_manager) %in% terminated_managers))

Output
  id      all_manager manager_termed_yn
1  1       John, Mary              TRUE
2  2       Paul, John             FALSE
3  3 Mary, Tom, Lilly              TRUE

Data
df <- structure(list(id = 1:3, all_manager = list(c("John", "Mary"),
    c("Paul", "John"), c("Mary", "Tom", "Lilly"))), row.names = c(NA,
-3L), class = "data.frame")

terminated_managers <- c("Mary", "Bill")


text:
Q: Differentiate MVC routing for {Controller}/parameter to {Controller}/{action}?param=myvalue I must be able to deal with a route like this:
MyController/ElementType
For that purpose I've created a custom route like this:
  context.MapRoute(
                  "NameOfTheRoute",
                  "MyPath/{controller}/{elementType}",
                  new { controller = "Elements", action = "Create" }
                  );

And it works fine, the problem is when I have a route like
/MyPath/Elements/GetElementType?elementType=fire88
GetElementType is a different action, but it goes to the Create action because of the custom route I declared before, how can I let know the routing they are different actions?

A: the reason why it going to this route because you didn't define a route to handle action  so MyPath/{controller}/{elementType} means after the name of controller everything will be considered as {elementType} so
you have to create another another route which will handle action
routes.MapRoute(
    "MyPathRouteWithAction",
    "MyPath/{controller}/{action}/{elementType}",
    new {controller = "Elements", action = "Create"}
);

routes.MapRoute(
    "NameOfTheRoute",
    "MyPath/{controller}/{elementType}",
    new {controller = "Elements", action = "Create"}
);

the first custom route will handle routs like /MyPath/Elements/GetElementType/fire88


text:
Q: ¿Cómo asignar el resultado de un case_when a todas las filas de un grupo definido con group_by? Estoy trabajando con la ENOE y quiero asignar a cada hogar el nivel educativo del "Jefe o jefa de hogar", código 101 en la variables par_c. La idea es crear una nueva columna en la que cada fila de un grupo (es decir, para todos los miembros del hogar) se repita el la escolaridad del jefe.
La n real es casi 500k, entonces el ahorro de RAM y el desempeño importan.
Así se ven los datos mínimos:

id_hogar
par_c
cs_p13_1

1000
101
Preparatoria o bachillerato

1000
201
Secundaria

1000
301
Preparatoria o bachillerato

1001
101
Preparatoria o bachillerato

1002
101
Profesional

1002
201
Carrera técnica

1002
301
Profesional

1002
418
Profesional

1002
408
Secundaria

1003
101
Maestría

1004
101
Primaria

1005
101
Preparatoria o bachillerato

1005
301
Preparatoria o bachillerato

1005
301
Profesional

Y así se reproducen:
library(tidyverse)
library(haven)  #Para las etiquetas de cs_p13_1, son datos importados de stata

structure(list(id_hogar = c(1000L, 1000L, 1000L, 1001L, 1002L,
1002L, 1002L, 1002L, 1002L, 1003L, 1004L, 1005L, 1005L, 1005L
), par_c = structure(c(101, 201, 301, 101, 101, 201, 301, 418,
408, 101, 101, 101, 301, 301), format.stata = "%12.0g"), cs_p13_1 = structure(c(5L,
4L, 5L, 5L, 8L, 7L, 8L, 8L, 4L, 9L, 3L, 5L, 5L, 8L), .Label = c("Ninguno",
"Preescolar", "Primaria", "Secundaria", "Preparatoria o bachillerato",
"Normal", "Carrera técnica", "Profesional", "Maestría", "Doctorado",
"No Sabe"), class = "factor")), row.names = c(NA, -14L), class = c("tbl_df",
"tbl", "data.frame")) -> datos

La solución que tengo:
datos %>%
  group_by(id_hogar) %>%
  mutate(escolaridad_jefe = case_when(par_c == 101 ~ cs_p13_1)) %>%
  fill(escolaridad_jefe, .direction = "downup")

Que funciona muy rápido con los datos de ejemplo, pero no me parece óptima. Es muy lento con el caso real porque son 500k filas, condiciones más complejas y, sobre todo, muchas variables las que tengo que crear así. Entonces tengo que hacer un fill para cada variable y el código se pone complicado de mantener.
¿Hay alguna manera directa para que el mutate(case_when)) asigne el valor output a todas las filas del grupo? Por diseño de la encuesta sé a priori que un solo jefe/a por hogar.
nest() no es una opción, anidar y desanidar demoran un minuto por operación.

PD: una solución no tidyverse (base, data.table) es bienvenida.

A: Probaría con un left_join()
datos %>%
  left_join(datos %>%
              filter(par_c == 101) %>%
              select(id_hogar, escolaridad_jefe = cs_p13_1),
            by = "id_hogar")

La subconsulta filtra los casos de "Jefe o jefa de hogar" y nos quedamos con su nivel educativo. Finalmente al relacionar por el id_hogar todas las filas heredan el nivel del jefe.
En cuanto a la performance, no puedo asegurar nada, pero posiblemente al ser menos "verbos" y más simples, puede que mejore algo el comportamiento.


text:
Q: sqlite3 one_file VFS Fails I was trying to run test_onefile.c example from sqlite3 VFS examples, and I get the following failure:
test_onefile: test_onefile.c:693: fsDelete: Assertion `strpcmp("-journal", &zPath[nName])==0' failed.

I'm running the code as follows:
int retval;
fs_register();
int q_cnt = 5,q_size = 150,ind = 0;
char **queries = (char**) malloc(sizeof(char) * q_cnt * q_size);

sqlite3_stmt *stmt;
sqlite3 *handle;

retval =  sqlite3_open_v2( "sampledb.sqlite2", &handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE , "fs");

  if(retval)
  {
      printf("Database connection failed\n");
      return -1;
  }
  printf("Connection successful\n");

  // Create the SQL query for creating a table
  char create_table[100] = "CREATE TABLE IF NOT EXISTS users (uname TEXT,pass TEXT NOT NULL,activated INTEGER)";

  // Execute the query for creating the table
  retval = sqlite3_exec(handle,create_table,0,0,0);

  // Insert first row and second row
  queries[ind++] = "INSERT INTO users VALUES('manish','mani',1)";
  retval = sqlite3_exec(handle,queries[ind-1],0,0,0);
  queries[ind++] = "INSERT INTO users VALUES('mehul','pulsar',0)";
  retval = sqlite3_exec(handle,queries[ind-1],0,0,0);

Edit:
The file it fails on is sampledb.sqlite2-wal, clearly not a journal file. However, I don't understand how it reached it.
Edit2:
Well, after removing the assertion in source file:
assert(strcmp("-journal", &zPath[nName])==0);
The code seems to work. However, I'm not a big fan of assertion deletion, as clearly it would lead to some unexpected behavior. The author had a reason to use the assertion.

A: The VFS implemented by test_onefile.c is quite old, and therefore does not support the additional files required for WAL mode.
To make it work with a modern SQLite, the fsDelete function should just ignore attempts to delete -wal or -shm files.


text:
Q: What should the length of public key on ECDH be? I am working on a project to implement ECDH on an Android app and My problem is related to Java implementation, it generates a longer public key than I expected.
// Generate ephemeral ECDH keypair
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
kpg.initialize(256);
KeyPair kp = kpg.generateKeyPair();
byte[] ourPk = kp.getPublic().getEncoded();
System.out.println("ourPk len is " + ourPk.length);
// Display our public key
console.printf("Public Key: %s%n", printHexBinary(ourPk));

As far as I know or learn from here, if it is a 256-bit curve (secp256k1), keys will be:
Public key: 32 bytes * 2 + 1 = 65 (uncompressed)
Private key: 32 bytes

I expect the output (len of ourPk) 65, but the actual one is 91.

A: As pointed out in comments you should refer to RFC5480 and its sections 2 and 2.2. kp.getPublic().getEncoded() will return DER encoded subject public key info. To extract EC public key from it - have a look at this code. I am using BouncyCastle library for DER objects handling :
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
kpg.initialize(256);
KeyPair kp = kpg.generateKeyPair();
byte[] ourPk = kp.getPublic().getEncoded();
System.out.println("ourPk len is " + ourPk.length);

ASN1Sequence sequence = DERSequence.getInstance(ourPk);

DERBitString subjectPublicKey = (DERBitString) sequence.getObjectAt(1);

byte[] subjectPublicKeyBytes = subjectPublicKey.getBytes();

System.out.println("EC key length : " + subjectPublicKeyBytes.length);

The output is :
ourPk len is 91
EC key length : 65


text:
Q: Is it possible to make Inkscape autotrace PNG to SVG, but from the command line? I want to automate "raster to vector" conversions. PNG to SVG. (most Qs here on SO are the other way around)
I have tried the old command line tool  autotrace on Linux, but I could not get it to run. I've tried to install a package, and to compile it from the source. Nope.
Then I've realised that Inkscape has "autotrace" now integrated in its codebase. I'd like to convert simple sketches from PNG to SVG.
And I want to do this in a Bash for-loop , with different autotrace settings (number of passes; ignore Speckles with max X pixels width) etc.
I've tried the "action" command-line option
inkscape --without-gui --actions="file-open:my.png"

and this brings up the small "png bitmap image import" dialog, waiting for me to confirm.
Also I've tried the verb command line option
inkscape --with-gui  --verb="FileImport:my.png"

and this opens the large "Select file to import" dialog (ignoring my --verb argument)
At this point I gave up.
I want Inkscape to import a PNG picture, autotrace it with some settings, save it as SVG. Perhaps, beofre saving, duplicate the traced layer, lock the imported background layer, rename the layers from path-12345 to "tracesettings-x-y-z" etc.
(my final goal is to permute the tracing settings, to find good ones for my use-case, but that's not the focus of this question)

A: Inkscape is using potrace and autotrace to trace bitmap images into vector formats such as SVG and PDF.
Let's assume you have an image: foo.png that you want to trace to SVG using potrace:

*

*First, you need to convert your image to a bitmap format (BMP).

*Invoke the potrace command

# I am using ImageMagick convert command to convert PNG to BMP
convert foo.png foo.bmp

# Invoke potrace command with SVG backend
potrace -b svg foo.bmp

The result will be: foo.svg.


text:
Q: Why does the ToSimplifyText remain unchanged? I tried to create a program which would remove the 4000 most used words from some text you put in using a prompt. This I did with a loop which removes words you find on the list one by one until the index reaches the end of the list and you have removed all 4000 (see code below). The problem is that nothing gets removed and my output is the same as input. My input is the text "The Chungus" and "The" is the first word on the list.
I have checked if every function and datatype is correct, and indeed if I remove the loop and substitute numbers for the CurrentSpaceIndex and CurrentWordStart, then the output is correct: "Chungus".
var x = "The be and of a in to have to ... "; //It's a list of the 4000 most used words in english. 4000 words with a space between them. The length of the string is 29307 characters, so the last character will have index 29306..

var ToSimplifyText = prompt("Please enter the text you wish to simplify:", "");

var WordToRemove;

var CurrentSpaceIndex = 0;

var CurrentWordStart = 0;

var CurrentChar;

while(CurrentSpaceIndex < 29307){
    CurrentChar = x.charAt(CurrentSpaceIndex);
    if (CurrentChar = " "){
    WordToRemove = x.substring(CurrentWordStart, CurrentSpaceIndex);
    ToSimplifyText = ToSimplifyText.replace(WordToRemove, "");
    CurrentWordStart = CurrentSpaceIndex + 1;
    }
    CurrentSpaceIndex = CurrentSpaceIndex + 1;
}
alert(ToSimplifyText);

I expect the output to be Chungusinstead of the unchanged The Chungus.

A: You are doing it very hard way. You can do it in following steps:

*

*Convert both strings to array of words using split()

*Then filter() the words from the user input which is present in words array.

*At last use join() and return the result.

var x = "The be and of a in to have to"; //It's a list of the 4000 most used words in english. 4000 words with a space between them. The length of the string is 29307 characters, so the last character will have index 29306..
var ToSimplifyText = prompt("Please enter the text you wish to simplify:", "");

const removeWords = (str,words) => str.split(' ').filter(x => !words.includes(x)).join(' ');

ToSimplifyText = removeWords(ToSimplifyText,x.split(' '))

alert(ToSimplifyText);

Why Your code doesnot work?
The reason is the use of Assigment Operator instead of comparison operator.
if (CurrentChar = " ")

should be
if (CurrentChar === " ")

var x = "The be and of a in to have to"; //It's a list of the 4000 most used words in english. 4000 words with a space between them. The length of the string is 29307 characters, so the last character will have index 29306..

var ToSimplifyText = prompt("Please enter the text you wish to simplify:", "");

var WordToRemove;

var CurrentSpaceIndex = 0;

var CurrentWordStart = 0;

var CurrentChar;

while(CurrentSpaceIndex < x.length){
    CurrentChar = x.charAt(CurrentSpaceIndex);
    if (CurrentChar === " "){
    WordToRemove = x.substring(CurrentWordStart, CurrentSpaceIndex);
    console.log(WordToRemove)
    ToSimplifyText = ToSimplifyText.replace(WordToRemove, "");
    CurrentWordStart = CurrentSpaceIndex + 1;
    }
    CurrentSpaceIndex = CurrentSpaceIndex + 1;
}
alert(ToSimplifyText);


text:
Q: How to properly align three-level enumerate 1. 1.1. 1.1.1 I've created my environment, and modified the enumerate command:
\renewcommand{\labelenumi}{\arabic{enumi}.}
\renewcommand{\labelenumii}{\arabic{enumi}.\arabic{enumii}.}
\renewcommand{\labelenumiii}{\arabic{enumi}.\arabic{enumii}.\arabic{enumiii}.}

\newenvironment{packed_enum}{
\begin{enumerate}
\setlength{\itemsep}{1pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt}
}{\end{enumerate}}

And this is what i get:

The first two levels align properly (I've marked it with blue line), but the third level starts too much on the left (red line). Can You help me fix this?
I've tried something like this  (also with changing labelsep to \leftmargin):
\renewcommand{\labelenumi}{\arabic{enumi}.}
\renewcommand{\labelenumii}{\arabic{enumi}.\arabic{enumii}.}
\renewcommand{\labelenumiii}{\setlength{\labelsep{5ex}\arabic{enumi}.\arabic{enumii}.\arabic{enumiii}.}

or this:
\renewcommand{\labelenumi}{\arabic{enumi}.}
\renewcommand{\labelenumii}{\arabic{enumi}.\arabic{enumii}.}
\renewcommand{\labelenumiii}{\hbox{\hspace{5ex}\arabic{enumi}.\arabic{enumii}.\arabic{enumiii}.}}

but neither helped.

A: If you're loading the enumitem package, you might as well use the commands it provides for making list-type environments, namely
\newlist{packed_enum}{enumerate}{5}
\setlist[packed_enum]{label*=\arabic*.,leftmargin=*}

Here's a complete MWE that produces the same output as the other answer.
% arara: pdflatex
% !arara: indent: {overwrite: yes}
\documentclass{article}
\usepackage{enumitem}

\newlist{packed_enum}{enumerate}{5}
\setlist[packed_enum]{label*=\arabic*.,leftmargin=*}

\begin{document}

\begin{packed_enum}
    \item First level
    \begin{packed_enum}
        \item Second level
        \begin{packed_enum}
            \item Third level
        \end{packed_enum}
    \end{packed_enum}
\end{packed_enum}

\end{document}

A: With the help of enumitem
\newenvironment{packed_enum}{%
  \renewcommand{\labelenumi}{\arabic{enumi}.}%
  \renewcommand{\labelenumii}{\arabic{enumi}.\arabic{enumii}.}%
  \renewcommand{\labelenumiii}{\arabic{enumi}.\arabic{enumii}.\arabic{enumiii}.}%
  \begin{enumerate}[itemsep=1pt,parsep=0pt,leftmargin=*]%
  }{\end{enumerate}}

The option leftmargin=* ensures that the label is aligned with the surrounding text. Note that I also inserted all \renewcommands inside the \newenvironment to make the changes only locally.
MWE:
\documentclass{article}
\usepackage{enumitem}

\newenvironment{packed_enum}{%
  \renewcommand{\labelenumi}{\arabic{enumi}.}%
  \renewcommand{\labelenumii}{\arabic{enumi}.\arabic{enumii}.}%
  \renewcommand{\labelenumiii}{\arabic{enumi}.\arabic{enumii}.\arabic{enumiii}.}%
  \begin{enumerate}[itemsep=1pt,parsep=0pt,leftmargin=*]%
  }{\end{enumerate}}

\begin{document}

\begin{packed_enum}
  \item First level
  \begin{packed_enum}
    \item Second level
    \begin{packed_enum}
      \item Third level
    \end{packed_enum}
  \end{packed_enum}
\end{packed_enum}

\end{document}

Output:


text:
Q: Open XML String in Web Browser I have an XML string and can convert the whole string to a hyperlink. When clicked on, is there a way I can open it in a browser formatted as an XML?

A: Yes you can with some browsers and with some plugins. There is an xml viewer plugin for both firefox and chrome. Do set the header to type xml though instead of html.

A: Well there is no general defined formatting for XML, if the XML is not a format like XHTML or SVG or MathML the browser knows to render and if it is not styled with CSS or XSLT then browser usually show the source as a collapsible tree:

Example link with data URL representing an XML document

That works fine for me with Mozilla browsers like Firefox, IE however complains and refuses to render anything, Chrome renders the text content of the XML instead of its source tree.


text:
Q: Conversion of a small XML containfg different data values to POJO I am currently writing a parser for a simple XML. The XML at its longest contains 18 lines. I am trying to parse it and convert it to a POJO. I know that I can use JAXB or similar libraries, but I felt that considering the size of the XML, that would be an overkill. Also, this is an exercise to think beyond libraries.
An example XML would be:
<machineinfo>
    <processorCount>4</processorCount>
    <boughtDate>2014-06-09 23:17:49.0</boughtDate>
    <installationStatus>COMPLETE</installationStatus>
    <machineType>BASIC</machineType>
    <osVersion>1849AB48DOED</osVersion>
    <serverName>fjv920dk</serverName>
    <machineStatus>UP</machineStatus>
    <statusPay1>NA</statusPay1>
    <statusPay2>NA</statusPay2>
    <errorCode>NO_ERROR</errorCode>
    <exceptionCode>0</exceptionCode>
    <isCloneable>true</isCloneable>
    <latestVersion>1849AB48DOED</latestVersion>
    <mastermachineName/>
    <podName>8D2</podName>
    <machineName>machine2</machineName>
</machineinfo>

My core conversion logic is as follows:
if (tagName.equalsIgnoreCase("processorCount")) {
    machineInfo.setProcessorCount(new Integer(data).intValue());
} else if (tagName.equalsIgnoreCase("boughtDate")) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
    DateTime dt = formatter.parseDateTime(data);
    machineInfo.setBoughtDate(dt);
} else if (tagName.equalsIgnoreCase("installationStatus") {
    machineInfo.setInstallationStatus(InstallationStatus.valueOf(data));
} else if (tagName.equalsIgnoreCase("installationStatus") {
    machineInfo.setInstallationStatus(InstallationStatus.valueOf(data));
}

As you can see, this leads to multiple if conditions. I tried simplifying that by using a Map as follows:
Map <String, Object> map = new HashMap<String, Object>();
map.put("machineName", data);
map.put("machineType", data);
String mapValue = (String) map.get(tagName);

But how do I determine which setter in machineInfo should be invoked?

A: You should use Java Reflection or Java Beans API for that.
I like to invoke dynamic setters using PropertyDescriptor:
Method writerMethod = new PropertyDescriptor(fieldName, MachineInfo.class).getWriteMethod();
writerMethod.invoke(machineInstance, fieldValue);

Refer to http://docs.oracle.com/javase/7/docs/api/java/beans/PropertyDescriptor.html
Regards,
Bruno

A: I solved this by using the following snippet:
ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
convertUtilsBean.deregister(DateTime.class);
convertUtilsBean.register(new JodaDateTimeConverter(), DateTime.class);
BeanUtilsBean beanUtilsBean = new BeanUtilsBean(convertUtilsBean, new PropertyUtilsBean());

try {
    beanUtilsBean.setProperty(machineInfo, qName, temp);
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (InvocationTargetException e) {
    e.printStackTrace();
}

And by creating the following converter:
class JodaDateTimeConverter implements Converter {

    /* (non-Javadoc)
     * @see org.apache.commons.beanutils.Converter#convert(java.lang.Class, java.lang.Object)
     */
    @SuppressWarnings("unchecked")
    public <T> T convert(Class<T> arg0, Object arg1) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
        DateTime dt = formatter.parseDateTime((String) arg1);
        return (T) dt;
    }
}


text:
Q: Views not found for Alert Dialog in fragments I am trying to populate an Alert Dialog (with a layout file having an EditText & Button) within a fragment of Activity.
The components are not being found by calling findViewById() in the fragment's corresponding class. I have written this code inside the class :
    AlertDialog.Builder builder=new AlertDialog.Builder(context);
    View v=getLayoutInflater().inflate(R.layout.layout_alert_dialog,null);
    final EditText txtAddNew=v.findViewById(R.id.txtAddNew);                //null
    final TextView txtErr = v.findViewById(R.id.txtErr);                    //null
    Button btnAdd=v.findViewById(R.id.btnAdd);                              //null

I think the problem raises from this line of code:
 View v=getLayoutInflater().inflate(R.layout.layout_alert_dialog,null);

The alertDialog XML code is below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/txtAddNew"
        android:hint="Category name"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtErr"
    />
    <Button
        android:id="@+id/btnAdd"
        android:text="Add Category" />
</LinearLayout>

Can anyone find what the actual problem is? Thanks!

A: Yes, that's correct
Do something like this :
LayoutInflater layout = LayoutInflater.from(this);
final View view = layout.inflate(R.layout.dialog_layout, null);
final AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setView(view);
dialog.show();

A: You can do it like below.
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
alertBuilder.setView(getLayoutInflater().inflate(R.layout.layout_alert_dialog,null));
AlertDialog alertDialog = alertBuilder.create();
EditText txtAddNew = alertDialog.findViewById(R.id.txtAddNew);
TextView txtErr = alertDialog.findViewById(R.id.txtErr);
Button btnAdd = alertDialog.findViewById(R.id.btnAdd);
alertDialog.show();

A: Try using dialog.setContentView(v)
See the difference between setView(v) and setContentView(v) here:
What is difference between Dialog.setContentView( View ) & AlertDialog.setView( View )