text:
Q: Python: nearest neighbour (or closest match) filtering on data records (list of tuples) I am trying to write a function that will filter a list of tuples (mimicing an in-memory database), using a "nearest neighbour" or "nearest match" type algorithim.
I want to know the best (i.e. most Pythonic) way to go about doing this. The sample code below hopefully illustrates what I am trying to do.
datarows = [(10,2.0,3.4,100),
            (11,2.0,5.4,120),
            (17,12.9,42,123)]

filter_record = (9,1.9,2.9,99) # record that we are seeking to retrieve from 'database' (or nearest match)
weights = (1,1,1,1) # weights to approportion to each field in the filter

def get_nearest_neighbour(data, criteria, weights):
    for each row in data:
        # calculate 'distance metric' (e.g. simple differencing) and multiply by relevant weight
    # determine the row which was either an exact match or was 'least dissimilar'
    # return the match (or nearest match)
    pass

if __name__ == '__main__':
    result = get_nearest_neighbour(datarow, filter_record, weights)
    print result

For the snippet above, the output should be:
(10,2.0,3.4,100)
since it is the 'nearest' to the sample data passed to the function get_nearest_neighbour().
My question then is, what is the best way to implement get_nearest_neighbour()?. For the purpose of brevity etc, assume that we are only dealing with numeric values, and that the 'distance metric' we use is simply an arithmentic subtraction of the input data from the current row.

A: Simple out-of-the-box solution:
import math

def distance(row_a, row_b, weights):
    diffs = [math.fabs(a-b) for a,b in zip(row_a, row_b)]
    return sum([v*w for v,w in zip(diffs, weights)])

def get_nearest_neighbour(data, criteria, weights):
    def sort_func(row):
        return distance(row, criteria, weights)
    return min(data, key=sort_func)

If you'd need to work with huge datasets, you should consider switching to Numpy and using Numpy's KDTree to find nearest neighbors. Advantage of using Numpy is that not only it uses more advanced algorithm, but also it's implemented a top of highly optimized LAPACK (Linear Algebra PACKage).

A: About naive-NN:
Many of these other answers propose "naive nearest-neighbor", which is an O(N*d)-per-query algorithm (d is the dimensionality, which in this case seems constant, so it's O(N)-per-query).
While an O(N)-per-query algorithm is pretty bad, you might be able to get away with it, if you have less than any of (for example):

*

*10 queries and 100000 points

*100 queries and 10000 points

*1000 queries and 1000 points

*10000 queries and 100 points

*100000 queries and 10 points

Doing better than naive-NN:
Otherwise you will want to use one of the techniques (especially a nearest-neighbor data structure) listed in:

*

*http://en.wikipedia.org/wiki/Nearest_neighbor_search (most likely linked off from that page), some examples linked:

*

*http://en.wikipedia.org/wiki/K-d_tree

*http://en.wikipedia.org/wiki/Locality_sensitive_hashing

*http://en.wikipedia.org/wiki/Cover_tree
especially if you plan to run your program more than once. There are most likely libraries available. To otherwise not use a NN data structure would take too much time if you have a large product of #queries * #points. As user 'dsign' points out in comments, you can probaby squeeze out a large additional constant factor of speed by using the numpy library.
However if you can get away with using the simple-to-implement naive-NN though, you should use it.

A: use heapq.nlargest on a generator calculating the distance*weight for each record.
something like:
heapq.nlargest(N, ((row, dist_function(row,criteria,weight)) for row in data), operator.itemgetter(1))


text:
Q: How many (reduced) quadratic forms represent a given prime? For a given prime $p$, how many (reduced) quadratic forms represent it?
(inspired by this question)
Is it enough to just find quadratic residues of $p$ (as candidates for the discriminant) and count which ones are 0 or 1 modulo 4, or is it more involved (as in "class number" complicated)? And can the resulting number of forms be deduced from $p$ using more elementary means? Is it always finite? Does it have any asymptotic behavior?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to Import tflite-support package. Receiving error "DLL load failed: The specified module could not be found" I have been trying to install tflite-support package in my Anaconda Environment. These were the steps followed by me:

*

*Created a new python environment using conda create --name test_env python==3.7

*Installed tensorflow using conda install tensorflow (Since pip install gives import error on my PC)

*Then installed the tflite-suppport package using pip install tflite-support (conda install throws PackagesNotFoundError Error)

The following code snippet can be used to reproduce the error:
import tensorflow as tf
from tflite_support import flatbuffers
from tflite_support import metadata as _metadata
from tflite_support import metadata_schema_py_generated as _metadata_fb

Which throws the following error:
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-4-37cdba048740> in <module>
----> 1 from tflite_support import flatbuffers
      2 from tflite_support import metadata as _metadata
      3 from tflite_support import metadata_schema_py_generated as _metadata_fb

c:\programdata\anaconda3\envs\testx\lib\site-packages\tflite_support\__init__.py in <module>
     28
     29 import flatbuffers as _flatbuffers
---> 30 from tensorflow_lite_support.metadata import metadata as _metadata
     31 from tensorflow_lite_support.metadata import metadata_schema_py_generated as _metadata_schema_py_generated
     32 from tensorflow_lite_support.metadata import schema_py_generated as _schema_py_generated

c:\programdata\anaconda3\envs\testx\lib\site-packages\tensorflow_lite_support\metadata\metadata.py in <module>
     32 from tensorflow_lite_support.metadata import metadata_schema_py_generated as _metadata_fb
     33 from tensorflow_lite_support.metadata import schema_py_generated as _schema_fb
---> 34 from tensorflow_lite_support.metadata.cc.python import _pywrap_metadata_version
     35 from tensorflow_lite_support.metadata.flatbuffers_lib import _pywrap_flatbuffers
     36

ImportError: DLL load failed: The specified module could not be found.

I have tried with different versions of python, tensorflow & tflite-support, but I get the same error everytime. Thanks in advance!

A: I did exactly the same as you did but I didn't mention any Python version and it works fine for me.
My python version is 3.8.5


text:
Q: Leaderstats not working? or just not detecting the click? I am trying to make a Simulator game on Roblox but I just can't seem to get the leader stats to work or it does work and my click event thing doesn't work, I am just following a tutorial for the scripting so I have no clue. This is my Remotes script where it says print("IS THIS WORKING") that was to see what was the problem. Basically that doesn't run or there's another problem that stops that from running, I think at least. I have other scripts and I will put some in that I think might be neccesary but if you need more feel free to ask me.
local replicatedStorage = game:GetService("ReplicatedStorage")
local remoteData = game:GetService("ServerStorage"):WaitForChild("RemoteData")

local cooldown = 1
print("IS THIS WORKING")

replicatedStorage.Remotes.Lift.OnServerEvent:Connect(function(player)

    if not remoteData:FindFirstChild(player.Name) then return "NoFolder" end

    local debounce = remoteData[player.Name].Debounce

    if not debounce then

        debounce.Value = true

        player.leaderstats.Stealth.Value = player.leaderstats.Stealth.Value + 25 *(player.leaderstats.Rebirths.Value + 1)
        wait(cooldown)

        debounce.Value = false

    end

Stats
local serverStorage = game:GetService("ServerStorage")

game.Players.PlayerAdded:Connect(function(player)

    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player

    local stealth = Instance.new("NumberValue")
    stealth.Name = "Stealth"
    stealth.Parent = leaderstats

    local rebirths = Instance.new("IntValue")
    rebirths.Name = "Rebirths"
    rebirths.Parent = leaderstats

    local Folder = Instance.new("Folder")
    Folder.Name = player.Name
    Folder.Parent = serverStorage.RemoteData

    local debounce = Instance.new("BoolValue")
    debounce.Name = "Debounce"
    debounce.Parent = Folder

    end)

ModuleScript
local module = {}

local replicatedStorage = game:GetService("ReplicatedStorage")
function module.Lift()

    replicatedStorage.Remotes.Lift:FireServer()

end
return module

LocalScript
local module = require(script.Parent:WaitForChild("ModuleScript"))
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

script.Parent.Activated:Connect(function()
    module.Lift()
end)

For my Explorer Structure click
here

A: local remoteData = game:GetService("ServerStorage"):WaitForChild("RemoteData")

your problem is when it waits for a child it yields the script until RemoteData is found
later in the script, it checks if RemoteData is nil or not
 if not remoteData:FindFirstChild(player.Name) then return "NoFolder" end

two solutions:
first is to add a max wait for the yield so it will eventually stop if it can't find RemoteData (only useful is RemoteData is added after the script starts running)
second is the replace wait with FindFirstChild that will check immediately without waiting for it
the solution I recommend
local remoteData = game:GetService("ServerStorage"):FindFirstChild("RemoteData")

secondary solution if you have RemoteData added after the script starts and want to double-check
local remoteData = game:GetService("ServerStorage"):WaitForChild("RemoteData",20)

be sure to tell me is this works as I spent a while figuring it out


text:
Q: C program doesn't open file passed as argument I'm writing a program that takes 2 filenames as arguments, then it opens it and elaborates the data.
Problem is that it doesn't open the second file, for some reason.
int main(int argc, char *argv[]) {

    FILE *fltr_file, *ig_file;

    ig_file = fopen(argv[2], "r");
    fltr_file = fopen(argv[3], "r");
}

fltr_file points to NULL (0x0) when I run the program. It takes ig and fltr as arguments, both files are present in the program's directory.

A: The argv[0] is the program name, the argv[1] is the first parameter.
If your program accepts only two arguments, you probably need indices 1 and 2:
ig_file = fopen(argv[1], "r");
fltr_file = fopen(argv[2], "r");


text:
Q: Clustered NodeJS only changes worker on hard reload on Desktop Chrome I'm experimenting with clusters and nodejs. I have this simple server that returns the current PID of a worker. To test it, I have an Angular application that makes 100 $http.get() calls on the '/pid' endpoint (code included below).
Chrome for Desktop returns the same PID for all 100 calls in about 8 seconds on a normal load/reload. If I hard reload (ctrl + shift + r), I get 4 separate PIDS randomly in about 3 seconds. Clearly, there's a performance boost there, but I can't seem to get the same result with a standard load/reload.
I get the desired behavior in Firefox and Chrome Android.
I haven't really been able to find much about this. I don't think it's an Angular caching issue, because it works correctly on other browsers.
I tried adding a no-cache meta tag to my html, just in case, but that didn't change anthing.
I've attempted this on my computer and another, to make sure it's not something funky with my setup.
Any thoughts on what I can do to make this work correctly on chrome on every load?
NodeJS Code
var express = require('express');
var cluster = require('express-cluster');
var cors = require('cors');
var fs = require('fs');
cluster(function(worker) {
    var app = express();
    app.use(express.static('public'));
    app.use(cors())
    app.get('/pid', function (req, res) {
        for(var i = 0; i < 10000; i++) {
        //increase load with loop, to increase need for workers
        }
      res.send("" + worker.process.pid);
    });
    console.log("Worker id: " + worker.id);
    return app.listen(3009);
}, {count:4});

Angular Code
angular.module('cluster', []).controller('mainCtrl',['$http','$scope', function($http, $scope){
    $scope.pids = [];
    for(var i = 0; i < 100; i++) {
      $http.get("http://localhost:3009/pid").then(function(response) {
        $scope.pids.push(response.data);
      }, function(error) {

      });
    }
}]);

Bad Output (Normal Chrome reload)
20990
20990
20990
20990
...

Expected Output (Chrome Hard Reload/Other Browsers)
20817
20743
20818
20746
...

The HTML is just an ng-repeat on the pids array.
This is running on a EC2 instance with only 1 core, on a MEAN Bitnami stack.


text:
Q: How can I list all implemented traits for a given type during compilation in a macro? I'm looking for a way to find all traits implemented for a given type, during compilation, for use within a macro.
My use case is that I'd like to write a macro that creates newtype structs and implements all inner type traits, or at least a subset of them.

A: You can't.

The Rustc Driver:
[…] the main phases of the compiler are:

*

*Parse Input: Initial crate parsing

*Configure and Expand: Resolve #[cfg] attributes, name resolution, and expand macros

*Run Analysis Passes: Run trait resolution, typechecking, region checking and other miscellaneous analysis passes on the crate

*Translate to LLVM: Translate to the in-memory form of LLVM IR and turn it into an executable/object files

(emphasis is mine)
Macros are expanded before trait resolution is done, so at the time your macro is expanded, type information is unknown.


text:
Q: Access data outside for loop I have a main class and a UI class.
Let me do some explaining first. What i am doing currently, is processing some jar files to find all of the classname inside them (to use later with reflection)
In main, i do things and process data and in the UI there is a JTabbedPane that loads a JFrame when a plugin is correctly loaded (To do so, I share the UI class from main and then invoke it).
Now, to make this dynamic, i made a nice for loop that loops through all jars and gets all the classnames.
Question is, how do i access those strings found in the for loop externally?
EDIT
A commenter pointed out that I could just declare the strings outside the for loop, problem is I have no clue on how many jars i will load and for the sake of user convenience, I'd like to keep the main program as it is (so no updates, just plugin updates that can be handled inside the jar itself at runtime)
Sorry if this is dumb.

A: As people in the comments said your best choice would be to declare a list of String outside the loop:
List<String> classnames = new ArrayList<String>();
for(String classname : jar) {
    classnames.add(classname);
}

Something like this.


text:
Q: Rails - putting elements inside Div from view rendered using helper in HAML I have two views that creates functioning modal. Top one is made with helper method
.modal-header
  %button.close{"aria-hidden" => "true", "data-dismiss" => "modal", :type => "button"} ×
  %h3.modal-title
    = title
.modal-body
  (some necessary code)

And after that there is the second file with content of that modal that looks like this:
generate_top(title)
(...)

Now when Rails generate this as a HTML, content of second view is separately of <div class="modal-body"> in which it should be. Is there any good way to insert view from second file into that modal-body div without moving class declaration from first?

A: Ok, so after all I couldn't find good answer to my problem, so I took different approach:
Instead of generating modal-header using helper, I modified my modal layout like this:
#mainModal{:class => "modal", :tabindex => "-1", :role => "dialog" , "aria-labelledby" => "mainModalLabel", "aria-hidden" => "true"}
  .modal-dialog
    .modal-content
      .modal-header
        %button.close{"aria-hidden" => "true", "data-dismiss" => "modal", :type => "button"} ×
        %h3.modal-title
          =yield :title if content_for? :title
      .modal-body
        (that necessary code that was mentioned before)
        =yield

And now I add title to modals by content_for method:
=content_for :title do
  ={Modal title}


text:
Q: Is it possible to get a character at terminal cursor using ANSI escape codes? I know I can move the cursor with the escape codes, and I can also print at the cursor. What I'd like to know is if it is possible to pull the character under the cursor.
I tried searching for such a code, but failed. So I assume it is not possible, but I'd like to ask if there is some way I failed to find.

A: This is not possible unless you modify your terminal emulator to make it possible; use curses library or equivalent.


text:
Q: Hive Table Data with MapReduce I am facing the following error while executing MapReduce job in Linux(CentOS).
I added all the jars in classpath. The database name and table name already in the hive database with some column of data in the table. Then also I can't able to access the data from the hive database table.
I'm using vanilla version of hadoop for work.
Should i need to edit hive-site.xml file by mysql driver path, username and password for hive?.
if yes please tell me the procedure to add username and password for hive.
Thank you in advance

murali]# hadoop jar /home/murali/workspace/hadoop/HiveInputForMapper/target/HiveInputForMapper-0.0.1-SNAPSHOT.jar com.cosmonet.HiveInputDriver -libjars $LIBJARS
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/hadoop/hadoop/share/hadoop/common/lib/slf4j-log4j12-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/murali/.m2/repository/org/slf4j/slf4j-log4j12/1.7.5/slf4j-log4j12-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
Java HotSpot(TM) Server VM warning: You have loaded library /hadoop/hadoop/lib/native/libhadoop.so which might have disabled stack guard. The VM will try to fix the stack guard now.
It's highly recommended that you fix the library with 'execstack -c <libfile>', or link it with '-z noexecstack'.
14/11/20 18:21:04 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
14/11/20 18:21:05 INFO metastore.HiveMetaStore: 0: Opening raw store with implemenation class:org.apache.hadoop.hive.metastore.ObjectStore
14/11/20 18:21:05 INFO metastore.ObjectStore: ObjectStore, initialize called
14/11/20 18:21:05 INFO DataNucleus.Persistence: Property datanucleus.cache.level2 unknown - will be ignored
14/11/20 18:21:05 INFO DataNucleus.Persistence: Property hive.metastore.integral.jdo.pushdown unknown - will be ignored
14/11/20 18:21:07 INFO metastore.ObjectStore: Setting MetaStore object pin classes with hive.metastore.cache.pinobjtypes="Table,StorageDescriptor,SerDeInfo,Partition,Database,Type,FieldSchema,Order"
14/11/20 18:21:07 INFO metastore.MetaStoreDirectSql: MySQL check failed, assuming we are not on mysql: Lexical error at line 1, column 5.  Encountered: "@" (64), after : "".
14/11/20 18:21:08 INFO DataNucleus.Datastore: The class "org.apache.hadoop.hive.metastore.model.MFieldSchema" is tagged as "embedded-only" so does not have its own datastore table.
14/11/20 18:21:08 INFO DataNucleus.Datastore: The class "org.apache.hadoop.hive.metastore.model.MOrder" is tagged as "embedded-only" so does not have its own datastore table.
14/11/20 18:21:09 INFO DataNucleus.Datastore: The class "org.apache.hadoop.hive.metastore.model.MFieldSchema" is tagged as "embedded-only" so does not have its own datastore table.
14/11/20 18:21:09 INFO DataNucleus.Datastore: The class "org.apache.hadoop.hive.metastore.model.MOrder" is tagged as "embedded-only" so does not have its own datastore table.
14/11/20 18:21:09 INFO DataNucleus.Query: Reading in results for query "org.datanucleus.store.rdbms.query.SQLQuery@0" since the connection used is closing
14/11/20 18:21:09 INFO metastore.ObjectStore: Initialized ObjectStore
14/11/20 18:21:09 INFO metastore.HiveMetaStore: Added admin role in metastore
14/11/20 18:21:09 INFO metastore.HiveMetaStore: Added public role in metastore
14/11/20 18:21:09 INFO metastore.HiveMetaStore: No user is added in admin role, since config is empty
14/11/20 18:21:09 INFO metastore.HiveMetaStore: 0: get_databases: NonExistentDatabaseUsedForHealthCheck
14/11/20 18:21:09 INFO HiveMetaStore.audit: ugi=root ip=unknown-ip-addr cmd=get_databases: NonExistentDatabaseUsedForHealthCheck
14/11/20 18:21:09 INFO metastore.HiveMetaStore: 0: get_table : db=bigdata tbl=categories
14/11/20 18:21:09 INFO HiveMetaStore.audit: ugi=root ip=unknown-ip-addr cmd=get_table : db=bigdata tbl=categories
Exception in thread "main" java.io.IOException: NoSuchObjectException(message:bigdata.categories table not found)
 at org.apache.hive.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:97)
 at org.apache.hive.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:71)
 at com.cosmonet.HiveInputDriver.run(HiveInputDriver.java:27)
 at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
 at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
 at com.cosmonet.HiveInputDriver.main(HiveInputDriver.java:49)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:606)
 at org.apache.hadoop.util.RunJar.main(RunJar.java:212)
Caused by: NoSuchObjectException(message:bigdata.categories table not found)
 at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.get_table(HiveMetaStore.java:1560)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:606)
 at org.apache.hadoop.hive.metastore.RetryingHMSHandler.invoke(RetryingHMSHandler.java:105)
 at com.sun.proxy.$Proxy9.get_table(Unknown Source)
 at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.getTable(HiveMetaStoreClient.java:997)
 at org.apache.hive.hcatalog.common.HCatUtil.getTable(HCatUtil.java:191)
 at org.apache.hive.hcatalog.mapreduce.InitializeInput.getInputJobInfo(InitializeInput.java:105)
 at org.apache.hive.hcatalog.mapreduce.InitializeInput.setInput(InitializeInput.java:86)
 at org.apache.hive.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:95)
 ... 10 more
14/11/20 18:23:10 INFO metastore.HiveMetaStore: 1: Shutting down the object store...
14/11/20 18:23:10 INFO HiveMetaStore.audit: ugi=root ip=unknown-ip-addr cmd=Shutting down the object store...
14/11/20 18:23:10 INFO metastore.HiveMetaStore: 1: Metastore shutdown complete.
14/11/20 18:23:10 INFO HiveMetaStore.audit: ugi=root ip=unknown-ip-addr cmd=Metastore shutdown complete

A: Its seems that your Hadoop installation contain multiple bindings for slf4j, removing one of the binding might solve the problem.
Add following exclusion in the dependencies that caused conflict.
<exclusions>
    <exclusion>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
    </exclusion>
</exclusions>

A: I guess framework could not locate the correct hive metastore.
Try provinding the hive conf file like so.
hadoop --config $HIVE_HOME/conf

A: This solved my issue. While running MapReduce, provide hive's conf directory through --config option hadoop --config $HIVE_HOME/conf jar jar_name MainClass args


text:
Q: Need some clearance on how to write this program I'm reading "C programming a modern approach 2nd edition"
One of the exercises is to write a program, where given in input, breaks down the input and shows how many $20 bills are used, $10, $5 and $1. It says
"To find how many $20 can be used, divide the total by 20, then reduce the amount by the total value of the $20 bills, repeat for the others"
So, this is what I had so far:
int main() {

    int amount, final, twenty, ten, five, one;

    printf("Enter the amount you'd like to use: ");
    scanf("%d", &amount);

    twenty = amount / 20;
    final = amount - (20 * twenty); // Amount is now 13

    ten = final / 10;
    final = 1 * ten;

    five = final / 5;
    final = 5 * five;

    one = final / 1;
    final = 1 * one;

    printf("$20 bills: %d\n", twenty);
    printf("$10 bills: %d\n", ten);
    printf("$5 bills: %d\n", five);
    printf("$1 bills: %d\n", one);

    return 0;
 }

So what I did was:
93 / 4 = 4.65 but truncated it to 4. 4 * 20 = 80 and did 93 - 80, which left me with 13. Now following these instructions, I encounter something wrong. I try the same thing but with $10 bills. 13 / 10 = 1.3 but truncated it to 1. 1 * 10 = 10 13 - 10 = 3 and I don't know how to implement it. The arithmetic in "final" I thought should follow the same setup as the first one:

amount - (20 * twenty) // Amount is now 13

but no dice.
I honestly have been at this for 3 hours, and I just can't do it, would really appreciate an explanation.

A: ten = final / 10;
final = 1 * ten;

Here is the logic error. It should be
ten = final / 10;
final -= ten * 10;

and 5, 1 has similar problem.

A: Each of your individual number checks should actually be in the form of
noOfNUMBERBills = final / NUMBER;
final %= NUMBER;

Where NUMBER is 5, 10 or 20
Read up on modulo (%) right now, you are going to need it a billion time in your programming career.


text:
Q: Can't get child magento theme to work correctly, no changes are made I'm using Magento Ver. 1.8.1.0 and I'm trying to make a child theme of a free theme I've downloaded. I already try to create the following folders copying all files I need from the original theme
public_html/atacadomiranda.com/app/design/frontend/my-pack/my-theme
public_html/atacadomiranda.com/skin/frontend/my-pack/my-theme

Also tried to make a folder called 'custom' inside of the main theme folder where is 'default' folder. Make all changes in DESIGN section of CONFIG ADMIN SESSION. I tried to do some changes to footer.phtml (just for be sure it's working), and no changes are made at all.
What I'm doing wrong?

A: It worked by changing the System->Config to 'custom' folder inside of parent theme folder.


text:
Q: Read Quadrature encoders over I2C bus I need to add encoders to the 4 motors attached to a "remote" PCB.  The remote PCB in question does not have microcontroller on it, but rather is connected to the microcontroller PCB with an I2C connection (yes, using a differential I2C amplifier).  Because of limitations in the cabling I only have the I2C connection between these PCBs.
So, I need to read 4x quadrature encoders over I2C.  Some options and their associated issues:

*

*Read encoders with microcontroller using interrupts.  This seems to be the most common method.  However, I don't have a microcontroller on the remote PCB, so this doesn't work.

*Use a Quadrature decoder chip like the LS7266R1, LS7267 or other dedicated chip.  However, these chips don't seem to be available on any vendor on Octopart, and they are expensive and they don't have an I2C interface.

*Build a quadrature decoder out of a D flip-flop and a counter and connect to an I2C IO expander:  There seem to be a ton design issues with the build it myself approach:  More flip-flops and NAND gates are needed to get full quadrature resolution and counter stability, counters on digikey only come in 4-bit and 8-bit versions (why are 8-bit counters rare and >$10 each?), ... all of this adds up to more cost and complexity than just adding a microcontroller.

Is adding a microcontroller to my remote PCB the best way?  Why isn't there an easier way to do this?  Given the number of digital encoders in the world, I'm surprised there isn't more available.

A:
However, I don't have a microcontroller on the remote PCB.

So put one there!
It is exactly for this type of application where tiny micro controllers are great. There are lots of 8 pin chips which are far, far cheaper then the $10 you mention. You can even implement 10, 12 or 16 bits if you want and have a choice of interfaces you can use to send data upstream.

A: The common mistake is to assume quadrature decoding needs some form of edge detection and counting the edges. It doesn't. You simply need to sample both states twice as often as an edge may occur.
→ Any I²C input chip will do, given the sample rate is high enough.
Do all the computation in your host CPU.

As some people need an example with reasonable numbers:
Let's assume you had four encoders, each one with one division per degree. All your axles rotate with up to 1000RPM. This is 16.67 rounds per second, which gives you 6,000 divisions per second. So you have to sample at 12,000 samples per second.
For example the MCP23008 I²C PIO chip has a continous polling mode which allows you to sample its 8 inputs in just 9 I²C clock cycles. So, to do one sample for four encoders, you need 9 clock cycles.
That means you need an I²C clock of just 108kHz to do that. Feasible? Yes. Uh, and the MCP23008 may be clocked up to 1.7MHz if you happen to need 1° accuracy at 15000RPM.


text:
Q: Use protobuf.js in a browser app I have a very simple browser application, which has to use protobuf:
https://github.com/dcodeIO/protobuf.js
I also have a '.proto' file with a message format, so I just need to encode the incoming messages with protobuf.
Unfortunately I am not able to find, how to bind protobuf in my project. All I find is about node.js, which I am not using.
I also find some information about using require.js to bind protobuf and wrote this in my script:
requirejs.config({
  paths: {
    protobuf:'//cdn.rawgit.com/dcodeIO/protobuf.js/6.8.6/dist/protobuf.js'
  }
});

But it seems to be wrong, as I getthis error in the console:
Uncaught Error: Mismatched anonymous define() module: function (Long) {
            if (Long && Long.isLong) {
                protobuf.util.Long = Long;
                protobuf.configure();
            }
            return protobuf;
        }

If there's anyone who has done anything similar, would you please give me a hand here?
Thanks


text:
Q: Converting a date/math formula in Excel into Numbers for Mac I have a formula in Excel that subtracts a birth date from today's date and divides by 365 which gives the age in decimal format. Example below.
B4 is equal to birthday of 10/03/2011.
E4 is today's date.
The result is 2.73. My child is a little over 2 and 1/2.
=IF(B4>0,(E$4-B4)/365," ")
When I try to use this formula in Numbers for Mac, it gives me an error about comparing dates with numbers and so. I looked at DatedIF, TimeValue, and DateValue but couldn't figure out how to do it in Number.
Anyone know how I could get this formula to return a decimal value of 2.73 years of age?

A: Assuming B4 is in "date" format, you could try the following formula
=IF(ISBLANK(B4),"",YEARFRAC(B4,TODAY(),1))

Here is some documentation on YEARFRAC from the horse's mouth
Try entering the formula
=B4>0

in a different cell, you will then encounter en error

You can't compare a date with a number because their data types are different.


text:
Q: Select the record ids in Yii I have a table and i need to pull all the ids (all the primary keys) corresponding a certain pattern. I need this to be done with the model class in Yii and save them to an array for further processing.

A: Here is one way to do what it seems like you are asking. In this example the model is "People" and the pattern is job_title LIKE "%developer%" -- post-processing is done to put into an array. If you can use an object, skip the post processing.
$criteria=new CDbCriteria;
$criteria->select = 'people_id';
$criteria->condition='job_title LIKE :txt';
$criteria->params=array(':txt'=>'%developer%');
$people=People::model()->findAll($criteria);
// save to array:
$people_a = array();
foreach ($people as $person) {
    $people_a[] = $person['people_id'];
}

A slightly more efficient way to do it (if you need the result to be an array) that allows you to use CommandBuilder and your existing models is:
$model = People::model();
$model->dbCriteria->condition .= 'job_title LIKE :txt';
$model->dbCriteria->select = 'people_id';
$model->dbCriteria->params = array(':txt'=>'%developer%');

$people = $model->getCommandBuilder()
    ->createFindCommand($model->tableSchema, $model->dbCriteria)
    ->queryAll();

$people_a = array();
array_walk($people, function ($value) use (& $people_a) {
    $people_a[] = $value['people_id'];
});

(the anonymous function above assumes PHP 5.3)

A: There is no way to select only IDs with ActiveRecord pattern. You can use CCommandBuilder to build sql query.


text:
Q: conda does not update Hi everybody I am new of Anaconda and VirtualBox,

*

*I installed VirtualBox on Windows 10.

*On the virtual machine, I installed Ubuntu 20.4.4

*Subsequently, I installed Anaconda 4.7.12
I tried to update my current Anaconda version using:
anaconda update anaconda

but the outcome is like that:
ioinfo@bioinfo:~$ conda update conda
Collecting package metadata (current_repodata.json): done
Solving environment: done

==> WARNING: A newer version of conda exists. <==
  current version: 4.7.12
  latest version: 4.13.0

Please update conda by running

    $ conda update -n base -c defaults conda

# All requested packages already installed.

The Anaconda info returns this:
bioinfo@bioinfo:~$ conda info

     active environment : None
            shell level : 0
       user config file : /home/bioinfo/.condarc
 populated config files :
          conda version : 4.7.12
    conda-build version : 3.18.9
         python version : 2.7.16.final.0
       virtual packages :
       base environment : /home/bioinfo/anaconda2  (writable)
           channel URLs : https://repo.anaconda.com/pkgs/main/linux-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/linux-64
                          https://repo.anaconda.com/pkgs/r/noarch
          package cache : /home/bioinfo/anaconda2/pkgs
                          /home/bioinfo/.conda/pkgs
       envs directories : /home/bioinfo/anaconda2/envs
                          /home/bioinfo/.conda/envs
               platform : linux-64
             user-agent : conda/4.7.12 requests/2.22.0 CPython/2.7.16 Linux/5.13.0-52-generic ubuntu/20.04.4 glibc/2.31
                UID:GID : 1000:1000
             netrc file : None
           offline mode : False

Anyone have an idea why conda can't update?


text:
Q: Keyboard shortcuts in an XBAP I would like to support keyboard shortcuts in my WPF XBAP application, such as Ctrl+O for 'Open' etc.  How do I disable the browsers built-in keyboard shortcuts and replace them with my own?

A: You can't disable the browser's built-in handling of keys. It's not your place as browser content to override the browser's own shortcut keys.

A: If you're desperate to do it then you could try adding a windows hook and intercepting the keystrokes you're interested in.
We had to do it to prevent IE help from opening (may God have mercy on my soul).
See:
http://msdn.microsoft.com/en-us/library/system.windows.interop.hwndsource.addhook(VS.85).aspx
And here's some code (ripped out of our app.xaml.vb) which may help (sorry, VB):
Private Shared m_handle As IntPtr
Private Shared m_hook As Interop.HwndSourceHook
Private Shared m_hookCreated As Boolean = False

'Call on application start
Public Shared Sub SetWindowHook(ByVal visualSource As Visual)
    'Add in a Win32 hook to stop the browser app from loading
    If Not m_hookCreated Then
        m_handle = DirectCast(PresentationSource.FromVisual(visualSource), Interop.HwndSource).Handle
        m_hook = New Interop.HwndSourceHook(AddressOf WindowProc)
        Interop.HwndSource.FromHwnd(m_handle).AddHook(m_hook)
        m_hookCreated = True
    End If
End Sub

'Call on application exit
Public Shared Sub RemoveWindowHook()
   'Remove the win32 hook
    If m_hookCreated AndAlso Not m_hook Is Nothing Then
        If Not Interop.HwndSource.FromHwnd(m_handle) Is Nothing Then
            Interop.HwndSource.FromHwnd(m_handle).RemoveHook(m_hook)
        End If
        m_hook = Nothing
        m_handle = IntPtr.Zero
    End If
End Sub

'Intercept key presses
Private Shared Function WindowProc(ByVal hwnd As System.IntPtr, ByVal msg As Integer, ByVal wParam As System.IntPtr, ByVal lParam As System.IntPtr, ByRef handled As Boolean) As System.IntPtr
    'Stop the OS from handling help
    If msg = WM_HELP Then
        handled = True
    End If
    Return IntPtr.Zero
End Function

A: Not an answer, but a comment.  It would be nice to disable the Backspace key behavior in an XBAP, nothing more annoying than hitting the backspace key while not in an element and the browser navigates you to the previous web page.


text:
Q: How to get textblock name for the selected TabItem from TabControl I create dynamically 5 types TabItem for TabControl. For example:
 <Style x:Key="StyleCrcs" TargetType="{x:Type TabItem}">
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="AllowDrop" Value="True"/>
        <EventSetter Event="PreviewMouseMove" Handler="TabItem_PreviewMouseMove"/>
        <EventSetter Event="Drop" Handler="TabItem_Drop"/>
        <Setter Property="ContentTemplate" >
            <Setter.Value>
                <DataTemplate>
                    <Grid>
                        <TextBlock TextWrapping="Wrap" Text="Adres(hex)" FontSize="15" Margin="10,10,396,444"/>
                        <ComboBox x:Name="AddressCrcs" HorizontalAlignment="Left" Margin="134,11,0,0" VerticalAlignment="Top" Width="120">
                            <ComboBoxItem>60</ComboBoxItem>
                            <ComboBoxItem>61</ComboBoxItem>
                            <ComboBoxItem>62</ComboBoxItem>
                            <ComboBoxItem>63</ComboBoxItem>
                            <ComboBoxItem>64</ComboBoxItem>
                            <ComboBoxItem>65</ComboBoxItem>
                            <ComboBoxItem>66</ComboBoxItem>
                            <ComboBoxItem>67</ComboBoxItem>
                        </ComboBox>

                        <TextBlock x:Name="Tranz1" TextWrapping="Wrap" Text="Tranzystor 1:" FontSize="15" Margin="10,126,396,337"/>
                        <TextBlock x:Name="Tranz2" TextWrapping="Wrap" Text="Tranzystor 2:" FontSize="15" Margin="10,156,396,307"/>
                    </Grid>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Each for them have specific constructions.
All of this types inheritance from ICards.
interface ICards
{
    string Name { get; set; }
    string Address { get; set; }
}
class CardCrcs : ICards
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string Tranzystor1 { get; set; }
    public string Tranzystor2 { get; set; }
}

When i create TabItem i add object to list.
Each TabItem has textblocks and I want set text for this textblocks when i change TabItem.
How can i do that?
<TabControl x:Name="TabCards" Grid.Column="1" SelectionChanged="TabCards_SelectionChanged">

var list = new List<ICards>()
var element = (CardCrcs)list[0];
TabCards.SelectedItem.Tranz1.Text = element.Tranzystor1;

TabCards.SelectedItem.Tranz1.Textdont work. How replace this to do that?
EDIT:
When i do that i can take header, but cant take textblock name.
var item = (TabItem)TabCards.SelectedItem;

A: I suggest binding your TabControl to a list of view model instances for which you also provide DataTemplates (that would map as tab item's ContentTemplate).
See this question and its answer for reference.
You seem to already have different view models defined (e.g. CardCrcs class), so you can define DataTemplate objects with TargetType set for each of them, describing how each tab item should look like.
Inside each of these templates you can use Bindings to properties that are defined by the corresponding classes, e.g. <TextBlock Text="{Binding Address}"/>.
Finally, set ItemsSource of TabControl to a list of view model instances that you can prepared in your DataContext if that is your wish: ItemsSource={Binding}.
This approach would limit a lot the code behind, and would be also easier to understand, IMO.


text:
Q: Unsupported ciphersuite TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 I recently received a certificate from Commodo and I'm trying to integrate it with my Scala Spray Server. I have an trait to configure my Spray sever:
import java.io.{BufferedInputStream, FileInputStream}
import java.security.{SecureRandom, KeyStore}
import java.security.cert.{X509Certificate, CertificateFactory}
import javax.net.ssl.{TrustManagerFactory, KeyManagerFactory, SSLContext}
import spray.io._
import org.apache.camel.util.jsse._

// for SSL support (if enabled in application.conf)
trait MySSLConfig {
  // if there is no SSLContext in scope implicitly the HttpServer uses the default SSLContext,
  // since we want non-default settings in this example we make a custom SSLContext available here
  implicit def sslContext: SSLContext = {
    val keyStoreResource = "/home/ubuntu/key.jks"
    val password = "password"

    val keyStore = KeyStore.getInstance("jks")
    keyStore.load(getClass.getResourceAsStream(keyStoreResource), password.toCharArray)
    val keyManagerFactory = KeyManagerFactory.getInstance("SunX509")
    keyManagerFactory.init(keyStore, password.toCharArray)
    val trustManagerFactory = TrustManagerFactory.getInstance("SunX509")
    trustManagerFactory.init(keyStore)
    val context = SSLContext.getInstance("TLS")
    context.init(keyManagerFactory.getKeyManagers, trustManagerFactory.getTrustManagers, new SecureRandom)
    context
  }
  implicit def sslEngineProvider: ServerSSLEngineProvider = {
    ServerSSLEngineProvider { engine =>
      engine.setEnabledCipherSuites(Array("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"))
      engine.setEnabledProtocols(Array("SSLv3", "TLSv1.2", "TLSv1", "TLSv1.1"))
      engine
    }
  }
}

However I am getting this error at runtime when I try and request my uri with https
2015-09-15 02:06:54,662 - [ERROR] - from akka.actor.OneForOneStrategy in NflDbApiActorSystemConfig-akka.actor.default-dispatcher-11
Unsupported ciphersuite TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
java.lang.IllegalArgumentException: Unsupported ciphersuite TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
        at sun.security.ssl.CipherSuite.valueOf(CipherSuite.java:235) ~[na:1.7.0_79]
        at sun.security.ssl.CipherSuiteList.<init>(CipherSuiteList.java:82) ~[na:1.7.0_79]
        at sun.security.ssl.SSLEngineImpl.setEnabledCipherSuites(SSLEngineImpl.java:2014) ~[na:1.7.0_79]
        at com.suredbits.dfs.config.MySSLConfig$$anonfun$sslEngineProvider$1.apply(MySslConfig.scala:34) ~[suredbits-dfs.suredbits-dfs-0.0.1.jar:0.0.1]
        at com.suredbits.dfs.config.MySSLConfig$$anonfun$sslEngineProvider$1.apply(MySslConfig.scala:33) ~[suredbits-dfs.suredbits-dfs-0.0.1.jar:0.0.1]
        at scala.Option.map(Option.scala:145) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.io.SSLEngineProviderCompanion$$anonfun$apply$3.apply(SslTlsSupport.scala:408) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.io.SSLEngineProviderCompanion$$anonfun$apply$3.apply(SslTlsSupport.scala:408) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.io.ServerSSLEngineProvider$$anon$3.apply(SslTlsSupport.scala:427) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.io.ServerSSLEngineProvider$$anon$3.apply(SslTlsSupport.scala:425) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.can.server.HttpServerConnection$$anon$1.sslEngine(HttpServerConnection.scala:78) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.can.server.RequestParsing$$anon$1$$anon$2.<init>(RequestParsing.scala:41) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.can.server.RequestParsing$$anon$1.apply(RequestParsing.scala:39) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.can.server.RequestParsing$$anon$1.apply(RequestParsing.scala:37) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.io.RawPipelineStage$$anon$3.apply(Pipelines.scala:117) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.io.RawPipelineStage$$anon$3.apply(Pipelines.scala:116) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.io.RawPipelineStage$$anon$3.apply(Pipelines.scala:116) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.io.RawPipelineStage$$anon$3.apply(Pipelines.scala:116) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.io.RawPipelineStage$$anon$3.apply(Pipelines.scala:116) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.io.RawPipelineStage$$anon$3.apply(Pipelines.scala:116) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.io.ConnectionHandler$class.running(ConnectionHandler.scala:56) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.can.server.HttpServerConnection.running(HttpServerConnection.scala:29) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.can.server.HttpServerConnection.register(HttpServerConnection.scala:68) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.can.server.HttpServerConnection$$anonfun$receive$1.applyOrElse(HttpServerConnection.scala:49) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at akka.actor.Actor$class.aroundReceive(Actor.scala:465) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at spray.can.server.HttpServerConnection.aroundReceive(HttpServerConnection.scala:29) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at akka.actor.ActorCell.receiveMessage(ActorCell.scala:516) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at akka.actor.ActorCell.invoke(ActorCell.scala:487) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:254) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at akka.dispatch.Mailbox.run(Mailbox.scala:221) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at akka.dispatch.Mailbox.exec(Mailbox.scala:231) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339) ~[suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979) [suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]
        at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107) [suredbits-dfs-nfl-assembly-0.0.1.jar:0.0.1]

Can anyone provide any insight as to why I am getting this error?
EDIT:
I upgraded the jdk to 1.8 as @Steffen Ullrich which yields a new error that I am receiving:
2015-09-15 15:14:51,717 - [ERROR] - from spray.can.server.HttpServerConnection in NflDbApiActorSystemConfig-akka.actor.default-dispatcher-7
Aborting encrypted connection to my-ip due to [SSLHandshakeException:no cipher suites in common] -> [SSLHandshakeException:no cipher suites in common]

2015-09-15 15:14:51,881 - [ERROR] - from spray.can.server.HttpServerConnection in NflDbApiActorSystemConfig-akka.actor.default-dispatcher-4
Aborting encrypted connection to my-ip due to [SSLHandshakeException:no cipher suites in common] -> [SSLHandshakeException:no cipher suites in common]

2015-09-15 15:14:52,029 - [ERROR] - from spray.can.server.HttpServerConnection in NflDbApiActorSystemConfig-akka.actor.default-dispatcher-10
Aborting encrypted connection to my-ip due to [SSLHandshakeException:Client requested protocol TLSv1.1 not enabled or not supported] -> [SSLHandshakeException:Client requested protocol TLSv1.1 not enabled or not supported]

2015-09-15 15:14:52,184 - [ERROR] - from spray.can.server.HttpServerConnection in NflDbApiActorSystemConfig-akka.actor.default-dispatcher-2
Aborting encrypted connection to my-ip due to [SSLHandshakeException:Client requested protocol TLSv1 not enabled or not supported] -> [SSLHandshakeException:Client requested protocol TLSv1 not enabled or not supported]

EDIT2:
I modified this line
engine.setEnabledCipherSuites(sslContext.getServerSocketFactory.getSupportedCipherSuites)

which gives me a list of cipher suites that includes
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256

however I am still getting this error:
2015-09-15 18:43:55,690 - [INFO] - from org.apache.camel.util.jsse.SSLContextParameters in NflDbApiActorSystemConfig-akka.actor.default-dispatcher-9
Available providers: SUN version 1.8.

2015-09-15 18:43:55,696 - [ERROR] - from spray.can.server.HttpServerConnection in NflDbApiActorSystemConfig-akka.actor.default-dispatcher-4
Aborting encrypted connection to my-ip due to [SSLHandshakeException:no cipher suites in common] -> [SSLHandshakeException:no cipher suites in common]

more logs using a more granular debugging mode for -Djava.net.debug=ssl
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
Ignoring disabled protocol: SSLv3
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-42, READ: TLSv1 Handshake, length = 167
*** ClientHello, TLSv1
RandomCookie:  GMT: -265533514 bytes = { 61, 40, 108, 219, 248, 171, 159, 143, 197, 121, 120, 2, 169, 117, 206, 251, 77, 174, 188, 36, 13, 240, 239, 104, 177, 132, 36, 253 }
Session ID:  {}
Cipher Suites: [Unknown 0x56:0x0, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5]
Compression Methods:  { 0 }
Extension server_name, server_name: [type=host_name (0), value=api.extrapoint.io]
Extension renegotiation_info, renegotiated_connection: <empty>
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Unsupported extension type_35, data:
Unsupported extension type_13172, data:
Unsupported extension type_16, data: 00:12:08:73:70:64:79:2f:33:2e:31:08:68:74:74:70:2f:31:2e:31
Unsupported extension status_request, data: 01:00:00:00:00
Unsupported extension type_18, data:
***
%% Initialized:  [Session-868, SSL_NULL_WITH_NULL_NULL]
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-42, fatal error: 40: no cipher suites in common
javax.net.ssl.SSLHandshakeException: no cipher suites in common
%% Invalidated:  [Session-868, SSL_NULL_WITH_NULL_NULL]
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-42, SEND TLSv1 ALERT:  fatal, description = handshake_failure
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-42, WRITE: TLSv1 Alert, length = 2
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-42, fatal: engine already closed.  Rethrowing javax.net.ssl.SSLHandshakeException: no cipher suites in common
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
Ignoring disabled protocol: SSLv3
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-38, READ: TLSv1 Handshake, length = 167
*** ClientHello, TLSv1
RandomCookie:  GMT: -1569487286 bytes = { 25, 54, 227, 33, 169, 61, 202, 196, 56, 250, 139, 68, 8, 183, 153, 237, 234, 230, 40, 91, 244, 198, 29, 236, 243, 121, 109, 28 }
Session ID:  {}
Cipher Suites: [Unknown 0x56:0x0, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5]
Compression Methods:  { 0 }
Extension server_name, server_name: [type=host_name (0), value=api.extrapoint.io]
Extension renegotiation_info, renegotiated_connection: <empty>
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Unsupported extension type_35, data:
Unsupported extension type_13172, data:
Unsupported extension type_16, data: 00:12:08:73:70:64:79:2f:33:2e:31:08:68:74:74:70:2f:31:2e:31
Unsupported extension status_request, data: 01:00:00:00:00
Unsupported extension type_18, data:
***
%% Initialized:  [Session-869, SSL_NULL_WITH_NULL_NULL]
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-38, fatal error: 40: no cipher suites in common
javax.net.ssl.SSLHandshakeException: no cipher suites in common
%% Invalidated:  [Session-869, SSL_NULL_WITH_NULL_NULL]
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-38, SEND TLSv1 ALERT:  fatal, description = handshake_failure
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-38, WRITE: TLSv1 Alert, length = 2
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-38, fatal: engine already closed.  Rethrowing javax.net.ssl.SSLHandshakeException: no cipher suites in common
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
Ignoring disabled protocol: SSLv3
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-45, READ: TLSv1 Handshake, length = 167
*** ClientHello, TLSv1
RandomCookie:  GMT: -1995784349 bytes = { 231, 253, 51, 160, 51, 83, 215, 117, 136, 228, 2, 249, 107, 133, 172, 213, 70, 200, 95, 170, 53, 5, 93, 19, 131, 185, 241, 92 }
Session ID:  {}
Cipher Suites: [Unknown 0x56:0x0, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5]
Compression Methods:  { 0 }
Extension server_name, server_name: [type=host_name (0), value=api.extrapoint.io]
Extension renegotiation_info, renegotiated_connection: <empty>
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Unsupported extension type_35, data:
Unsupported extension type_13172, data:
Unsupported extension type_16, data: 00:12:08:73:70:64:79:2f:33:2e:31:08:68:74:74:70:2f:31:2e:31
Unsupported extension status_request, data: 01:00:00:00:00
Unsupported extension type_18, data:
***
%% Initialized:  [Session-870, SSL_NULL_WITH_NULL_NULL]
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-45, fatal error: 40: no cipher suites in common
javax.net.ssl.SSLHandshakeException: no cipher suites in common
%% Invalidated:  [Session-870, SSL_NULL_WITH_NULL_NULL]
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-45, SEND TLSv1 ALERT:  fatal, description = handshake_failure
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-45, WRITE: TLSv1 Alert, length = 2
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-45, fatal: engine already closed.  Rethrowing javax.net.ssl.SSLHandshakeException: no cipher suites in common
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
Ignoring disabled protocol: SSLv3
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-41, READ: TLSv1 Handshake, length = 208
*** ClientHello, TLSv1.2
RandomCookie:  GMT: -1327152795 bytes = { 83, 242, 3, 179, 176, 55, 11, 121, 181, 163, 83, 1, 237, 23, 101, 140, 177, 179, 40, 128, 77, 190, 63, 204, 162, 105, 4, 57 }
Session ID:  {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5]
Compression Methods:  { 0 }
Extension server_name, server_name: [type=host_name (0), value=api.extrapoint.io]
Extension renegotiation_info, renegotiated_connection: <empty>
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Unsupported extension type_35, data:
Unsupported extension type_13172, data:
Unsupported extension type_16, data: 00:1b:08:73:70:64:79:2f:33:2e:31:05:68:32:2d:31:34:02:68:32:08:68:74:74:70:2f:31:2e:31
Unsupported extension status_request, data: 01:00:00:00:00
Unsupported extension type_18, data:
Extension signature_algorithms, signature_algorithms: SHA256withRSA, SHA384withRSA, SHA512withRSA, SHA1withRSA, SHA256withECDSA, SHA384withECDSA, SHA512withECDSA, SHA1withECDSA, Unknown (hash:0x4, signature:0x2), SHA1withDSA
***
%% Initialized:  [Session-871, SSL_NULL_WITH_NULL_NULL]
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-41, fatal error: 40: no cipher suites in common
javax.net.ssl.SSLHandshakeException: no cipher suites in common
%% Invalidated:  [Session-871, SSL_NULL_WITH_NULL_NULL]
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-41, SEND TLSv1.2 ALERT:  fatal, description = handshake_failure
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-41, WRITE: TLSv1.2 Alert, length = 2
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-41, fatal: engine already closed.  Rethrowing javax.net.ssl.SSLHandshakeException: no cipher suites in common
Using SSLEngineImpl.
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
Ignoring disabled protocol: SSLv3
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-43, READ: TLSv1 Handshake, length = 167
*** ClientHello, TLSv1
RandomCookie:  GMT: -300410757 bytes = { 151, 231, 251, 170, 239, 146, 191, 87, 5, 9, 151, 64, 86, 10, 220, 175, 228, 71, 112, 41, 250, 35, 36, 140, 114, 28, 8, 130 }
Session ID:  {}
Cipher Suites: [Unknown 0x56:0x0, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5]
Compression Methods:  { 0 }
Extension server_name, server_name: [type=host_name (0), value=api.extrapoint.io]
Extension renegotiation_info, renegotiated_connection: <empty>
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Unsupported extension type_35, data:
Unsupported extension type_13172, data:
Unsupported extension type_16, data: 00:12:08:73:70:64:79:2f:33:2e:31:08:68:74:74:70:2f:31:2e:31
Unsupported extension status_request, data: 01:00:00:00:00
Unsupported extension type_18, data:
***
%% Initialized:  [Session-872, SSL_NULL_WITH_NULL_NULL]
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-43, fatal error: 40: no cipher suites in common
javax.net.ssl.SSLHandshakeException: no cipher suites in common
%% Invalidated:  [Session-872, SSL_NULL_WITH_NULL_NULL]
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-43, SEND TLSv1 ALERT:  fatal, description = handshake_failure
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-43, WRITE: TLSv1 Alert, length = 2
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-43, fatal: engine already closed.  Rethrowing javax.net.ssl.SSLHandshakeException: no cipher suites in common
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
Ignoring disabled protocol: SSLv3
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-43, READ: TLSv1 Handshake, length = 167
*** ClientHello, TLSv1.1
RandomCookie:  GMT: -1944581904 bytes = { 65, 211, 112, 212, 209, 223, 205, 60, 175, 177, 83, 168, 139, 174, 78, 221, 40, 69, 103, 105, 117, 231, 103, 50, 53, 237, 22, 58 }
Session ID:  {}
Cipher Suites: [Unknown 0x56:0x0, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5]
Compression Methods:  { 0 }
Extension server_name, server_name: [type=host_name (0), value=api.extrapoint.io]
Extension renegotiation_info, renegotiated_connection: <empty>
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Unsupported extension type_35, data:
Unsupported extension type_13172, data:
Unsupported extension type_16, data: 00:12:08:73:70:64:79:2f:33:2e:31:08:68:74:74:70:2f:31:2e:31
Unsupported extension status_request, data: 01:00:00:00:00
Unsupported extension type_18, data:
***
%% Initialized:  [Session-873, SSL_NULL_WITH_NULL_NULL]
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-43, fatal error: 40: no cipher suites in common
javax.net.ssl.SSLHandshakeException: no cipher suites in common
%% Invalidated:  [Session-873, SSL_NULL_WITH_NULL_NULL]
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-43, SEND TLSv1.1 ALERT:  fatal, description = handshake_failure
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-43, WRITE: TLSv1.1 Alert, length = 2
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-43, fatal: engine already closed.  Rethrowing javax.net.ssl.SSLHandshakeException: no cipher suites in common
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Using SSLEngineImpl.
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
Ignoring disabled protocol: SSLv3
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-41, READ: TLSv1 Handshake, length = 167
*** ClientHello, TLSv1
RandomCookie:  GMT: 584450856 bytes = { 254, 198, 84, 40, 79, 119, 157, 34, 77, 19, 234, 180, 195, 251, 21, 69, 247, 233, 184, 117, 184, 4, 179, 104, 68, 102, 84, 232 }
Session ID:  {}
Cipher Suites: [Unknown 0x56:0x0, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5]
Compression Methods:  { 0 }
Extension server_name, server_name: [type=host_name (0), value=api.extrapoint.io]
Extension renegotiation_info, renegotiated_connection: <empty>
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1}
Extension ec_point_formats, formats: [uncompressed]
Unsupported extension type_35, data:
Unsupported extension type_13172, data:
Unsupported extension type_16, data: 00:12:08:73:70:64:79:2f:33:2e:31:08:68:74:74:70:2f:31:2e:31
Unsupported extension status_request, data: 01:00:00:00:00
Unsupported extension type_18, data:
***
%% Initialized:  [Session-874, SSL_NULL_WITH_NULL_NULL]
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-41, fatal error: 40: no cipher suites in common
javax.net.ssl.SSLHandshakeException: no cipher suites in common
%% Invalidated:  [Session-874, SSL_NULL_WITH_NULL_NULL]
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-41, SEND TLSv1 ALERT:  fatal, description = handshake_failure
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-41, WRITE: TLSv1 Alert, length = 2
NflDbApiActorSystemConfig-akka.actor.default-dispatcher-41, fatal: engine already closed.  Rethrowing javax.net.ssl.SSLHandshakeException: no cipher suites in common

A: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 is a TLSv1.2 cipher suite.
It can not be used with SSLv3 or TLSv1. Also, it might not be even available for the unknown version of Java you are using.
Edit: since it is now known that Java 1.7 is used:
According to the documentation from Oracle no GCM ciphers are available in Java 1.7 but they only got added to Java 1.8. Which explains the message about unsupported cipher.

A: The issue with this was that the key was generated incorrectly. I had to go on to support with COMODO and get help with the key generation.


text:
Q: uploading video from app to youTube iphone sdk I am tring to uplosd a video taken in my app to YouTube.  I have linked the title, the usename , the password, the path to the movie, its length, keywords, and the catagories along with my app key.  Yet when I try to upload I get the following message.
2012-12-02 21:29:33.235 my little world app[12790:907] * Assertion failure in -GDataServiceBase fetchObjectWithURL:objectClass:objectToPost:ETag:httpMethod:delegate:didFinishSelector:completionHandler:retryInvocationValue:ticket:, /Users/nilesh/gdata-objectivec-client-read-only/Source/BaseClasses/GDataServiceBase.m:549
2012-12-02 21:29:33.238 my little world app[12790:907] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'GTMHTTPUploadFetcher needed'
This is the code I use to try to upload it.
- (IBAction)publish: (id) sender;{

    self.mProgressView.hidden =NO;

    NSString *audioName = [pictureDictionary4 objectForKey:@"photoVideokey"];
    NSArray *pathsa = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectorya = [pathsa objectAtIndex:0];
    //Get a full path to the image in the documents directory.
    NSString *fullPatha = [documentsDirectorya stringByAppendingPathComponent:audioName];
    NSError *error = nil;
    NSDictionary *attributes = [[NSFileManager defaultManager]
                                attributesOfItemAtPath:fullPatha error:&error];

    if (!error) {
        NSNumber *size = [attributes objectForKey:NSFileSize];
    }

    NSString *devKey = @"xxxxxx";

    GDataServiceGoogleYouTube *service = [self youTubeService];
    [service setYouTubeDeveloperKey:devKey];

    NSString *username = self.accountView.text;
  NSURL *url = [GDataServiceGoogleYouTube youTubeUploadURLForUserID:username];
    NSData *data = [NSData dataWithContentsOfFile:fullPatha];
    NSString *filename = [pictureDictionary4 objectForKey:@"photoVideokey"];

    // gather all the metadata needed for the mediaGroup
    NSString *titleStr =self.movieNameField.text;
    GDataMediaTitle *title = [GDataMediaTitle textConstructWithString:titleStr];

    NSString *categoryStr = self.catagoryField.text;
    GDataMediaCategory *category = [GDataMediaCategory mediaCategoryWithString:categoryStr];
    [category setScheme:kGDataSchemeYouTubeCategory];

    NSString *descStr = self.descpView.text;
    GDataMediaDescription *desc = [GDataMediaDescription textConstructWithString:descStr];

    NSString *keywordsStr = self.tagsField.text;
    GDataMediaKeywords *keywords = [GDataMediaKeywords keywordsWithString:keywordsStr];

    BOOL isPrivate = NO;

    GDataYouTubeMediaGroup *mediaGroup = [GDataYouTubeMediaGroup mediaGroup];
    [mediaGroup setMediaTitle:title];
    [mediaGroup setMediaDescription:desc];
    [mediaGroup addMediaCategory:category];
    [mediaGroup setMediaKeywords:keywords];
    [mediaGroup setIsPrivate:isPrivate];

    NSString *mimeType = [GDataUtilities MIMETypeForFileAtPath:fullPatha
                                               defaultMIMEType:@"video/mp4"];

    // create the upload entry with the mediaGroup and the file data
    GDataEntryYouTubeUpload *entry;
    entry = [GDataEntryYouTubeUpload uploadEntryWithMediaGroup:mediaGroup
                                                          data:data
                                                      MIMEType:mimeType
                                                          slug:filename];

    SEL progressSel = @selector(ticket:hasDeliveredByteCount:ofTotalByteCount:);
    [service setServiceUploadProgressSelector:progressSel];

    GDataServiceTicket *ticket;
    ticket = [service fetchEntryByInsertingEntry:entry
                                      forFeedURL:url
                                        delegate:self
                               didFinishSelector:@selector(uploadTicket:finishedWithEntry:error:)];

    [self setUploadTicket:ticket];

    NSLog(@"%@",length.text);
    NSLog(@"%@",number.text);
     NSLog(@"%@",accountView.text);
     NSLog(@"%@",tagsField.text);
     NSLog(@"%@",catagoryField.text);
     NSLog(@"%@",movieNameField.text);
     NSLog(@"%@",descpView.text);
     NSLog(@"%@",PasswordDisplayField.text);
     NSLog(@"%@",ViewingField.text);

    NSLog(@"%@",username);
    NSLog(@"%@",url);
    NSLog(@"%@",filename);
    NSLog(@"%@",titleStr);
    NSLog(@"%@",category);
    NSLog(@"%@",categoryStr);
    NSLog(@"%@",descStr);
    NSLog(@"%@",desc);
    NSLog(@"%@",keywords);
     NSLog(@"%@",keywords);
     NSLog(@"%@",keywordsStr);

}

    - (GDataServiceGoogleYouTube *)youTubeService {

        static GDataServiceGoogleYouTube* service = nil;

        if (!service) {
            service = [[GDataServiceGoogleYouTube alloc] init];

            [service setServiceShouldFollowNextLinks:YES];
            [service setIsServiceRetryEnabled:YES];
        }

        // update the username/password each time the service is requested
        NSString *username = [accountView text];
        NSString *password = [PasswordDisplayField text];

        if ([username length] > 0 && [password length] > 0) {
            [service setUserCredentialsWithUsername:username
                                           password:password];
        } else {
            // fetch unauthenticated
            [service setUserCredentialsWithUsername:nil
                                           password:nil];
        }

        NSString *devKey =  @"AI39si5rnzA1o82wzQj_kFFJBQRNEPv29OKD9hx6RxLPzvacvfvLFi_uI9eNj0uq8Cul8VQnBbDs4CAvq7ViKq-RnVCgh3OVBQ";
        [service setYouTubeDeveloperKey:devKey];

        return service;
    }

    // progress callback
    - (void)ticket:(GDataServiceTicket *)ticket
hasDeliveredByteCount:(unsigned long long)numberOfBytesRead
ofTotalByteCount:(unsigned long long)dataLength {

    [mProgressView setProgress:(double)numberOfBytesRead / (double)dataLength];
}

    // upload callback
    - (void)uploadTicket:(GDataServiceTicket *)ticket
finishedWithEntry:(GDataEntryYouTubeVideo *)videoEntry
error:(NSError *)error {
    if (error == nil) {
        // tell the user that the add worked
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Uploaded!"
                                                        message:[NSString stringWithFormat:@"%@ succesfully uploaded",
                                                                 [[videoEntry title] stringValue]]
                                                       delegate:nil
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil];

        [alert show];

    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!"
                                                        message:[NSString stringWithFormat:@"Error: %@",
                                                                 [error description]]
                                                       delegate:nil
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil];

        [alert show];

    }
    [mProgressView setProgress: 0.0];

    [self setUploadTicket:nil];
}

#pragma mark -
#pragma mark Setters

    - (GDataServiceTicket *)uploadTicket {
        return mUploadTicket;
    }

    - (void)setUploadTicket:(GDataServiceTicket *)ticket {

        mUploadTicket = ticket;
    }

I would really appreciate some direction on this.  Thanks

A: It sounds like you're missing the Google Toolbox for Mac - HTTP Fetcher dependency?
In general, you might have more help with questions specific to the Objective-C GData client library if you ask in the dedicated issue tracker or discussion group, since it's really an implementation question rather than a general YouTube API question.

A: I finally got this part working by adding all the correct .h files to my app and importing them, including the right GTMHTTPUploadFetcher file.  Thanks for the help.


text:
Q: Question on logical inferences The instruction of this question is:

Encode the following arguments and show whether they are valid or not.
  If not valid give countermodels i.e., truth assignments to the
  propositions which make them false.
If the investigation continues, then new evidence is brought to light.
  If new evidence is brought to light, then several leading citizens are
  implicated. If several leading citizens are implicated, then the
  newspapers stop publicizing the case. If continuation of the
  investigation implies that the newspapers stop publicizing the case,
  then bringing to light of new evidence implies that the investigation
  continues. The investigation does not continue. Therefore, new
  evidence is not brought to light.

My attempt:
Let $p$ denote "the investigation continues"
    $\quad \space \space q$ denote "new evidence is brought to light"
    $\quad \space \space r$ denote "several leading citizens are implicated"
    $\quad \space \space s$ denote "the newspapers stop publicizing the case"
So, the premises are:
$p \to q $
$q \to r $
$r \to s $
$(p \to s) \to (q \to p)$
$\neg p$
$\therefore \neg q$
I am very much a beginner in logic so I am not sure if this is correct so far or how to prove or disprove this using the standard rules of inference. Any ideas?

A: looks like you missed a couple.
The fourth statement should be:
(p -> s) -> (q -> p)

So we have:
p→q
q→r
r→s
(p→s)→(q→p)
¬p
∴¬q

So by the first three primitives we have p->s. Hence q -> p. So not p implies not q.
I think this checks out, but I my formal logic training is a little weak.

A: Here's a simplification of Zhen Lin's argument. We know
$$ \tag A (p \to s) \to (q \to p)$$
Contrapose this:
$$ \tag B (q\land\neg p) \to (p\land \neg s)$$
Now I'm going to prove $q\to p$ by contradiction. We assume its negation
$$ \tag C q\land \neg p $$
and from this and (B) by modus ponens we can then conclude
$ p\land \neg s $ and in particular $p$. However (C) also trivially implies $\neg p$ which is a contradiction.
Thus, given (A) I have proved
$$\tag D q\to p$$
(And in contrast to Zhen I didn't even need the $\neg p$ premise to do so. On the other hand, my proof is not intuitionistically valid).
Now the story explicitly tells us $\neg p$. Therefore, by modus tollens and (D), we have $\neg q$. Q.E.D.

A: Edit. I assume you meant $(p \to s) \to (q \to p)$ in your fourth premise – but it doesn't actually matter, as we shall see.

*

*Ex falso quodlibet, so
$$\lnot p, p \vdash s$$
and by conditional proof,
$$\lnot p \vdash (p \to s)$$

*By modus ponens,
$$\lnot p, ((p \to s) \to (q \to p)) \vdash (q \to p)$$

*By contraposition,
$$\lnot p, (q \to p) \vdash \lnot q$$

*Putting it all together,
$$\lnot p, ((p \to s) \to (q \to p)) \vdash \lnot q$$
So it turns out the other premises $p \to q, q \to r, r \to s$ are irrelevant for this deduction.

A: You meant, for the fourth premiss,
$$(p \to s) \to (q \to r)$$
Which might help! Intuitively, the first three premisses in PL give you
$$p \to s$$
Modus ponens with the corrected fourth premiss yields
$$q \to r$$
Modus tollens with the fifth premiss gives the conclusion. So it is just a question of following these steps in your preferred formal system.
A general point about such questions in elementary logic texts, however. You should always ask yourself, when translations involving conditionals or "implies" are concerned, whether the validity of the supposed rendering into PL shows (i) that the original argument is valid, or (ii) that the material conditional is here a bad translation of the intuitive content of the original. (After all, you are being asked whether the original argument is valid, and showing a certain rendering of it into PL is valid only settles the matter if the rendering is a good one: and where vernacular conditionals are involved, things can easily go wrong. So you should always, when answering, indicate whether you think that showing the PL argument is valid establishes what is asked.)

A: The text of the problem does not state that you have to use the rules of interference. To show that $\neg q$ holds when $\neg p$ and $(p \rightarrow s)\rightarrow(q \rightarrow p)$ holds you can also use truth tables. The lines were $\neg p$ and $(p \rightarrow s)\rightarrow(q \rightarrow p)$ holds are the lines 1,2,3,4. For these lines the last column is 1 so  $\neg q$ is true.
$$
\begin{array}{ccccccccccccc}
&n&p&q&r&s&p \rightarrow  q&q \rightarrow  r&r \rightarrow  s&(p \rightarrow s)\rightarrow(q \rightarrow p)& \neg p& \neg q\\\hline
&1&0&0&0&0&1&1&1&1&1&1\\
&2&0&0&0&1&1&1&1&1&1&1\\
&3&0&0&1&0&1&1&0&1&1&1\\
&4&0&0&1&1&1&1&1&1&1&1\\
&5&0&1&0&0&1&0&1&0&1&0\\
&6&0&1&0&1&1&0&1&0&1&0\\
&7&0&1&1&0&1&1&0&0&1&0\\
&8&0&1&1&1&1&1&1&0&1&0\\
&9&1&0&0&0&0&1&1&1&0&1\\
&10&1&0&0&1&0&1&1&1&0&1\\
&11&1&0&1&0&0&1&1&1&0&1\\
&12&1&0&1&1&0&1&1&1&0&1\\
&13&1&1&0&0&1&0&1&1&0&0\\
&14&1&1&0&1&1&0&1&1&0&0\\
&15&1&1&1&0&1&1&1&1&0&0\\
&16&1&1&1&1&1&1&1&1&0&0
\end{array}
$$


text:
Q: Aggregate one data frame by time intervals from another data frame I'm trying to aggregate two data frames (df1 and df2).
The first contains 3 variables: ID, Date1 and Date2.
df1
ID      Date1      Date2
 1 2016-03-01 2016-04-01
 1 2016-04-01 2016-05-01
 2 2016-03-14 2016-04-15
 2 2016-04-15 2016-05-17
 3 2016-05-01 2016-06-10
 3 2016-06-10 2016-07-15

The second also contains 3 variables: ID, Date3 and Value.
df2
ID      Date3 Value
 1 2016-03-15     5
 1 2016-04-04     7
 1 2016-04-28     7
 2 2016-03-18     3
 2 2016-03-27     5
 2 2016-04-08     9
 2 2016-04-20     2
 3 2016-05-05     6
 3 2016-05-25     8
 3 2016-06-13     3

The idea is to get, for each df1 row, the sum of df2$Value that have the same ID and for which Date3 is between Date1 and Date2:
ID      Date1      Date2 SumValue
 1 2016-03-01 2016-04-01        5
 1 2016-04-01 2016-05-01       14
 2 2016-03-14 2016-04-15       17
 2 2016-04-15 2016-05-17        2
 3 2016-05-01 2016-06-10       14
 3 2016-06-10 2016-07-15        3

I know how to make a loop on this, but the data frames are huge! Does someone has an efficient solution? Exploring data.table, plyr and dplyr but could not find a solution.

A: A couple of data.table solutions that should scale well (and a good stop-gap until non-equi joins are implemented):
Do the comparison in J using by=EACHI.
library(data.table)
setDT(df1)
setDT(df2)

df1[, `:=`(Date1 = as.Date(Date1), Date2 = as.Date(Date2))]
df2[, Date3 := as.Date(Date3)]

df1[  df2,
      {
        idx = Date1 <= i.Date3 & i.Date3 <= Date2
        .(Date1 = Date1[idx],
          Date2 = Date2[idx],
          Date3 = i.Date3,
          Value = i.Value)
      },
      on=c("ID"),
      by=.EACHI][, .(sumValue = sum(Value)), by=.(ID, Date1, Date2)]

#   ID      Date1      Date2 sumValue
# 1:  1 2016-03-01 2016-04-01        5
# 2:  1 2016-04-01 2016-05-01       14
# 3:  2 2016-03-14 2016-04-15       17
# 4:  2 2016-04-15 2016-05-17        2
# 5:  3 2016-05-01 2016-06-10       14
# 6:  3 2016-06-10 2016-07-15        3

foverlap join (as suggested in the comments)
library(data.table)
setDT(df1)
setDT(df2)

df1[, `:=`(Date1 = as.Date(Date1), Date2 = as.Date(Date2))]
df2[, Date3 := as.Date(Date3)]

df2[, Date4 := Date3]

setkey(df1, ID, Date1, Date2)

foverlaps(df2,
          df1,
          by.x=c("ID", "Date3", "Date4"),
          type="within")[, .(sumValue = sum(Value)), by=.(ID, Date1, Date2)]

#     ID      Date1      Date2 sumValue
# 1:  1 2016-03-01 2016-04-01        5
# 2:  1 2016-04-01 2016-05-01       14
# 3:  2 2016-03-14 2016-04-15       17
# 4:  2 2016-04-15 2016-05-17        2
# 5:  3 2016-05-01 2016-06-10       14
# 6:  3 2016-06-10 2016-07-15        3

Further reading
Rolling join on data.table with duplicate keys
foverlap joins in data.table

A: With the recently implemented non-equi joins feature in the current development version of data.table, v1.9.7, this can be done as follows:
dt2[dt1, .(sum = sum(Value)), on=.(ID, Date3>=Date1, Date3<=Date2), by=.EACHI]
#    ID      Date3      Date3 sum
# 1:  1 2016-03-01 2016-04-01   5
# 2:  1 2016-04-01 2016-05-01  14
# 3:  2 2016-03-14 2016-04-15  17
# 4:  2 2016-04-15 2016-05-17   2
# 5:  3 2016-05-01 2016-06-10  14
# 6:  3 2016-06-10 2016-07-15   3

The column names needs some fixing.. will work on it later.

A: Here's a base R solution using sapply():
df1 <- data.frame(ID=c(1L,1L,2L,2L,3L,3L),Date1=as.Date(c('2016-03-01','2016-04-01','2016-03-14','2016-04-15','2016-05-01','2016-06-01')),Date2=as.Date(c('2016-04-01','2016-05-01','2016-04-15','2016-05-17','2016-06-15','2016-07-15')));
df2 <- data.frame(ID=c(1L,1L,1L,2L,2L,2L,2L,3L,3L,3L),Date3=as.Date(c('2016-03-15','2016-04-04','2016-04-28','2016-03-18','2016-03-27','2016-04-08','2016-04-20','2016-05-05','2016-05-25','2016-06-13')),Value=c(5L,7L,7L,3L,5L,9L,2L,6L,8L,3L));
cbind(df1,SumValue=sapply(seq_len(nrow(df1)),function(ri) sum(df2$Value[df1$ID[ri]==df2$ID & df1$Date1[ri]<=df2$Date3 & df1$Date2[ri]>df2$Date3])));
##   ID      Date1      Date2 SumValue
## 1  1 2016-03-01 2016-04-01        5
## 2  1 2016-04-01 2016-05-01       14
## 3  2 2016-03-14 2016-04-15       17
## 4  2 2016-04-15 2016-05-17        2
## 5  3 2016-05-01 2016-06-15       17
## 6  3 2016-06-01 2016-07-15        3

Note that your df1 and expected output have slightly different dates in some cases; I used the df1 dates.

Here's another approach that attempts to be more vectorized: Precompute a cartesian product of indexes into the two frames, then perform a single vectorized conditional expression using the index vectors to get matching pairs of indexes, and finally use the matching indexes to aggregate the desired result:
cbind(df1,SumValue=with(expand.grid(i1=seq_len(nrow(df1)),i2=seq_len(nrow(df2))),{
    x <- df1$ID[i1]==df2$ID[i2] & df1$Date1[i1]<=df2$Date3[i2] & df1$Date2[i1]>df2$Date3[i2];
    tapply(df2$Value[i2[x]],i1[x],sum);
}));
##   ID      Date1      Date2 SumValue
## 1  1 2016-03-01 2016-04-01        5
## 2  1 2016-04-01 2016-05-01       14
## 3  2 2016-03-14 2016-04-15       17
## 4  2 2016-04-15 2016-05-17        2
## 5  3 2016-05-01 2016-06-15       17
## 6  3 2016-06-01 2016-07-15        3


text:
Q: Difference between Multi Dimension Array and Associative Array I Know what are arrays and how they work but having a problem with multi dimension array using foreach
here is code :
foreach($my_formats_array as $format) {
parse_str($format);
$avail_formats[$i]['itag'] = $itag;
$avail_formats[$i]['quality'] = $quality;
$avail_formats[$i]['ip'] = $ip;
$i++; }

$i is iterator = 0 , loop is running , i incremented as the loop run, but is this happening
$avail_formats[$i]['itag'] = $itag; ?
Could Someone Please explain that with reference link so i can learn about this logic
Where :
$avail_formats[] = '';
$i = 0;
$ipbits = $ip = $itag = $sig = $quality = '';
$expire = time();

Thanks


text:
Q: onmouseover not working I'm trying to get onmouseover and onmouseout to work in some fairly simple PHP code. While the resulting webpage source code shows the HTML markup just fine, for the onmouseover and onmouseout attributes, the anchor continues to show (in the window status bar or equivalent in Chrome, etc.) the original target that I am trying mask.
If I test with a simple html on my desktop, then the onmouseover and onmouseout work fine; they just don't work on pages served on the web. Any ideas of what I am doing wrong? Or is there an alternative I can use? I just don't want people to see the affiliate marketing domain of 'http://www.anrdoezrs.net/click-5510191-10819825' when the link is actually/ultimately going to Groupon, or what not. Hoping there is an easy syntax fix or alternative way of accomplishing this. Thank You.
(These destination variables or in an array; a random one from the array gets chosen to be passed to the HTML.)
$images1[0] = ""

A: Chrome (and most other browsers) doesn't allow websites to change your status bar, because of exactly the sort of abuse you're trying to do here. The entire point of the URL showing up in the bottom-left corner of the browser is to give the user information on where the link is going to go.


text:
Q: Nav bar cuts view on dismiss view controller on iPhone XS Max swift I have two view controllers, VC1 and VC2, First I present VC1 and programmatically create Nav Bar and place two buttons in that, after that I present VC2 and the same I create navbar programmatically. Now when i dimiss VC2 to VC1 it cuts the view to half of navbar and button also get cutoff. I have tried different solutions but not getting it fixed. I'm confused why it is cutting the view? This is my code to create navbar in VC1,
let width = self.view.frame.width
    let navigationBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 20, width: width, height: 64))
    UINavigationBar.appearance().barTintColor = .white
    UINavigationBar.appearance().tintColor = .white
    UINavigationBar.appearance().isTranslucent = false
    self.view.addSubview(navigationBar);
    let navigationItem = UINavigationItem(title: "Owners")
    self.title = "Owners"
    let cancelBtn = UIButton()
    let searchBtn = UIButton()
    cancelBtn.setImage(UIImage.init(named: "cancelBtn")?.tint(with: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)), for: .normal)
    cancelBtn.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
    cancelBtn.addTarget(self, action: #selector(onTapBack), for: .touchUpInside)
    let suggestButtonContainer = UIView(frame: cancelBtn.frame)
    suggestButtonContainer.addSubview(cancelBtn)
    searchBtn.setImage(Icon.cm.search?.tint(with: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)), for: .normal)
    searchBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
    searchBtn.addTarget(self, action: #selector(onTapSearch), for: .touchUpInside)
    let searchView = UIView(frame: searchBtn.frame)
    searchView.addSubview(searchBtn)
    let searchButtonItem = UIBarButtonItem(customView: searchView)
    let suggestButtonItem = UIBarButtonItem(customView: suggestButtonContainer)
    navigationItem.leftBarButtonItem = suggestButtonItem
    navigationItem.rightBarButtonItem = searchButtonItem
    navigationBar.setItems([navigationItem], animated: false)

and this is how i create VC2 navbar,
let width = self.view.frame.width
    let navigationBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 25, width: width, height: 64))
    UINavigationBar.appearance().barTintColor = .white
    UINavigationBar.appearance().tintColor = .white
    UINavigationBar.appearance().isTranslucent = false
    self.view.addSubview(navigationBar);
    let navigationItem = UINavigationItem(title: "Owners")
    self.title = "Owners"
    let cancelBtn = UIButton()
    cancelBtn.setImage(UIImage.init(named: "cancelBtn")?.tint(with: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)), for: .normal)
    cancelBtn.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
    cancelBtn.addTarget(self, action: #selector(onTapBack), for: .touchUpInside)
    let suggestButtonContainer = UIView(frame: cancelBtn.frame)
    suggestButtonContainer.addSubview(cancelBtn)
    let suggestButtonItem = UIBarButtonItem(customView: suggestButtonContainer)
    navigationItem.leftBarButtonItem = suggestButtonItem
    navigationBar.setItems([navigationItem], animated: false)

Now when is dismiss from VC2 to VC1 it shows navbar like this,

A: I think the problem come from the status bar height.
20pt for iPhone 6, 7, 8, ..., and 44pt for iPhones with a notch.
try to set the navigation bar frame origin.y to UIApplication.shared.statusBarFrame.height
let navigationBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: UIApplication.shared.statusBarFrame.height, width: width, height: 64))


text:
Q: Creating an "anonymous enum" within a method (particularly in VB.NET) I'd like to define an enum "on the fly" and use it as a parameter type for calling a method.  Is something like this possible?  Basically, I don't want to have to declare a class-level enum every time I have a method that needs one.
Here's how I would envision using it:
Function GetNumberOfLegs(ByVal ForAnimalType As <here's where I define my anonymous enum>) As Integer
    Select Case ForAnimalType
        Case Cat
            Return 4
        Case Human
            Return 2
    End Select
End Function

It seems reasonable that this should be possible, given that you can define anonymous types and use other related things like lambda expressions.

A: No, basically. Well, you could use an int and some consts - but by the time you've done that, you might as well have used an enum (plus it will be much easier to work with).


text:
Q: Java: How to extract substring between two characters from a string? I am relatively new to Java and I need some help to extract multiple substrings from a string. An example of a string is as given below:
String = "How/WRB can/MD I/PRP find/VB a/DT list/NN of/IN celebrities/NNS '/POS real/JJ names/NNS ?/."

Desired result: WRB MD PRP VB DT NN IN NNS POS JJ NNS
I have a text file with possibly thousands of similar POS-tagged lines that I need to extract the POS tags from and do some calculation based on the POS tags.
I have tried using tokenizer but didn't really get the result I wanted. I even tried using split() and saving to arrays because I need to store it and use it later and that still didn't work.
Lastly, I tried using Pattern Matcher and I am having problems with the regex as it return the word with the forward slash.
Regex: [\/](.*?)\s\b
Result: /WRB /MD ....

If there's a better way to do this, please let me know or if anyone can help me figure out what's wrong with my regex.

A: This should work:
String string = "How/WRB can/MD I/PRP find/VB a/DT list/NN of/IN celebrities/NNS '/POS real/JJ names/NNS ?/.";
System.out.println(string.replaceAll("[^/]+/([^ ]+ ?)", "$1"));

Prints: WRB MD PRP VB DT NN IN NNS POS JJ NNS .

A: If you still wanted to use pattern matching, look at positive lookbehinds. It will allow you to match a word that begins with a slash, but not actually match the slash itself.
An example would be something like this:
(?<=/).+?(?= |$)

Matches anything that starts with a slash, and is followed by a space OR the end of the string
Here is a working example written in Java:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.LinkedList;

public class SO {
    public static void main(String[] args) {
        String string = "How/WRB can/MD I/PRP find/VB a/DT list/NN of/IN celebrities/NNS '/POS real/JJ names/NNS ?/.";
        Pattern pattern = Pattern.compile("(?<=/).+?(?= |$)");
        Matcher matcher = pattern.matcher(string);

        LinkedList<String> list = new LinkedList<String>();

        // Loop through and find all matches and store them into the List
        while(matcher.find()) {
            list.add(matcher.group());
        }

        // Print out the contents of this List
        for(String match : list) {
            System.out.println(match);
        }
    }
}

A: String string = "How/WRB can/MD I/PRP find/VB a/DT list/NN of/IN celebrities/NNS '/POS real/JJ names/NNS ?/.";

string = string .replaceAll("\\S+/", "").replace(".", "");

System.out.println(string );

A: What about str = str.repalceAll("\\S+/", "")? It will replace remove non-whitespace characters followed by slash.


text: Q: Do all accelerating charge emit EM radiation? A nucleus and an electron attract each other, so if they are to remain apart, the energy of the electron's movement must balance the energy of attraction. However, the laws of physics had previously established that a charged particle moving in a curved path must give off energy. If this requirement is applied to an orbiting electron, why did not the electron continuously lose energy and spiral into the nucleus?


text:
Q: OpenCV image convert problem (BayerGB8 to RGB) I am trying to convert an image acquired from a high speed camera using pleora sdk. The documentation / settings from the manufacturers app reads that images are transmitted using BayerGB8.
For further processing and storing I need the image in some sort of RGB/BGR format.
However, my code just shows some weird colors:
using
      cv::Mat bayer8BitMat(lHeight, lWidth, CV_8UC1, dispBuffer->GetDataPointer());
      cv::Mat rgb8BitMat(lHeight, lWidth, CV_8UC3);
      cv::cvtColor(bayer8BitMat, rgb8BitMat, CV_BayerGB2RGB);

      QImage qimg= QImage((uchar*) rgb8BitMat.data, rgb8BitMat.cols, rgb8BitMat.rows, rgb8BitMat.step, QImage::Format_RGB888);

my image looks like this:

using the CV_BayerGB2RGB option gives me the following picture:

another option I tried:
      cv::Mat bayer8BitMat(lHeight, lWidth, CV_8UC1, dispBuffer->GetDataPointer());
      cv::Mat rgb8BitMat(lHeight, lWidth, CV_8UC1);
      cv::cvtColor(bayer8BitMat, rgb8BitMat, CV_BayerBG2RGB);

      QImage qimg= QImage((uchar*) rgb8BitMat.data, rgb8BitMat.cols, rgb8BitMat.rows, rgb8BitMat.step, QImage::Format_RGB16);

shows the following:

The image should approximately look like this (It is very dark where the camera is ...)


text:
Q: Traverse directory and zip certain subdirectories in place How can I bulk-zip folders in subdirectories without including the parent folder in the zip archives? I have a folder structure like this:
folder01
    folder02
        file01
        file02

When I run:
find . -type d -name "folder02" -exec zip -r '{}'.zip '{}' \;

I get "folder02.zip" which always extracts its contents into a parent folder "folder01". How can I prevent this? For me it creates useless parent folder structures when extracting these archives anywhere else.

A: Using some simple bash:
find . -type d -name "folder02" -exec bash -c 'cd "$(dirname "{}")"; zip -r "$(basename "{}")".zip "$(basename "{}")"' \;


text:
Q: Bitmapfactory.decodeFile() with a file in the same directory as the script So I have a script (its a ModPE) and I want to load an image. My question is, how do I load an image using the Bitmapfactory.decodeFile() method which is in the same directory as the script?

A: You can use ./ to define current working directory (CWD)
String myImage = "./myFileInCWD.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(myImage);

The . is important as / means the root or top level directory


text:
Q: Google tag manager - is it possible to push in dataLayer with custom clientID I'm trying to implement UA Enhanced Ecommerce using Google Tag Manager(Data Layer) for two person interactions(Buyer - Seller).
As I understand when dataLayer.push() happens and data goes to GA - clientID is unique user identifier.
All interaction steps are going on Buyer side, except Responded step.
Is it possible to make dataLayer.push() with Buyer clientID(what I save in database) on Responded step, because now I see funnel gap in Google Analytics Checkout Behavior report?

A: Solution for me was to use Measurement Protocol and send wanted data from backend.


text:
Q: Cant zoom on apple device and Samsung S3 error i currently developing this site, my problem is than user cannot zoom page on mobile devices. (Ipad,Iphone..) And user saw only part of the website when website load on Samsung S3. I Tried to search, but i dont saw answer what can help me.
I think than problem is in metatay "viewport".
Actually i have this.
        <meta name="viewport" content="width=1050px; user-scalable=yes; target-densityDpi=device-dpi" />

Thanks for any suggestion :).

A: If anyone is interested. I fixed like this, i just edit width and delete another tags.
        <meta name="viewport" content="width=1136px">


text:
Q: Plugin log level in OpenDistro cluster I have a fresh opendistro cluster that works fine, but I try to disable some traces in log and there is one that I can't remove.
The lines of log look like this :
[2020-04-22T10:09:17,502][INFO ][stats_log                ] [myhost01] ------------------------------------------------------------------------
Program=PerformanceAnalyzerPlugin
StartTime=1580542897.428
EndTime=Wed, 21 Apr 2020 10:09:17 CEST
Time=60074 msecs
Timing=total-time:60074.0/1
Counters=TotalError=0
EOE

It's clearly written by the PerformanceAnalyzer Plugin provided by opendistro, so I try to change the log config/log4j2.properties of this plugin and I've restarted the master (myhost01 in this example) but no change in log.
My question is : How to change the log level of this plugin?