text:
Q: Hadoop - Problem with Text to float conversion I have a csv file containing key-value pairs; it can have multiple records for the same key. I am writing a mapreduce program to aggregate this data - for each key, it is supposed to give the frequency of key and sum of values for the key.
My mapper reads the csv file and emits both key and value as Text type eventhough they are numeric (doing this way because I am running into problems using FloatWritable for value).
In the reducer, when I try to convert the Text value to float, I am running into NumberFormatException and the value shown in the error is not even in my input.
Heres my code:
public static class AggReducer
       extends Reducer<Text,Text,Text,Text> {
    private Text result = new Text();

    public void reduce(Text key, Iterable<FloatWritable> values,
                       Context context
                       ) throws IOException, InterruptedException {
      int numTrips = 0;
      int totalFare = 0;

      for (Text val : values) {
        totalFare += Float.parseFloat(val.toString());
        numTrips++;
      }

      String resultStr = String.format("%1s,%2s", numTrips, totalFare);
      result.set(resultStr);
      context.write(key, result);
    }
  }

Note : I made the reducer produce mapper's output without any changes and that gave the expected output

A:
running into NumberFormatException and the value shown in the error is not even in my input

Well, that's quite impossible. Somewhere the value needs to be in your input or generated mapper output. Try catch works just as well in a reducer as anywhere else, though
FWIW, use DoubleWritable


text:
Q: Split Column of mulitiple variables into 2 (Not key and Value) I have this data frame tk which is a subset of my original data
tk

> ##    document   term count    sentiment
> ## 1       111 happen     1 anticipation
> ## 2       111   time     1 anticipation
> ## 3       112 mother     1 anticipation
> ## 4       112 mother     1          joy
> ## 5       112 mother     1     negative
> ## 6       112 mother     1     positive
> ## 7       112 mother     1      sadness
> ## 8       112 mother     1        trust
> ## 9       112    sue     1        anger
> ## 10      112    sue     1     negative
> ## 11      112    sue     1      sadness
> ## 12      112  wrong     1     negative
> ## 13      113   suck     1     negative
> ## 14      114   gate     1        trust

I need to

*

*add a new column (tk$positive_negative) to contain values "positive" and "negative" only from the sentiment variable.

*add another new column (tk$emotions) to contain any other value except "positive" and "negative" from also the sentiment variable.

I have tried for loop but i couldn't succeed
for (i in tk$sentiment){
  ifelse(i=="positive",tk$positive_negative<-"positive",ifelse(i=="negative",tk$positive_negative<-"negative",tk$emotions<-paste(print(i))))
}

> ## [1] "anticipation"
> ## [1] "anticipation"
> ## [1] "anticipation"
> ## [1] "joy"
> ## [1] "sadness"
> ## [1] "trust"
> ## [1] "anger"
> ## [1] "sadness"
> ## [1] "trust"

tk

> ##    document   term count    sentiment emotions positive_negative
> ## 1       111 happen     1 anticipation    trust          negative
> ## 2       111   time     1 anticipation    trust          negative
> ## 3       112 mother     1 anticipation    trust          negative
> ## 4       112 mother     1          joy    trust          negative
> ## 5       112 mother     1     negative    trust          negative
> ## 6       112 mother     1     positive    trust          negative
> ## 7       112 mother     1      sadness    trust          negative
> ## 8       112 mother     1        trust    trust          negative
> ## 9       112    sue     1        anger    trust          negative
> ## 10      112    sue     1     negative    trust          negative
> ## 11      112    sue     1      sadness    trust          negative
> ## 12      112  wrong     1     negative    trust          negative
> ## 13      113   suck     1     negative    trust          negative
> ## 14      114   gate     1        trust    trust          negative

Please advice, thank you

A: See the comment by @Sotos. ifelse is already vectorized which basically means it already applies the function to every element in the vector for you. So no need for a loop! Also, using vectorized functions is much faster than a non-vectorized approach.
With that said I think to solve your problem all you need to do is:
tk$positive_negative <- ifelse(tk$sentiment %in% c("positive","negative"),tk$sentiment,"")
tk$emotions <- ifelse(tk$sentiment %in% c("positive","negative"),"",tk$sentiment)

tk
   document   term count    sentiment positive_negative     emotions
1       111 happen     1 anticipation                   anticipation
2       111   time     1 anticipation                   anticipation
3       112 mother     1 anticipation                   anticipation
4       112 mother     1          joy                            joy
5       112 mother     1     negative          negative
6       112 mother     1     positive          positive
7       112 mother     1      sadness                        sadness
8       112 mother     1        trust                          trust
9       112    sue     1        anger                          anger
10      112    sue     1     negative          negative
11      112    sue     1      sadness                        sadness
12      112  wrong     1     negative          negative
13      113   suck     1     negative          negative
14      114   gate     1        trust                          trust

Data:
    tk <- structure(list(document = c(111L, 111L, 112L, 112L, 112L, 112L,
112L, 112L, 112L, 112L, 112L, 112L, 113L, 114L), term = structure(c(2L,
6L, 3L, 3L, 3L, 3L, 3L, 3L, 5L, 5L, 5L, 7L, 4L, 1L), .Label = c("gate",
"happen", "mother", "suck", "sue", "time", "wrong"), class = "factor"),
    count = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L), sentiment = c("anticipation", "anticipation", "anticipation",
    "joy", "negative", "positive", "sadness", "trust", "anger",
    "negative", "sadness", "negative", "negative", "trust")), .Names = c("document",
"term", "count", "sentiment"), row.names = c(NA, -14L), class = "data.frame")

redpajama_set_name: RedPajamaStackExchange


text:
Q: AjaxFileUpload validation I am uploading multiple files using AjaxFileUpload and zipping all of them on submit button to a destination folder.
Now I need to validate if the zip file already exists in destination folder and show message on submit button, and allow the user to change the zipfile name.
Tried UploadStart, OnUploadComplete, UploadCompleteAll but could not achieve.


text:
Q: Need help understanding PNP Base into NPN Collecter circuit for LED Array I am a novice in circuitry and I'm trying to make an 8x8x8 LED Cube using an instructables guide for a school project. I have ordered all the parts and was testing the grounding circuit for each layer (pictured below). I am trying to understand how the PNP and NPN transistors interact. The PNP is a TIP42C and the NPN is a 2N2222.

The PNP's (O1-O7) Emitter is connected to 5V, the Collector is connected to the cathode end of 64 LEDs, and the Base is connected to 5V through a 10Ω resistor and to the collector of the 2N2222 through a 1kΩ resistor.
The NPN's (T1-T8) base is connected to a MUX through a 1kΩ resistor, the emitter goes to ground, and the collector is from the PNP. I understand how this portion works.
R1-R8 and R17-R24 are 1kΩ. R25-R32 are 10kΩ.
What I don't understand is why the PNP transistor is necessary. I tried to build one line of the diagram:

Green Wire: High/Low to NPN Base
Black Wire: Ground from NPN Emitter
Orange Wire: Cathode from 64 LED Array (simulated with 3 LEDs)
Red Wire: 5V to PNP Emitter
White Wire: 5V to LEDs
But the issue I ran into was with the 5V into the Emitter of the PNP (Red wire). If I took that out, the LED's lit up, but the diagram clearly has the emitter of the PNP wired to 5V.
Is there some fundamental property of PNP transistors that I am missing? I calculated the total current of the 64 LEDs (~1.2A). (Is this right?) and would this circuit support that?
FYI, each line from JP2 in the first picture is a ground line from a 64 LED array and the lines from the IC1 are driven by an arduino uno.
I've been racking my brain over this for the last week and can't figure it out so any help would be greatly appreciated! Thank you!

A: Oh, it's simple, you think the circuit provided is the ground control for the leds. It is not. It is the high side control for the leds. Your breadboard is not accurate reflection of the circuit. The PNP is turning on, and you are essentially shorting out the leds with 5V on both sides.

simulate this circuit – Schematic created using CircuitLab
So, when the red wire, 5V is connected to the emitter, and the PNP is ON, the 5V is connected to the collector and you short out the leds. When you remove it, I'm taking an educated guess, you create a ground path from the collector through the base of the TIP 42C, which in turn goes through the NPN that is turned on. This could have damaged the TIP 42C you are testing with, btw. Floating emitter isn't ideal.
In the cube, they are using the 2n2222 (or 2n3904 on the board layout) as npn drivers of the PNP TIP 42C. This controls the led anode. The low side is controlled by the ULN2803 darlington transistor array ICs on the shift register board. This is done to allow a scanning function to control that many leds from a small number of pins of the micro controller.

FYI, each line from JP2 in the first picture is a ground line from a 64 LED array and the lines from the IC1 are driven by an arduino uno.

No, JP2 is the Anodes of the LED array.


text:
Q: Javascript Running Order Just a quick question. I wonder how javascript function runs if they're being called.
Example: I have this
function1();
function2();
function3();
function4();
function5();

I am calling these functions somewhere in my program. Does it run orderly based on what line they are called? Thank you!


text:
Q: Matlab patch object coordinates I have a patch object in Matlab that represents a racetrack. Is there a way to determine whether a certain x-y coordinate lies inside this patch? I want to be able to detect when a racecar drives off the track.

A: While there is no Matlab implementation of what you're asking that i'm aware of, it wouldn't be too hard to do yourself.
If you're track is a convex hull, then you could use the matlab function convhull() to generate the convex hull of the track. This function returns a list of indices and the area of the convex hull.
i.e.
[k_track, a_track] = convhull(x_track,y_track).
Then compare this to the convex hull of the set of track points and the vehicle point.
x_new = [x_track x_car]
y_new = [y_track y_car]
[k_new, a_new] = convhull(x_new,y_new)
If the car is inside the track, the convex hulls (and therefore areas) will be the same.
if a_track ~= a_new
car outside of track
else
car inside track
end
Note this relies on the track being a convex hull. If it isn't, you may be able to break it into segments that are and iterate the procedure.


text:
Q: How to select a value using Xpath I am new XML and struggling to find an answer to this problem. I have the following code (see below) and would like to extract the value 3400.0000000000 from it.
How do I do this using Xpath?
<SpindleSpeed dataItemId="c2" name="Sspeed" sequence="351828725" subType="ACTUAL" timestamp="2014-12-01T21:51:32.834494">3400.0000000000</SpindleSpeed>

A: XPath has two parts - locations paths and functions. A location path will always return a list of nodes (an empty one if it can not find a matching node).
Here are three possible location paths in your XML:
/SpindleSpeed for the SpindleSpeed element node that is the document element
//SpindleSpeed for any SpindleSpeed element node in the document
//SpindleSpeed/text() for any text nodes inside any SpindleSpeed element node in the document
If you have a list you can cast it
number(//SpindleSpeed) is the content of the first node in the list (from the location path) as a number - 0.0 if the list was empty.
string(//SpindleSpeed) is the content of the first node in the list (from the location path) as a string - an empty string for an empty list.

A: Try this :
//SpindleSpeed/text()

A: If X is an expression that selects the SpindleSpeed element, then string(X) is an expression that returns its string value, that is "3400.0000000000"


text:
Q: How to set unexpected data type to na? I have a data frame like this:
a = pd.DataFrame({'foo':[1,2,3,'str']})

    foo
0   1
1   2
2   3
3   str

I want to set the data type to int64:
a['foo'].astype('int32')

but I got an error message:
ValueError: invalid literal for int() with base 10: 'str'

How to set unexpected data type to NA. In my case, I'd like to return data frame like the following:
    foo
0   1
1   2
2   3
3   NA

A: The best is convert all values to floats, because NaNs are float by to_numeric with parameter errors='coerce':
df = pd.to_numeric(df['foo'], errors='coerce')
print (df)
0    1.0
1    2.0
2    3.0
3    NaN
Name: foo, dtype: float64

But if really need integers with floats, is possible this hack:
df = df['foo'].where(df['foo'].apply(lambda x: isinstance(x, int)))
print (df)
0      1
1      2
2      3
3    NaN
Name: foo, dtype: object

print (df.apply(type))
0      <class 'int'>
1      <class 'int'>
2      <class 'int'>
3    <class 'float'>
Name: foo, dtype: object

A: Or using isalpha
a.foo.mask(a.foo.str.isalpha().notnull())
Out[331]:
0      1
1      2
2      3
3    NaN
Name: foo, dtype: object


text:
Q: Does Spring Version 4.3.20 work with Java 11? I am confused when it comes to the supported java-versions of spring 4.3.20. Updating a Spring 4.3.20 project to Java 11 worked without any hiccups what so ever. All my tests work fine, the webapp starts up and all the features of Spring that require bytecode-magic like @Cacheable work. How is this even possible? From what I understand I should have to update to Spring 5+. I checked the language level in my maven settings and bytecode version of the generated .class-files and they indeed use major version: 55.
What am I missing?
I build with Java 11 and launch my local tomcat with Java 11. I double checked all my settings and used visualvm to verify that tomcat indeed runs with Java 11.
Heres the output of javap:

A: Spring 5.1 supports Java 11, earlier versions do not. See Spring Framework Versions:

JDK Version Range

*

*Spring Framework 5.1.x: JDK 8-12

*Spring Framework 5.0.x: JDK 8-10

*Spring Framework 4.3.x: JDK 6-8

and What's New in Spring Framework 5.x:

What's New in Version 5.1
General Core Revision

*

*Infrastructure:

*

*Warning-free support for JDK 11 on the classpath and the module path.

That 4.3.x works on Java 11 might just mean that you have been lucky up to now (not using things that are not compatible with Java 11). Also, Java is pretty good in backwards compatibility, even with the things removed or intentional backwards incompatible changes since Java 9, it is entirely possible that the real broken things in Spring are very small and obscure.
That said, I would not use a set of libraries as vast as Spring with Java 11 if the authors say that Java compatibility is only guaranteed in a later version than you use. If you want to use Spring with Java 11, upgrade to Spring 5.1.

A: Remember: tests can only prove the presence of bugs, not their absence.
According to some comments on their release blog, 4.3.20 is in deed "not compatible" with Java 11.
On the other hand: spring is a huge framework. So the simple answer might be: it works for, as long as you don't run into areas that will not work.
And keep in mind: any JDK of version N can run bytecode for bytecode that has older versions N-x.

A: Seems the compatibility is a common question in the community, so there is an answer (kinda) in Spring documentation: https://spring.io/blog/2015/04/03/how-spring-achieves-compatibility-with-java-6-7-and-8
Basically, Spring codebase itself does not use even the features of Java 7, therefore it is compatible with 6.
As to the bytecode transformation, I believe JVM keeps some level of compatibility due to its specs allowing some of the framework's features to work.
However, if the official docs say it is not compatible, then you should rely on this accident, since other features may not work or get broken with patches and minor releases.
P.S. You also mentioned cglib which can be used to manipulate bytecode, but it's not actually required. It does generate Java code or even bytecode that is always backward-compatible in new JVM releases.


text:
Q: how can i import meteor-roles in typescript? I'm writing a angular2-meteor application with typescript using angular2-meteor 0.5.4 and angular2 beta17.
I'm using accounts-password meteor package with with angular2-meteor-accounts-ui for ui representation.
I also installed the meteor package alanning:roles.
now I need to import Roles in typescript and i fail to do so because it doesn't contain a typescript definition file.
I searched on google and I found https://github.com/meteor-typescript/meteor-typescript-libs
which container typescript definitions for many packages including Roles.
is this the way to go? am I missing something.
since I'm new to meteor and typescript i need reassurance that i'm following the right path.
thank you!

A: import your Roles like so

import { Roles } from 'meteor/alanning:roles';

Next, you need to add / update your custom typings file (meteor.d.ts in my case, which is autoloaded by Meteor)

declare module "meteor/alanning:roles" {
  export module Roles {
    function createRole(roleName: string): string;
    function deleteRole(roleName: string): void;
    function addUsersToRoles(users: any, roles: any, groups?: string): void;
    function removeUsersFromRoles(users: any, roles: any): void;
    function userIsInRole(user: any, roles: any): boolean;  //user can be user ID or user object
    function getRolesForUser(userId: string): string[];
    function getAllRoles(): Mongo.Cursor<RolesDAO>;
    function getUsersInRole(roleName: string): Mongo.Cursor<RolesDAO>;
    var GLOBAL_GROUP: string;
  }
}

A: There is a simpler way to import meteor packages in typescript. Most of the types are defined here

https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types
https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/meteor

Install NPM module that has types defined.
meteor npm install --save @types/meteor-roles

Import the types in your modules
import { } from '@types/meteor-roles';

Now, you can use Roles type for methods like addUsersToRoles() etc.


text:
Q: How to convert nested JSON to csv in C#? I am trying to use Newtonsoft.Json to deserialize below JSON to csv but failed.  I am unable to properly define the schema of the JSON and thus failed.
Input JSON:
{
 "2017-02-11":
  {
  "Table1": [
    {
      "code": "code day1.1.1",
      "no": "no day1.1.1"
    }
  ],
  "Table2": [
    {
      "code": "code day1.2.1",
      "no": "no day1.2.1"
    },
    {
      "code": "code day1.2.2",
      "no": "no day1.2.2"
    }
  ]
 },
 "2017-02-12":
  {
  "Table1": [
    {
      "code": "code day2.1.1",
      "no": "no day2.1.1"
    },
    {
      "code": "code day2.1.2",
      "no": "no day2.1.2"
    }
  ],
  "Table2": [
    {
      "code": "code day2.2.1",
      "no": "no day2.2.1"
    }
  ]
 }
}

Output csv:
,,code,no
2017-02-11,Table1,code day1.1.1,no day1.1.1
,Table2,code day1.2.1,no day1.2.1
,,code day1.2.2,no day1.2.2
2017-02-12,Table1,code day2.1.1,no day2.1.1
,,code day2.1.2,no day2.1.2
,Table2,code day2.2.1,no day2.2.1

When I try to use
DataSet dataSet = Newtonsoft.Json.JsonConvert.DeserializeObject<DataSet>(content).

It returns exception.

A: When you deserialise an object, your returning type needs properties which match that of the object names in the JSON.
Your JSON uses dates as objects names, which I assume means that these values are dynamic. If they are dynamic, then I'd recommend using
var dynamicResults = JSON.Decode(content);

Decode returns a dynamic list type which can be looped through, from there you can bind your results from each dynamic into a new DataSet type.


text:
Q: Getting the number of like counts from a facebook album I was trying to develop a python script  for my friend, which would take a link of a public album and count the like and comment numbers of every photo with "requests" module. This is the code of my script
import re
import requests

def get_page(url):
    r = requests.get(url)
    content = r.text.encode('utf-8', 'ignore')
    return content

if __name__ == "__main__":
    url = 'https://www.facebook.com/media/set/?set=a.460132914032627.102894.316378325074754&type=1'
    content = get_page(url)
    content = content.replace("\n", '')

    chehara = "(\d+) likes and (\d+) comments"
    cpattern = re.compile(chehara)
    result = re.findall(cpattern, content)
    for jinish in result:
        print "likes "+ jinish[0] + " comments " + jinish [1]

But the problem here is, it only parses the likes and comments for the first 28 photos, and not more, what is the problem? Can somebody please help?
[Edit: the module "request" just loads the web page, which is, the variable content contains the full html source of the facebook web page of the linked album]

A: use the facebook graph api:
For Albums its documented here:
https://developers.facebook.com/docs/reference/api/album/
Use the limit attribute for testing since its rather slow:
http://graph.facebook.com/460132914032627/photos/?limit=10
EDIT
i just realized that the like_count is not part of the json, you may have to use fql for that

A: If you want to see the next page you need to add the after attribute to your request like in this URL:
https://graph.facebook.com/albumID/photos?fields=likes.summary(true),comments.summary(true)&after=XXXXXX&access_token=XXXXXX

You could take a look at this JavaScript project for reference.


text:
Q: Why did Valorum want to conceal the mission of the Jedi ambassadors? After a while, I ended up watching The Phantom Menace on TV the other night and spotted a curious issue in the third chapter of the opening crawl.

While the Congress of the Republic endlessly debates this alarming
  chain of events, the Supreme Chancellor has secretly dispatched two
  Jedi Knights, the guardians of peace and justice in the galaxy, to
  settle the conflict....

It was Chancellor Finis Valorum who sent the two Jedi, Qui-Gon Jinn and Obi-Wan Kenobi, to negotiate with the Trade Federation to end their blockade of Naboo. But why did he have to do it in secret? The Jedi were in fact common negotiators on behalf of the Senate, at least according to Wookieepedia:

As keepers of the peace, the Jedi Order undertook diplomatic missions
  on behalf of the Galactic Senate, and pursued interplanetary criminals
  across the galaxy.

Additionally, as soon as the Consular cruiser reached Naboo, the captain of the ship revealed they were carrying negotiators on behalf of the Chancellor.

Captain Madakor: With all due respect, the ambassadors for the Supreme
  Chancellor wish to board immediately.

Did Valorum try to conceal this mission of his from someone specifically? Is there a background story about him sending the Jedi ambassadors to Naboo in secret?

A: This was addressed in the film's novelisation. In short, the Chancellor has exceeded his personal authority in bringing the Jedi (who report directly to him) into a debate between two parties who have seats in the Senate.

The blockade had been in effect now for almost a month. The Republic
Senate continued to debate the action, searching for an amicable way
to resolve the dispute. But no progress had been made, and at last the
supreme chancellor had secretly notified the Jedi Council that he had
sent two Jedi directly to the ostensible initiators of the blockade,
the Neimoidians, in an effort to resolve the matter more directly.
It was a bold move. In theory, the Jedi Knights served the supreme
chancellor, responding on his direction to life-threatening
situations. But any interference in the internal politics of the
Senate's member bodies, particularly where an armed conflict between
worlds was involved, required Senate approval. The supreme chancellor
was skirting the edges of his authority in this case. At best, this
was a covert action and would spark heated debate in the Senate at a
later date.
Star Wars Episode I: The Phantom Menace - Official Novelisation


text:
Q: OOCSS & BEM - inline list - How to handle scaffolding, how to add skin? I am just getting my head around the OOCSS methodology. As I think it makes everything easier to understand, I am also trying to use BEM naming convention.
Using this principle, I am trying to create a navigation for a homepage - basically just an inline list. As OOCSS is about abstraction, I created this CSS so far:
.horizontal-list {
    padding: 0;
    list-style: none;
}

.horizontal-list__item {
    display: inline;
}

I tried not to use a class name like nav or navigation as I first try to layout the structure before applying the skin – and this is where my actual question begins.
To add some color, to change the font-size etc., I would probably just add this as a modifier like .horizontal-list--nav. Another modifier could be for a breadcrumb navigation: .horizontal-list--breadcrumb. Would it be ok to it like this?
To me its logical, as the i.e. the text color has nothing to do with the list being inline per se, but with the list being a breadcrumb for example, but I am not sure if I approach the thing from the wrong direction.

Also, the HTML for that list would look something like this:

Link

Link

Link

The li is an element of horizontal-list, that's clear. But what about the a being nested inside the li, how do I markup that? according to the OOCSS principles, I shouldn't do
.horizontal-list__item a {
    color: white;
}

right? But adding a class like horizontal-list__item__item also seems pretty wrong somehow. How do I do that correctly?

A: In BEM, elements depend on block but not on each other. So, you should mark your links with the class .horizontal-list__link even if in HTML it is placed into another element.
Also, if you use BEM structure on a file system, you do not include element folders into the other element folders. The structure is flatten, like the following:
blocks/
    horizontal-list/
        __item/
            horizontal-list__item.css
        __link/
            horizontal-list__link.css
        horizontal-list.css

A: *

*On modifiers.
Yes, you're doing it correctly. Modifiers should be understood as flags or properties. You can combine several modifiers on a single node, or even use key-value modifiers (I'm used to Yandex-based BEM notation, so it could be smth like .horizontal-list_theme_green or .horizontal-list_theme_red for themes).

I would say the word "horizontal" shouldn't be the part of your block name. Menus can be vertical as well, and this can also be expressed with a modifier: "my-list my-list_align_horizontal".

*

*On elements.
In BEM, elements can be nested in the HTML structure, but they are always defined as a flat list. So, you should turn your anchor tags into .horizontal-list__link elements or something. Style definitions of different elements should be kept independent whenever possible, so just do:

.horizontal-list__link { color: white }
Things like this are okay though:
.horizontal-list__item:hover horizontal-list__link { color: blue }


text:
Q: How to avoid having to use @SuppressWarnings? I am using an open source java library called Weka in an Eclipse Indigo project. The library seems a bit outdated so Eclipse is showing me thousands of warnings in regards to its code. A typical example is:

ArrayList is a raw type. References to generic type ArrayList<E>
  should be parameterized

In reference to a line like this:
ArrayList t = new ArrayList();

Eclipse's quick fix indicates that I can either convert the above code to use generics or that I can add a @SuppressWarnings 'rawtypes' annotation as a fix.
But both of these fixes involve making changes to the code of the open source project and I'd have to do these changes several (hundreds of?) times over.
Instead, might there be some global setting for Eclipse (or the Java compiler?) where I can indicate that I do not want to be warned for a specific project?

A: Window > Preferences > Java > Compiler > Errors/Warnings > Generic Types. Alternatively this can be set on a project by project basis (if you have other projects in your workspace you want to keep the same) by right-clicking on the project > Properties > Java > Errors/Warnings > Check "Enable project specific settings" and then as before.

A: Try Window->Preferences, Java->Compiler->Errors/Warnings.  I see there's a "Generic types" section near the bottom.  I don't know if that's exactly what you're looking for, but from my experience this is a good place to ignore specific Eclipse warnings.

A: In Eclipse navigate to Window->Preferences->Java->Compiler->Errors/Warnings->Generic types here you will find a category for "Usage of raw type" which you can set to ignore rather than warning.

A: It has been suggested that you just turn off the "offending" warnings via Window > Preferences, but that turns them off for all projects in your workspace, including the project(s) containing your own Java 1.5 + code.  That's a bad idea, 'cos you should be paying attention to the warnings if they occur in your code.  (If you ignore them you are liable to get unexpected runtime exceptions.)
Another possibility would be change the project settings to set the Java compiler's source level to Java 1.4 or earlier.  You should only do this on the Weka project.  The project containing your code needs to use a source level of at least Java 1.5 ... given that you are using generics.

Thanks. Might this not cause problems later on when I deploy the project to a production server running JRE 1.6? Won't I have to have JRE 1.4 present there as well?

No ... for a couple of reasons:

*

*Unless you are modifying Weka, you can use the original JARs and ignore any build artifacts created by Eclipse.

*The source level and the target level are different.  The source level says what version of the Java language the source code must conform to.  The target level says what version of the classfile format should be used.  You can get the Java compiler to generate Java 1.6 bytecode format for Java 1.4 source code.  (But not vice versa).

*A Java 1.6 JRE will happily run a Java 1.4 JAR.

Also, where do I do this? Do you mean Project > Properties > Java Compiler > Compiler compliance level?

Yes.  Note that it allows you to specify the source and target levels independently ... modulo the constraint that the Java compilers only allow certain combinations.


text:
Q: Specify type of rxjs observable's "error" handler Suppose I have some operation that returns an observable.
this.loginService
  .post<IResponse>(url, { username, password })
  .subscribe(
    next => { /* I know the type of next */ },
    error => { /* Can I specify type of err, or is it always any? */ }
  );

The type of next is something I can set - in this case IResponse.
What about error - can I specify it's type somehow? Or is it always any, and I'll always need to typecast within the handler?

A: It's been my experience that a service that yields observables from a HTTP operation should never emit uncaught HTTP errors. It creates a lot of boilerplate code in the consumers of that service, and forces consumers to handle HTTP specific issues.
I also think that services should not catch all types of errors, but only the known and expected errors. Requiring the application itself to handle edge cases using an error interceptor.
export interface ILoginResponse {
   //...
}

export interface IServiceResponse<TType> {
   success: boolean;
   payload?: TType;
}

@Injectable()
export class LoginService {

   public login(options: any): Observable<IServiceResponse<ILoginResponse>> {
      return this.httpClient.post<ILoginResponse>('login', options).pipe(
          map(payload => ({success: true, payload})),
          catchError(err => {
              if(err instanceof HttpErrorResponse) {
                  // handle http errors here, maybe retry, update headers, etc..
                  return of({success: false});
              }
              // this error is unexpected, we don't know what to do
              // let the app interceptor handle it, but upstream observables
              // won't know what to do either. Our app has crashed...
              // You can return success false, but why handle this error?
              return throwError(err);
          });
   }
}

Why should you do the above?
Any time you use a route resolver that emits an uncaught error it will fail route transition. The router will basically crash. The user will basically just see a blank page, because resolvers have no error handling fall back.
The above only catches HTTP errors, because that's the only kind that we think should be thrown. Another kind of error should be seen as a bug.
If a component calls this service, then the programmer should check the success flag for true before trusting the emitted value. This can be filtered if the business logic does not care if it fails, or the component can visually show the user that it failed to perform the HTTP request. Either way, the HTTP error response does not go to the app error interceptor.
This is just an approach. People do their HTTP stuff all differently. The other answer correctly answers your question.

A: Another way to do it using catchError operator:
this.loginService
  .post<IResponse>(url, { username, password })
  .catchError<TypeOfYourErrorResponse>(() => // Your catch callback)
  .subscribe(
    next => { /* I know the type of next */ },
  );

A: You can use parentheses for what you want to achieve:
this.loginService
  .post<IResponse>(url, { username, password })
  .subscribe(
    (next: TypeOfYourResponse) => {...},
    (error: TypeOfYourErrorResponse) => {...}
  );

For further reading on arrow functions:
https://www.tutorialsteacher.com/typescript/arrow-function
https://basarat.gitbooks.io/typescript/docs/arrow-functions.html

A: I really liked @Reactgular's accepted answer
I like the fact it will make the consumer think about errors when they have to check success status!  However sometimes the consumer may want to get and display an error from the server, so I've changed it a little:
// DON'T FORGET THESE!
import { Observable, of } from "rxjs";
import { catchError, map } from "rxjs/operators";

export interface ILoginResponse {
   //...
}

export interface IServiceResponse<TType> {
   payload?: TType;
   error?: HttpErrorResponse;
}

@Injectable()
export class LoginService {

   public login(options: any): Observable<IServiceResponse<ILoginResponse>> {
      return this.httpClient.post<ILoginResponse>('login', options).pipe(
          map(payload => ({ payload })),
          catchError(err => of({ error: err }))
   }
}

No need for success flag, just check if you have a payload or error
loginService.login().subscribe(response => {
   if (response.payload) {
      // success...
   }
   else if (response.error) {
      // handle the error
   }
},

I think return all errors, the client might not care so it can be ignored, but it will be there if they do care; if you want to handle specific errors, use an HttpInterceptor somewhere else...


text:
Q: Remove multiple licenses via Azure AD v2 powershell I want to remove multiple licenses using PowerShell. Actually I able to remove single licence like below. But How do I remove multiple licenses?
$AzureUser = Get-AzureAdUser -ObjectId $ADuser.UserPrincipalName

$License = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicense

$License.SkuId = "6fd2c87f-b296-42f0-b197-1e91e994b900"   #6fd2c87f-b296-42f0-b197-1e91e994b900 Office 365 E3

$LicensesToAssign = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicenses

$LicensesToAssign.AddLicenses = @()
$LicensesToAssign.RemoveLicenses = $License.SkuId

Set-AzureADUserLicense -ObjectId $AzureUser.ObjectId -AssignedLicenses $LicensesToAssign

A:
But How do I remove multiple licenses?

There is a easy way to achieve this, we can use MSOL powershell (Azure AD v1) to do it:
We can use this script to list all licences assigned to this account:
$UPN = jasontest1@tech1108.com
$a = Get-MsolUser -UserPrincipalName $UPN
$c = $a.Licenses.accountskuid

Then we can use foreach to remove all licences:
foreach ( $d in $c ){ Set-MsolUserLicense -UserPrincipalName $UPN -RemoveLicenses $d }

Here is the information about -RemoveLicenses, please refer to this link.
By the way, if you want to install MSOL powershell on your PC, we can use this command to install it: install-module msonline.

Update:
We can use this script to remove licenses from one account(Azure AD PowerShell V2).
$a = get-azureaduser -ObjectId "4xxxxxxx0"
$skuids = $a.AssignedLicenses.skuid
$License = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicense
$LicensesToAssign = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicenses
$LicensesToAssign.AddLicenses = @()
foreach($skuid in $skuids){$License.SkuId = $skuid; $LicensesToAssign.RemoveLicenses = $License.SkuId; Set-AzureADUserLicense -ObjectId "user-object-id" -AssignedLicenses $LicensesToAssign}


text:
Q: How to set default value I am trying to parse a csv file using csv helper
this is my maping class
sealed class CSVFileDefinitionMapFinal : CsvClassMap<CSVFileDefinitionFinal>
{
    public CSVFileDefinitionMapFinal()
    {
        Map(m => m.FARM_ID).Name("FRM_ID");
    }
}

this is my item class
class CSVFileDefinitionFinal
{
    public int FARM_ID { get; set; }
}

the problem is that the FRM_ID in the csv may hav null. so when I do the mappign above, I have an exception that null can't be transfer to integer. I am asking about if there is a way to try and catch that and set the value to -10 when it is null.
the try and catch should be in the maping class, but I couldn't know what to do after catching the exception. in other words, i couldn't know how to set default value to the maping object

A: You can make that property nullable and not-automatic:
class CSVFileDefinitionFinal
{
    private int _farmId;

    public int? FARM_ID
    {
        get { return _farmId; }
        set { _farmId = value == null ? -10 : value.Value; }
    }
}

Note that you need to define a private int _farmId member in that class.

A: You can just add a default to the mapping.
Map(m => m.FARM_ID).Name("FRM_ID").Default( -10 );


text:
Q: Angular providers: Provide value dynamically based on @Input() parameter export const FormatDate = new InjectionToken('FormatDate');
...
@Component({
  selector: '...',
  templateUrl: '...',
  styleUrls: ['...'],
  providers: [{ provide: FormatDate, useValue: 'MM.yyyy' }]
})
export class DatePicker {
  @Input() format: string
  ...
}

I want to dynamically provide 'FormatDate' based on input 'format' parameter. If format === 'short' then useValue: 'MM.yy'. If format === 'long' then useValue: 'MM.yyyy'. Is that possible?

A: Yes, you can do that using pipe. Create a pipe and the transform method should be like this(pseudo code might help you to create a flow):
exPipe.ts
 transform(format: any) {
     return format === 'long' ? fetch value form store or anywhere(MM.yyyy)
                              : fetch value form store or anywhere(MM.yy) || (MM.yyyy).slice(0, 4) // just slice it
  }

In the template you can do this(just an example) :
<div> {{format | exPipe }}</div>


text:
Q: Spring Bean injection not working Dwr I have two actions in two different packages
<package name="default" extends="struts-default json-default" namespace="/">

      <action name="getstarted"  class="GetStartedActionBean">
            <result name="success">/jsp/getStarted.jsp</result>
            <result name="input">/jsp/getStarted.jsp</result>
      </action>
</package>

<package name="example" extends="json-default">

      <action name="searchIndustryaction"  class="GetStartedActionBean"  method="searchIndustry">
      </action>

  </package>

I have injected one bean it is working fine when the page loads but my search is through dwr at that time bean is not injected
in my impl
private SessionFactory sessionfactory;

 public void setSessionfactory(SessionFactory sessionfactory) {
     this.sessionfactory = sessionfactory;
}

sessionFactory is set when the execute method is called but using dwr when i called searchIndustry sessionfactory is always null
Dwr entry
<create creator="new" javascript="AdvancedSearch" scope="application">
            <param name="class" value="com.sample.dao.impl.IndustryDAOImpl"/>
        </create>

How would I call the injected bean in dwr?

A: If you are using DWR means you have to put an entry like this
<create creator="spring" javascript="Industry">
<param name="beanName" value="Yourbeanname" />
</create>

but you are directly calling the class so change to this format. Hope it may useful for you

A: In your dwr.xml you can make for the creator one of those :
new: Which uses the Java 'new' operator.
static: Which uses the 'getInstance()' method (by default) to obtain an instance of the class.
none: This does not create objects. See below for why. (v1.1+)
scripted: Uses a scripting language like BeanShell or Groovy via BSF.
spring: Gives access to beans through the Spring Framework.
jsf: Uses objects from JSF. (v1.1+)
struts: Uses struts FormBeans. (v1.1+)
pageflow: Gives access to a PageFlow from Beehive or Weblogic. (v1.1+)


text:
Q: How can I create an appmenu/DBusmenu using python?
Possible Duplicate:
How to add support for the global menu to a python non-gtk, non-qt app?

I want to add support for the indicator-appmenu to an application that is not written in one of the supported toolkits. I want to use a python script as a bridge and I would like to know how I attach the menu structure to the appmenu (or to do the communication between application and appmenu).
I found and read the following resources:

*

*https://wiki.ubuntu.com/Unity/LauncherAPI#Python_Example
This explains very well how to create a Dbusmenu, however they attach it to the quicklist of the launcher. I would expect a similar way to attach it to the appmenu?

*wiki.ubuntu.com/DesktopExperienceTeam/ApplicationMenu
no documentation available yet (?)

*http://developer.ubuntu.com/api/ubuntu-11.10/python/Dbusmenu-0.4.html
I don't understand how this looks in a script, I would need an example. Can someone tell me a python application that adds an appmenu on its own (where the appmenu is not extracted automatically from the toolkit)?


text:
Q: Complicated induction proof of helpful inequality I really need help proving the following inequality using induction:
Let $ x\in\left[ 0,1 \right] $. Let's define a sequence $a_{ i }\in\ \{ 0,1,2 \}$ recursive as following: Let $ i\in \mathbb{N} $ and let
$a_{1},...,a_{i}$ be already defined, then define $a_{i+1}$ as:
$$ a_{i+1} = \max(a\in\ \{ 0,1,2 \}: \frac{a}{3^{i+1}} + \sum_{j=1}^{i} \frac{a_{j}}{3^{j}} \le x)\ $$
Let's also assume that we don't maximize over the empty set.
Now i want to proove that for all $ i\in \mathbb{N} $: $a_{i+1}$ is defined properly and the following inequality is true:
$$ \sum_{j=1}^{i+1} \frac{a_{j}}{3^{j}} \le x \le (\sum_{j=1}^{i} \frac{a_{j}}{3^{j}}) + \frac{1}{3^{i}}$$
Does anyone have hints on how to prove it using induction? I don't really get it...
I have problems, especially with the maximum function
I calculated the first few sequence elements: $a_0 = 0$, $a_1=floor(3x)$ except for $x=1$, then $a_1=2$

A: Assume existence of $a_1,\cdots,a_i$ with the given properties. You know: $$\tag{$\star$}\sum_{j=1}^i\frac{a_j}{3^j}\le x$$And also that $a_i$ is the maximal element of $\{0,1,2\}$ for which this inequality holds. You want to know if there exists any $a_{i+1}\in\{0,1,2\}$ which satisfies the maximum condition. Since $\{0,1,2\}$ is finite, the only obstacle to the existence of the maximum is in the case that the set of $a\in\{0,1,2\}$, $$\frac{a}{3^{i+1}}+\sum_{j=1}^i\frac{a_j}{3^j}\le x$$Is empty. But $a=0$ is always a solution because of the 'inductive hypothesis', the inequality $(\star)$. Thus, $a_{i+1}$ always exists.
You also want to show, rewriting slightly, that: $$\frac{a_{i+1}}{3^{i+1}}+\sum_{j=1}^{i}\frac{a_j}{3_j}\le x\le\frac{a_{i+1}+1}{3^{i+1}}+\sum_{j=1}^i\frac{a_j}{3^j}$$Because $a_{i+1}$ is maximal, there is a contradiction there if the inequality is false. Note the left hand inequality always holds by definition of $a_{i+1}$. Have a further think about this!


text:
Q: Different classes with same methods with different parameters I have three classes: ToBeMum, NewMum, and ExperiencedMums. These classes have different methods which do the same things however they differ in parameters. How can I restructure the code to avoid copy/paste in all the three classes? For example:
NewMum:
public List<Question> GetMotherActualDayCareAge()
        {

            List<QuestionInfo> mumsHabits;
            var answers = Answers.GetAnswers;

            string answerValue = string.Empty;

            var oneA = from a in answers
                       where a.Questionid == "Q49d"
                       select new QuestionInfo { questionId = a.Questionid, userId = a.UserId };

            var oneB = from a in answers
                       where a.Questionid == "Q65d"
                       select new QuestionInfo { questionId = a.Questionid, userId = a.UserId };

            var temp = oneA.Union(oneB).ToList();

            mumsHabits = temp.Intersect(mothers, new UserIdEqualityComparer()).ToList();

            return mumsHabits;
        }

ExperiencedMum
public List<QuestionInfo> GetMotherActualDayCareAge()
        {
            List<QuestionInfo> mumsHabits;

            var answers = Answers.GetAnswers;

            string answerValue = string.Empty;

            var oneA = from a in answers
                       where a.Questionid == "Q49c"
                       select new QuestionInfo { questionId = a.Questionid, userId = a.UserId };

            var oneB = from a in answers
                       where a.Questionid == "Q65c"
                       select new QuestionInfo { questionId = a.Questionid, userId = a.UserId };

            var temp = oneA.Union(oneB).ToList();

            mumsHabits = temp.Intersect(mothers, new UserIdEqualityComparer()).ToList();

            return mumsHabits;
        }

A: This is gonna be very simple. You can write a common method with this same concept in a separate class.
For ex, create a class called Helper.cs which should contains the following method
public List<QuestionInfo> GetMotherActualDayCareAge(string var1, string var2)
    {
        List<QuestionInfo> mumsHabits;

        var answers = Answers.GetAnswers;

        string answerValue = string.Empty;

        var oneA = from a in answers
                   where a.Questionid == var1
                   select new QuestionInfo { questionId = a.Questionid, userId = a.UserId };

        var oneB = from a in answers
                   where a.Questionid == var2
                   select new QuestionInfo { questionId = a.Questionid, userId = a.UserId };

        var temp = oneA.Union(oneB).ToList();

        mumsHabits = temp.Intersect(mothers, new UserIdEqualityComparer()).ToList();

        return mumsHabits;
    }

Now just call this method wherever needed. In your case, you can call this method from ToBeMum.cs, NewMum.cs, and ExperiencedMums.cs.
For ex, In NewMum.cs, you can just call like this.
List<QuestionInfo> quesList = GetMotherActualDayCareAge("Q49d", "Q65d");

In ExperiencedMum.cs, you can call like this.
List<QuestionInfo> quesList = GetMotherActualDayCareAge("Q49c", "Q65c");

So now this becomes dynamic, where only one method is written and the method is called multiple times without copy/paste.

A: This is the answer for user2549110's second question.
Try creating an abstract class like AbsMumSurvey.cs which should contain the following,
public abstract class AbsMumSurvey
{
   public abstract void IsDayCare();

   public abstract void IsEconomicalToEducateChild();

   public int NoOfBabies()
   {
       return 2;

       //This is the sample logic just for understanding. You can write your own logic.
   }
}

Now IsDayCare() and IsEconomicalToEducateChild() are the abstract methods which should be compulsorily overridden in the derived class.
Now in GoingToDeliver.cs, you can do like the following.
public class GoingToDeliver : AbsMumSurvey
{
    public override void IsDayCare()
    {
        //Write your logic here.
    }

    public override void IsEconomicalToEducateChild()
    {
        //Write your logic here.
    }
}

you may or may not implement NoOfbabaies(). If you also want to implement NoOfBabies(), try the following code.
    public new int NoOfBabies()
    {
        return base.NoOfBabies();
    }

Same way, you can derive these methods from many classes.

A: I would extract out a common method for the following:
var oneA = from a in answers
                       where a.Questionid == "Q49d"
                       select new QuestionInfo { questionId = a.Questionid, userId = a.UserId };

            var oneB = from a in answers
                       where a.Questionid == "Q65d"
                       select new QuestionInfo { questionId = a.Questionid, userId = a.UserId };

And pass in the QuestionIds as parameters instead of hard coding them in the code. This new method can then be called from both of your existing methods and avoid duplicated code


text:
Q: How to reload data after flush I can run manage.py flush to purge the database. Now, how do I reload the initial data from the migrations file?
If I run manage.py migrate unit I get the following:
Operations to perform:
  Apply all migrations: unit
Running migrations:
  No migrations to apply.

My migration file mostly follows the example from the docs, except I modified the 0001 file to run the data loads after schema creation. E.g.,
class Migration(migrations.Migration):

    dependencies = []

    operations = [
        # django makemigration generated schema stuff
        ...
        # data creation stuff...
        migrations.RunPython(models_1_create, models_1_reverse),
        migrations.RunPython(models_2_create, models_2_reverse),
    ]

A: You can't, migrations are for modifying a databases schema, with data migrations to modify existing data.
You're better off making that a custom management command,
or if you really insist on redoing the migration, since you've already flushed the database, why not just drop the database completely and recreate it, then you'll be able to migrate again.
See also providing initial data with fixtures


text:
Q: AVAssetExportSession make black video sometimes I'm new baby for Video Processing use Swift 3. I try to merge multiple videos with AVAssetExportSession, and using AVVideoCompositionCoreAnimationTool to add overlay for final video.
The problem is sometimes the final video is perfect, but sometimes it just give me a black video with sound only even I didn't change anything :(
Anybody who ran into that problem same me please give an idea, thanks!
let mixComposition: AVMutableComposition = AVMutableComposition()

//Add assets here

let mainComposition: AVMutableVideoComposition = AVMutableVideoComposition(propertiesOf: mixComposition)
mainComposition.frameDuration = CMTimeMake(1, 30)
mainComposition.renderSize = renderSize
mainComposition.renderScale = 1.0
mainComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer)
mainComposition.instructions = instructions

let exportSession: AVAssetExportSession = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)!
exportSession.videoComposition = mainComposition
exportSession.audioMix = audioMix
exportSession.outputURL = outputURL
exportSession.outputFileType = AVFileTypeMPEG4
exportSession.shouldOptimizeForNetworkUse = true

exportSession.exportAsynchronously {
    // Ended here
}


text:
Q: Unable to setup Postgres in Nix-Shell I'm working on a Phoenix/Elixir project which is managed using nix-shell. I'm having issues regarding postgres setup.
I'm starting server using pg_ctl -D $PGDATA start and it outputs as:
pg_ctl: another server might be running; trying to start server anyway
waiting for server to start....2021-09-01 19:19:00.780 PKT [72367] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2021-09-01 19:19:00.784 PKT [72367] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"
2021-09-01 19:19:00.806 PKT [72369] LOG:  database system was interrupted; last known up at 2021-09-01 19:14:57 PKT
2021-09-01 19:19:00.848 PKT [72369] LOG:  database system was not properly shut down; automatic recovery in progress
2021-09-01 19:19:00.849 PKT [72369] LOG:  redo starts at 0/16D84A0
2021-09-01 19:19:00.849 PKT [72369] LOG:  invalid record length at 0/16D8580: wanted 24, got 0
2021-09-01 19:19:00.849 PKT [72369] LOG:  redo done at 0/16D8548
2021-09-01 19:19:00.862 PKT [72367] LOG:  database system is ready to accept connections
 done
server started

when I execute createuser postgres --createdb --echo in nix-shell envoirnment it produces following error even though the run directory exists.
createuser: could not connect to database template1: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/run/postgresql/.s.PGSQL.5432"?

No other postgres instance is running.
In pg_hba.conf auth method is set to trust.
unix_socket_directories is set to /tmp.
shell.nix looks something like
{ pkgs ? import <nixpkgs> {} }:

with pkgs;

let
  inherit (lib) optional optionals;

  elixir = beam.packages.erlangR22.elixir_1_10;
  postgresql = postgresql_11;
in

mkShell {
  buildInputs = [
    ps
    elixir
    coreutils
    which
    git
    postgresql
    redis
    doxygen
    mongodb-tools
    redis-dump
    (python37.withPackages(ps: with ps; [ credstash awscli ]))
    cmake
    nix-prefetch-git
    zlib
    jq
    teleport
  ]);

  # Fix GLIBC Locale
  LOCALE_ARCHIVE = lib.optionalString stdenv.isLinux
    "${pkgs.glibcLocales}/lib/locale/locale-archive";
  LANG = "en_US.UTF-8";

  # Put the PostgreSQL and Redis databases in the project diretory.
  PGDATA="./.db/postgres";
  RDDATA="./.db/redis";

  shellHook = ''
  ERL_INCLUDE_PATH="${erlangR22}/lib/erlang/usr/include";
}

I totally a noob to Nix and have no idea how to get it working.
Any help would be appreciated, thanks.

A: You have to tell createuser to connect via the socket in /tmp:
createuser -h /tmp -U postgres --createdb --echo newuser

A: You've set a custom path in the postgres config, so you probably also need to specify that with pqsl / createuser. In other words createuser -h /tmp/ ....


text:
Q: Copy end of string and paste to new column Which UNIX command do I use to copy the end of a string in column 1 and paste it to a new column?
For example,
> $ head -3 test1.bed
> HLA:HLA00001_A_01:01:01:01_3503  1
> HLA:HLA02169_A_01:01:01:02N_3291 1
> HLA:HLA14798_A_01:01:01:03_2903  1

Becomes,
> $ head -3 test1.bed
> HLA:HLA00001_A_01:01:01:01_3503  1 3503
> HLA:HLA02169_A_01:01:01:02N_3291 1 3291
> HLA:HLA14798_A_01:01:01:03_2903  1 2903

A: awk to the rescue!
$ awk '{n=split($1,a,"_"); print $0, a[n]}' file

HLA:HLA00001_A_01:01:01:01_3503  1  3503
HLA:HLA02169_A_01:01:01:02N_3291 1  3291
HLA:HLA14798_A_01:01:01:03_2903  1 2903


text:
Q: Simple Linear Algebra Proof - Determinants Prove or disprove the following statement:
If R is the RREF of A, then det A = det R.
So far, I think that this is true, considering A and R are row equivalent, and that the determinant changes as we row reduce in order to compensate for the changing rows. Although, I'm not sure how to go about proving this statement.
Any help would be appreciated, thanks.

A: Consider the matrix
$$
A =\begin{pmatrix}
2 & 0 & 0 \\
0 & 2 & 0 \\
0 & 0 & 2 \\
\end{pmatrix}
$$
The determinant is  $\det A = 2 \cdot 2 \cdot 2 = 8$ by multiplying down the diagonal. If you row reduce $A$ to a new matrix $R$ then what is the determinant of $R$?


text:
Q: Calculate -3db point in low pass inverting transistor audio amplifier What I am trying to do:
I am looking to find the \$ -3dB \$ frequency for my common emitter transistor amplifier with a capacitor in the feedback loop.
I have somewhat of an idea, but I wanted someone to confirm or correct my understanding.

simulate this circuit – Schematic created using CircuitLab
Notes:

*

*Assume my sine wave is actually audio with a full range of frequency - maybe white noise?

*My peak-peak voltage is ~200mV, i.e., I am not saturating the transistor.
My Thoughts:

*

*As the frequency decreases, such that, \$ \frac{1}{2\pi FC_{2}} > R_{3}\$, the feedback current from \$ Q_{collector} \$ to \$ Q_{base} \$ is controlled by \$ R_{3} \$, i.e., \$ 400k \Omega \$. Therefore, the gain for the frequencies will be whatever the gain of the transistor is?

*As the frequency increases, such that, \$ \frac{1}{2\pi FC_{2}} \rightarrow 0 \$, this will essentially short \$ Q_{collector} \$ to \$ Q_{base} \$, which should make the gain \$ 0 \$ for those frequencies.

*Given my above assumptions, if I calculate the frequency at which \$ \frac{1}{2\pi FC_{2}} = R_{3} \$, this will give me the \$ -3dB \$ point?

Calculating with my assumptions:
Rearranging the capacitive reactance formula:
$$ X_{c} = \frac{1}{2\pi FC} \therefore F = \frac{1}{2\pi CX_{c}}$$
Solving with actual values:
$$ Given: X_{c} = 400k, C = 400pF $$
$$
\frac{1}{2 * pi * 400 * 10^{-12} * 400 * 10^3} = 994.71Hz
$$
So... at \$ \approx 994Hz \$, my gain will \$ -3dB \$ than the gain at say, \$ 20Hz \$, where \$ X_{c} \approx 20M \$ ?
My question:
Can someone confirm my understanding is correct?

A: The transfer function is Av=G/(1+GH).
If you had an inverting Op Amp with an AOL of only 10 and a negative feedback Resistance ratio of 10:1 you will only get a closed loop gain of 2/3 of 10 as the simulation does with a peak gain of 6.7 and the -3dB point is 1.6kHz or 60% higher than the Rc*Cfb , yet not double either with the AC couple load of the same value.
The negative feedback lowers the collector output impedance so that the load has less attenuation effect than in the open loop case.
I'm not getting into the proof (others may correct my errors) but using Aol's of 1e5 or more the closed loop draws negligible input current and the feedback current matched the input current into a virtual null with Vin+. Here that that is not the case although the AC voltage at the base is certainly reduced significantly. The voltage is also attenuated by the low base input impedance of hFE * re.
So due to the low input impedance and low open loop voltage gain,  the closed loop gain is 1/3 less (for hFE=100)than the expected Rf/Rin of 400/39k~10. Also the bandwidth is not reduced as much as expected to ~1kHz because the feedback AC current does not match the generator input AC current. The simulator shows 1.6kHz.


text:
Q: humanize NoMethodError on padrino-0.14.1.1 I used padrino-0.14.1.1 and activesupport-5.1.1 in combination and I generate padrino admin app. When I display the login page (/admin/sessions/new) the following error occurred and become 500 error page.
DEBUG -  TEMPLATE (0.0007s) /sessions/new
2017-11-07 20:23:01 - NoMethodError - undefined method `humanize' for "login.title":String:
    /Path/to/app/'vendor/bundle' /ruby/2.3.0/gems/padrino-admin-0.14.1.1/lib/padrino-admin/helpers/view_helpers.rb:43:in `padrino_admin_translate'
...

I think it is not a bug of Padrino, because I cannot find same problems in the Internet. And I add the following require to the beginning of view_helpers.rb provisionaly.
require 'active_support'
require 'active_support/core_ext/string'

However, I think it is not good to edit Padrino's files because of my application problem. Please let me know if you have any other good countermeasures.

A: I got the answer of this question from Padrino maintainer on Github.
And I tried the suggestion in the answer, that worked well.
The answer is following.
--
Looks like a bug due to the ongoing effort to remove the ActiveSupport dependency from Padrino.
You don't need to update view_helpers.rb - creating a file in config/initializers should be sufficient as a temporary stop-gap until the bug is fixed.
# config/initializers/extra_requires.rb
require "active_support"
require "active_support/core_ext/string"


text:
Q: Asking the user to input one of the options and depending on the choice, the program shows the answer How to ask the user to input two numbers, and after that show these options:

sum,
average,
maximum,
minimum,
exit.

Then due to the user choice, the program shows the answer, and this process continues until the user input number 5.
My code does not work properly. Here is the code:
#include <stdio.h>
#include <iostream>

using namespace std;

int main() {
  int x, y, choice;
  char sum, average, max, min;
  cout << "Enter two numbers: " << endl;
  cin >> x >> y;
  cout << "Choose one of these options: \n";
  cout << " sum - average - max - min - exit " << endl;
  choice == sum || average || max || min;
  cin >> choice;

  sum == x + y;
  max == x > y || y > x;

  if (choice == sum) {
    cout << "The sum is: " << x + y << endl;
  }

  if (choice == average) {
    cout << "The average is: " << x / y << endl;
  }

  if (choice == max&& x > y) {
    cout << "The maximum is: " << x << endl;
  } else
      cout << " The maximum is: " << y << endl;

  if (choice == min&& x < y) {
    cout << "The minimun is: " << x << endl;
  } else
    cout << " The minimun is: " << y << endl;

  while (true) {
    string choice;
    cin >> choice;
    if (choice == "5") {
      break;
    }
  }
  return 0;
}

A: So you want to calculator which should end based on the user choice? If So
You can wrap the Function with a While loop and Keep a set a bool based on the user input. Like :
bool Terminate = false;
while(!Terminate)
{
    //Do Your Calculations Here

    //Ask for the User Input
    std::string UserChoice = "";
    std::cout << "Do You Want to Exit [ Y/N ]";
    std::cin << UserChoice;
    if(UserChoice == "Y" || USerChoice == "y")
    {
       std::cout << "Ending the Program";
       Terminate = true;
    }
}

If you have any doubts check this out
https://learn.microsoft.com/en-us/cpp/get-started/tutorial-console-cpp?view=msvc-160


text:
Q: How can I calculate the number of combinations in this set? I'm a real math newbie (I'm an English graduate; please be gentle). I'm building a webapp which allows users to manipulate an image, a little like Photoshop. The app needs to swap out the base image with a pre-rendered one depending on what settings the user chooses.
Currently we're trying to figure out how many editing controls there can be without having to create an infinite number of images. Right now I've been thinking of seven controls, eg:

*

*Exposure

*Noise

*Pressure

*(etc)

Even a rank amateur like me can see that seven of these fields will produce many permutations: at the moment I'm thinking of them as being binary inputs, eg. Exposure can either be on or off (therefore producing two distinct images), as opposed to a scale (eg. Exposure: 2, Noise: 4 etc).
With 7 field options, each with two states, that's 14 sample points in the set and 7 sample points in each permutation, right? I've been using this tool to help me wrap my head around the problem – it's saying there are 3432 combinations (or 17,297,280 permutations... yikes). Am I calculating this properly?
Alternatively, reading this question, it feels simpler. If I represent my switches like so:
Exposure    0 1
Noise       0 0
Pressure    0 0
XQ Mix      0 0
Invert      0 0
Desaturate  0 0
Equalise    0 0 ... etc

... then in effect I'm generating 7 digit numbers with 2 different possible values ($0$ and $1$) per digit, eg. $2^7$ (128 possible images). Is this right, or is my above methodology correct?


text:
Q: How can I optimize this: Many Postgres triggers calling the same function within a transaction I have a cached field in one of my database tables that get's updated based on many different tables and the state of fields in those tables.
Each of those tables calls the same function via a trigger:  updateCachedField(basetable_id INTEGER).  The updateCachedField function queries all these other tables and calculates the new cached value for the base table.  The updateCachedField function is complicated and very cost heavy.
During a single transaction it's possible for many of the tables that affect the cached field to be changed.  So during a single transaction, the updateCachedField function may get called 50 times... but with only 5 different basetable_id's.
Is there a way to optimize this so that the updateCachedField function only gets called 5 times instead of the 50+?

A: I think your best option is to use a deferrable constraint trigger and query based on the xmin value or other information.  You could in fact also copy "log" data for snapshotting somewhere else.
Without clear information its not really clear what you are looking at but one option is to essentially have three sets of tables:

*

*Live tables.  Updates (deltas or other aggregate-useful info) get written to log tables on update or insert.

*Log tables.  These are append only.

*Aggregate snapshot tables which periodically aggregate new sets of log tables.
You could then have a live view which would show current aggregate data, aggregating only from the last snapshot.


text:
Q: How to insert code in a method in a derived class I have a base class with a method called Update:
Start Update

    Code block 1 (An If statement)

    Code block 2 (Setting a variable based on the If result)

    Code block 3 (A switch which is setting something)

End Update

The order in which the code is executed is important so they can't be shifted around.
I also have a derived class which needs a little bit more code. This code however has to be in between Code Block 1 and 2. So when I would rewrite the entire thing it would be something like this:
Start Update

    Code block 1 (An If statement)

    Code block 4 (An extra calculation based on the If result)

    Code block 2 (Setting a variable based on the If result)

    Code block 3 (A switch which is setting something)

End Update

I'm looking for ways how to reuse Code Block 1 through 3 and also put Code Block 4 in there.
The best thing I came up with is having a method called Extra in my base class and have the Update method look like this:
Start Update

    Code block 1 (An If statement)

    Call Extra

    Code block 2 (Setting a variable based on the If result)

    Code block 3 (A switch which is setting something)

End Update

In the base class the Extra method would be empty since it has no use here.
The derived class would also have the Extra method but in that method the following would be called:
Start Extra

    Code block 4 (An extra calculation based on the If result)

End Extra

A: Here's an alternative approach to consider.
Make Blocks 1, 2 and 3 into (protected) methods on the base class.  Make the base class' Update call these three methods.
Add Block 4 as a (private) method on the derived class.  Make the derived class' Update call all four methods in the required order.
You've got a bit of a contradiction between the DRY principle here and the Open/Closed principle.  Really, you shouldn't be hacking about in the base class to add functionality to the derived one.  But making the code clean, maintainable and readable is more important than obsessing about the various SOLID principles.

A: I understand your question as being about style, not so much about technical possibilities.
From the comments in your code sample, I'd like to give names to your blocks (you can surely do better than I, knowing what the steps really are about):

*

*FindUpdateSituation

*SetGenericData

*SetCaseSpecificData

Whatever you name the blocks, it will surely make sense to refactor them into individual methods.
Now the question is "Where do the additional actions that we called Block4 fit best?" And that needs some analysis, where I see (at least) three possible outcomes:
Version A:
After some thinking, you find that for your base class and all derived classes, updating still is a 3-step process consisting of the blocks named above, and that Block4 just sets some generic data, and fits into that part. Then override the SetGenericData method, prepending the new action before calling the base implementation.
Version B:
You find that from an abstract point of view, the Update method always should have been a 4-step process, and should have had a SetSpecialVariables block, which just (because of the clever implementation of your base class) happened to be empty there. Then introduce the SetSpecialVariables call into the base implementation, add an empty method there and the proper one in your derived class.
Version C:
You find that it's just coincidence that the Update methods of base class and derived class have some elements in common. Then override the Update method in the subclass, using the refactored individual-block methods if their names (not their implementation) describe what the subclass needs.

A: Setting your base class method with virtual will allow you to override then and reimplement them at derived class.

A: I think the approach you came up with is a valid one and it is close to the template method design pattern.
you can search for the design pattern for further info and see if it matches your requirements
Edit
to make the answer clear,
let's say that you have a base alogrithm for a generic solution that consists of certain steps:
begin Solution
     call step 1
     call step 2
     call step 3
     call step 4
 end solution

and the solution needs to be customized in certain scenarios by adding extra pieces of code in between the known steps.
one way to do it is to do as Simon B said:
1- make the known steps protected in the parent class
2- create a method that contains the extra code you need in the child class
2- define a solution method in the child class and call the known steps from the parent class and insert your call you extra code in the correct place.
one risk you have here is that any class inheriting you base class will have the ability to modify your solution by defining their solution method and doing whatever they want or simply changing the order of the steps call.
what I think you can do is define the following proteceted no-op methods in the base class:
preStep1
postStep1
preStep2
postStep2
preStep3
postStep3
preStep4
postStep4
and then modify the solution method to look like:
begin Solution
     call preStep 1
     call step 1
     call postStep 1
     call preStep 2
     call step 2
     call postStep 2
     call preStep 3
     call step 3
     call postStep 3
     call preStep 4
     call step 4
     call postStep 4
 end solution

and then in the child class, you can modify any the of preStep* or postStep* as needed to insert your code in the correct place.
also, if you want to make sure the general flow of the solution does not change (step1 -->step2-->step3-->step4) then you can make the solution method in the parent class final.
this mathces the open-closed principle, since in the future if you want to define another child class with a different code to be inserted -let's say before step 4- then you just need to extend the parent class and override the the preStep4 method. thus, you added a new code in the middle of the base solution but the only change is the declaration of the new child class.
and I believe alot of existing frameworks use this design pattern and call these extra methods lifeCycle hooks that developer can use to execute extra code at specific points of time in the lifecycle.


text:
Q: How to externalize a class that extends another Introduction
I have the following class:
public class Foo extends ArrayList<ElementsClass> implements Externalizable {
    Field field1 = new Field();
    Field field2 = new Field();

    ...
}

I implement the methods writeExternal and readExternal like this:
public void writeExternal(ObjectOutput out) throws IOException {
    out.writeObject(field1);
    out.writeObject(field2);
}

public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException {
    field1 = (Field) in.readObject();
    field2 = (Field) in.readObject();
}

Observation
One of the fields is not Serializable that is why I implement Externalizable. I want to externalize only those things that I am able to.
Problem
Although I know that the ArrayList<ElementsClass> is serializable if ElementsClass is serializable, I don't know how to externalize the class Foo itself.

A: Try this:
public void writeExternal(ObjectOutput out) throws IOException {
    out.writeObject(super.toArray());
    out.writeObject(field1);
    out.writeObject(field2);
}

public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException {
    Object[] arr = (Object[]) in.readObject();
    for (int k=0; k<arr.length; k++) super.add(arr[k]);
    field1 = (Field) in.readObject();
    field2 = (Field) in.readObject();
}

A: Is it not that your class Foo is already externalized?
If you execute, statements like below, It should write the object in the file with the entries of externalized attributes.
    Foo class = new Foo();
    FileOutputStream fos = new FileOutputStream("temp");
    ObjectOutputStream oos= new ObjectOutputStream(fos);
    oos.writeObject(class );

A: I think you should try a custom serialization, like the one descriped here: https://stackoverflow.com/a/7290812/1548788


text:
Q: what is the zero connected to some MUX in this 8 bit right shifter
in this picture of an 8 bit right shifter, can someone please tell me what those 0's represent ? in the first row of MUX there is one zero connect, in the second row the first two have 0 connected, and in the third row there are 4 zeros connected?

A: There are three shifting possibilities:

*

*shift(0) is the bit0 of the shift amount. It weights 20 = 1.
Setting that bit shift at least 1 bit.

*shift(1) is the bit1 of the shift amount. It weights 21 = 2.
Setting that bit shift at least 2 bits.

*shift(2) is the bit2 of the shift amount. It weights 22 = 4.
Setting that bit shift at least 4 bits.

When shifting the incoming bits must be set to zero for logical shifts ( 01001101 shifted left by 3 becomes 01101000) and that's the reason for those zeros.
The circuit (a barrel shifter) basically decomposes a shift amount into a sum of powers of two (e.g. 5 as 1 + 4) so that any amount in the range 0-7 (3-bit of a number) can be done using a fixed arrangement of wires in one clock.
A SISO (Serial In, Serial Out) register would require multiple clock cycles.


text:
Q: IndexedDB fully backup and restore of databases (without Dexie.js) I want to backup IndexedDB into json file, and restore it on another machine / browser.
the goal is to fully backup and import website session (localStorage, cookies etc...)
I think that dumpIndexedDb() function works correctly,
the problem occur when I try to get this data and restore it back using restoreIndexedDbDump(data). there's no errors.
but only few databases restored.
I'm pretty sure I was missed something with indexedDB api in the restore operation.
thanks in advance.
function dumpDB(dbName) {
    return new Promise((resolve, reject) => {
        var request = indexedDB.open(dbName)
        request.onerror = e => reject(e)
        request.onsuccess = (e) => {
            var data = {} // { dbVersion: 1, oName: {keyPath: 'key', data: [{},{}]} }
            var db = e.target.result
            var dbVersion = db.version
            data['dbVersion'] = dbVersion
            data['objectStores'] = {}
            var oStores = db.objectStoreNames
            for (let osName of oStores) {
                var transaction = db.transaction(osName, "readonly")
                var oStore = transaction.objectStore(osName)
                var keyPath = oStore.keyPath
                data['objectStores'][osName] = {}
                data['objectStores'][osName]['keyPath'] = keyPath
                var request = oStore.getAll()
                request.onerror = e => reject(e)
                request.onsuccess = (e) => {
                    data['objectStores'][osName]['data'] = e.target.result
                }
            }
            db.close()
            resolve(data)
        }
    })
}

async function dumpIndexedDb() {
    var data = {}
    var dbs = await indexedDB.databases() // not working in firefox, tested in chrome.
    for (let db of dbs) {
        var dbData = await dumpDB(db.name)
        data[db.name] = dbData
    }
    return data // {dbName: { dbVersion: 1, oName: {keyPath: 'key', data: [{},{}]} } }
}

function restoreObjectStore(dbName, version, oName, keyPath, data) {
    return new Promise((resolve, reject) => {
        request = window.indexedDB.open(dbName, version);
        request.onerror = e => reject(e)
        request.onupgradeneeded = function (e) {
            try {
                var db = e.target.result
                if (keyPath) var objectStore = db.createObjectStore(oName, { keyPath: keyPath, autoIncrement: false })
                else var objectStore = db.createObjectStore(oName, { autoIncrement: false })
                for (let row of data) {
                    console.log(`adding row of ${oName}`)
                }
                objectStore.transaction.commit()
                db.close()
                resolve("ok")
            } catch(e) {
                reject(e)
            }
        }
    })
}

async function restoreIndexedDbDump(data) {
    for (let dbName in data) {
        console.log(`deleting db ${dbName}`)
        indexedDB.deleteDatabase(dbName)
        for (let oStoreName in data[dbName]['objectStores']) {
            let odata = data[dbName]['objectStores'][oStoreName]['data']
            let dbVersion = data[dbName]['dbVersion']
            if ( data[dbName]['objectStores'][oStoreName]['keyPath'] ) {
                var keyPath = data[dbName]['objectStores'][oStoreName]['keyPath']
                await restoreObjectStore(dbName, dbVersion, oStoreName, keyPath, odata)
            }
            else {
                await restoreObjectStore(dbName, dbVersion, oStoreName, null, odata)
            }
        }
    }
}

async function testBackupandRestore() {
    var data = await dumpIndexedDb()
    await restoreIndexedDbDump(data)
}


text:
Q: How to prevent $ interpretation in JSP to make jQuery templates work I have a page generated with data from both backend and front. The front end is using a jquery template, and page itself is written in JSP, and there is a conflict of using $ sign:
<script type="text/javascript">
   ${title}
</script>

For example, I want the above code to be interpreted by front end, but JSP is translating to something else. How do I prevent this from happening?
thanks
Oliver

A: Add this to the top of the page:
<%@ page isELIgnored="true" %>

This should only be in the page which defines the template. Include that page from the main page, if you want to use EL in it.

A: You could try using the following for any problematic lines
out.print("${title}")

A: Put backslash before dollar sign and it won't be interpreted as JSP EL.
\${title}

So, ${1+1} prints 2 and \${1+1} prints ${1+1}.
Otherwise, you can do what Jared says.

A: Why not enclose them between jsp:text or move all your template code in a .js file if possible.

A: also you can use this
<%="${name}"%>


text:
Q: Entity Framework infers relationship I have some code that is working, but I don't know how.  I'm asking this question in hopes that someone can explain how it is working, as any searching I do online gives me information that's not quite specific to what I'm seeing.
I have two entities.
EntityA, EntityB.
EntityA has this:
public partial class EntityA
{
    ...
    public Guid EntityBGuid { get; set; }
    public virtual EntityB EntityB { get; set; }
}

EntityB has this:
public partial class EntityB
{
    ...
    public virtual ICollection<EntityA> EntityAs{ get; set; }
}

Nowhere in DatabaseEntities.cs > OnModelCreating() is a relationship defined for either entity.
Nowhere in either table in SQL is there a FK defined for the relationship.
So when I do something like this:
context.LettingProjects.Where(query).Select(s => s.Call).ToList(); //Crash.

But with a .Include, I get data:
context.LettingProjects.Include(i => i.Call).Where(query).Select(s => s.Call).ToList(); //Results.

My question is how does this even work?  I don't know how EF handles this in the background, and it seems like a gotcha waiting to happen.

A: When you are writing this:
context.LettingProjects.Where(query).Select(s => s.Call).ToList();

EF will simply query for a single table.
However, as you probably configured the relationships in your models to contain other Tables too (ICollection<EntityA>), they will contain a null value because EF will not send a query asking for their data.

My question is, how does this even work? I don't know how EF handles this in the background, and it seems like a gotcha waiting to happen.

The answer to your question now should be simple:
when you write .Include(s => s.OtherTable) you are asking EF to join your current table data with the one you specified.
EF will use the Foreign Key relationships and will give you back a collection of items with the data for the related tables, too (not null version). That's why it will not fail.

This is very similar to using the LINQ to Entities Join method, but in this case, it's requiring you to write much less code unless you want to control the join operation by yourself.


text:
Q: How do I run a SQL query only if it has no specific value in it I have a problem with an sql query i want to run. Basically I want to update a table only if it has no '.' in it (for example 1 row has value '2' and the other row will have value '2.1', in this case i would only want to update the value with a 2.) This is what I tried
UPDATE new__tags SET sort_order = 1 WHERE id = '.$id. ' AND sort_order NOT LIKE "%.%"';

Unfortunately this did not work and still updated everything.
Thanks for your time.

A: Try this:
"UPDATE new__tags SET sort_order = 1 WHERE id = $id AND CAST(sort_order AS CHAR) NOT LIKE '%.%'";

A: If your sort_order is an INT , use CAST
"UPDATE `new__tags` SET `sort_order` = 1 WHERE `id` = '.$id. ' AND CAST(`sort_order`  as CHAR) NOT LIKE '%.%'";

A: try this i tested with phpmyadmin
"UPDATE new__tags SET sort_order = 1 WHERE id = $id AND sort_order NOT REGEXP '[.]'";


text:
Q: Counting each punctuation I have a CSV file that contains a large amount of data, and I want to count the number of each punctuation.
For now I only know how to count the whole punctuations of the text but not each of them separated.
I would like to have the number each punctuation in each row saved in a CSV file.
Below are my attempts to get the number of each punctuation, but I got errors like re.error: nothing to repeat at position 0'.
news=pd.read_csv("cluesnew.csv")
news['?']= news.string_column.str.count('?')
news['[']= news.string_column.str.count('[')
news[']']= news.string_column.str.count(']')
news['!']= news.string_column.str.count('!')
news[';']= news.string_column.str.count(';')
news['{']= news.string_column.str.count('{')
news['}']= news.string_column.str.count('}')
news['/']= news.string_column.str.count('/')
news['-']= news.string_column.str.count('-')
news['_']= news.string_column.str.count('_')
news[',']= news.string_column.str.count(',')
news['.']= news.string_column.str.count('.')
news[':']= news.string_column.str.count(':')
news['`']= news.string_column.str.count('`')
news['...']= news.string_column.str.count('...')
news.to_csv("cluesnew.csv")

Some examples of cluesnew.csv
ID string_column
1  In 2017 alone, death due to diabetes was recorded at 10.1 per cent.
2  12.4 per cent of the country's citizens have diabetes.

An example of the resulting dataframe would be:
string_column                                                         . , [ ] ! ` { ....
In 2017 alone, death due to diabetes was recorded at 10.1 per cent.   1 1 0 0 0 0 0 ....
12.4 per cent of the country's citizens have diabetes.                1 0 0 0 0 1 0 ....

I appreciate any help, thanks.

A: You don't need pandas to do that. The standard library csv module can handle the task.
Here is a possible solution in Python 3 using csv module:
from string import punctuation
from collections import OrderedDict
from pathlib import Path
import csv

source = Path('/path/to/source.csv')
target = Path('/path/to/target.csv')

with source.open() as src, target.open('w') as tgt:

    csvreader = csv.reader(src, quoting=csv.QUOTE_ALL)
    csvwriter = csv.writer(tgt, quoting=csv.QUOTE_ALL)

    # skip header line from source
    next(csvreader)

    # write the header to target
    csvwriter.writerow(['string_column'] + [_ for _ in punctuation])

    counter = OrderedDict()

    for string_column, *_ in csvreader():
        # reset the counter for each line
        counter.clear()

        string_column = line.rstrip()

        # count punctuation
        for c in punctuation:
            counter[c] = string_column.count(c)

        # write the line
        csvwriter.writerow([string_column] + [counter[_] for _ in punctuation])

After that, you can easily read the resulting target.csv into a pandas data frame if you want to, with something like this:
>>> import pandas as pd
>>> df = pd.read_csv(target)
>>> df.columns
Index(['string_column', '!', '"', '#', '$', '%', '&', ''', '(', ')', '*', '+',
       ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\', ']',
       '^', '_', '`', '{', '|', '}', '~'],
      dtype='object')
>>>

I hope it helps.

A: This is one approach using regex.
Ex:
import re
import string

df = pd.DataFrame({'string_column': ['In 2017 alone, death due to diabetes was recorded at 10.1 per cent.', "12.4 per cent of the country's citizens have diabetes."]})
for i in string.punctuation:
    if i == '.':
        df[i] = df['string_column'].str.count(r"{}(?![0-9])".format(re.escape(i)))
    else:
        df[i] = df['string_column'].str.count(re.escape(i))
print(df['.'])
print(df[','])

Output:
0    1
1    1
Name: ., dtype: int64
0    1
1    0
Name: ,, dtype: int64

A: You can get all punctuations from your string like this:
import string
p = [ch for ch in s if ch in string.punctuation]

Then you can count how many times each character (punctuation in this case) is encountered like this:
from itertools import groupby
counts = [len(list(punc)) for key, punc in groupby(p)]


text:
Q: type mismatch runtime error 13 access 2007 I just migrated to ms access 2007 and created my own ribbon.
In my form, I have this "print" button where if you click that it will open the "report form"
here is what I wrote in my VBA code:
Case "btnPrintRevisionEingabe"
DoCmd.OpenReport acReport, "Revision_Eingabe_rpt", acSaveNo

and when I clicked on the "print" button
I'm getting an error "type mismatch runtime error 13"....
Please help..
Thanks

A: Try just the following
docmd.OpenReport "Revision_Eingabe_rpt", acViewReport

nothing after that. Leave out the acSaveNo. That should work.


text:
Q: Rspec check method is executed within a block class Foo
  def self.with_context
    # some preprocessing stuff
    yield
    # some postprocessing stuff
  end

  def self.bar
    with_context do
      #some stuff here
    end
  end
end

How I can test the Foo.bar method is run inside Foo.with_context ?
It should pass on the above example.
But should fail on the example below:
class Foo
  def self.with_context
    # some preprocessing stuff
    yield
    # some postprocessing stuff
  end

  def self.bar
    #some stuff here ( not within the with_context block - FATAL)
  end
end


text:
Q: Indexing in Excel using VBA The below code is used in My workbook for Indexing. Problem is this code is overwriting the cells in A1 with "Back to Index". How can I modify this code so it does not overwrite the current value A1 cell in each sheet and a Hyperlink in A1 cell with current value retained is created back to the Index page? TIA
Private Sub Worksheet_Activate()
Dim wSheet As Worksheet
Dim l As Long

l = 1

    With Me
        .Columns(1).ClearContents
        .Cells(1, 1) = "INDEX"
        .Cells(1, 1).Name = "Index"
    End With

    For Each wSheet In Worksheets
        If wSheet.Name <> Me.Name Then
            l = l + 1
                With wSheet
                    .Range("A1").Name = "Start_" & wSheet.Index
                    .Hyperlinks.Add Anchor:=.Range("A1"), Address:="", _
                    SubAddress:="Index", TextToDisplay:="Back to Index"
                End With

                Me.Hyperlinks.Add Anchor:=Me.Cells(l, 1), Address:="", _
                SubAddress:="Start_" & wSheet.Index, TextToDisplay:=wSheet.Name
        End If
    Next wSheet

End Sub

A: Seems pretty straightforward to me but perhaps I did not understand the problem.
    With wSheet
        .Range("A1").Name = "Start_" & .Index
        .Hyperlinks.Add Anchor:=.Range("A1"), Address:=vbNullstring, _
        SubAddress:="Index", TextToDisplay:=.Range("A1").Text
    End With


text:
Q: zoo-project missing lib libzoo_service.so.1.5 While running this command in zoo-project on ubuntu 14.04 , 64 bit
./zoo_loader.cgi "request=Getcapabilities&servise=wps"

./zoo_loader.cgi: error while loading shared libraries: libzoo_service.so.1.5: cannot open shared object file: No such file or directory
A file seems missing. How can I fix it ?

A: Can you please try to manually run the "sudo ldconfig" command. This should solve the issue in case the libzoo_service.so.1.5 is located in a directory that is referenced from /etc/ld.so.conf or /etc/ld.so.conf.d/* files.


text:
Q: Add item to Visual Studio source control context menu I would like to create an extension for VS Source Control Explorer context menu,
In order to add an option on the Text Editor context menu I know you need to set IDM_VS_CTXT_CODEWIN on Group's Parent node into the vsct file.
Can someone tell me the correct value for Source Control Explorer context menu?

A: I don't think that particular context menu guid:id pair is published anywhere. I usually try searching the various .VSCT files under the ….VSSDK\VisualStudioIntegration\Common\Inc directory to find a unique menu item in the context menu, figure out what menu group it's parented to, and work back from there.
But given the thousands of commands and menus wired into the IDE, this can be a hit or miss scenario.
When a search of the various .VSCT files on the above mentioned path doesn't pan out, I usually revert to using the EnableVSIPLogging registry key, to discover the guid:id pair for the given context menu.
Easiest way to set this is to install Mad's Extensibility Tools extension, which adds an "Enable VSIP Logging" command on the IDE's main "View" menu. Once you set this, if you hold down the CTRL+SHIFT keys, while right clicking in the Toolwindow, you'll get a diagnostic message box, with the guid and id of the context menu. You can use these as the parent for the menu group containing your command.
For example:

VSDebug Message
Menu data:
Guid = {**FFE1131C-8EA1-4D05-9728-34AD4611BDA9**}
GuidID = 962
CmdID = ***4113***
Type = 0x00000400
Flags = 0x04000000

    NameLoc = (null)
OK
Where FFE1131C-8EA1-4D05-9728-34AD4611BDA9 is the context menu guid, and 4113 is the menu id.
Note, if you hold the CTRL+SHIFT while selecting an actual command, the same dialog will appear, but the guid and cmdid, will identify the specific command(menu item) selected.
Sincerely,


text:
Q: Convert String to Sort with in Spring REST RequestParam I want to do a custom Page and Pageable class because I am not really satisfied with the JSON got from these Spring classes. For that, I have two POJO with a converter function to Pageable to use PagingAndSortingRepository interface.
I want to reuse Spring Sort in my CustomPageable, but when I call my API, Spring fails to convert my String sort=foo,asc in a Sort object. I have checked the PageRequest class to do how it work and I don't understand why the conversion doesn't work in the case of my POJO.
Here is my endpoint:
@GetMapping(path = "/versions", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<CustomPage<VersionDto>> getVersions(CustomPageable pageable) {
        final var page = repository.findAll(pageable.toSpringPageable()).map(version -> new VersionDto(version.getId()));
        final var customPage = CustomPage.from(page, VersionResource.class, ressource -> ressource.getVersions(null));
        return ResponseEntity.ok(customPage);
    }

And here is my CustomPageable class:
@Data
public class CustomPageable {

    private final int limit;
    private final int offset;
    private final Sort sort;

    public CustomPageable(Integer limit, Integer offset, Sort sort) {
        this.offset = offset == null ? 0 : offset;
        this.sort = sort;
        if(limit == null && offset == null)
            this.limit = Integer.MAX_VALUE;
        else
            this.limit = Objects.requireNonNullElse(limit, 20);
    }

    public Pageable toSpringPageable() {
        return PageRequest.of(offset, limit, sort);
    }

    public String toString() {
        return "?limit=" + limit + "&offset=" + offset;
    }
}

The query I do:
localhost:8080/versions?sort=releaseTime,asc

The error:
Field error in object 'customPageable' on field 'sort': rejected value [releaseTime,asc]; codes [typeMismatch.customPageable.sort,typeMismatch.sort,typeMismatch.org.springframework.data.domain.Sort,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [customPageable.sort,sort]; arguments []; default message [sort]]; default message [Failed to convert value of type 'java.lang.String' to required type 'org.springframework.data.domain.Sort'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'org.springframework.data.domain.Sort': no matching editors or conversion strategy found]]

Thank for your help!


text:
Q: Node.js - How to throttle and limit logic but not limiting main endpoint? The question might sound a little weird but I am not sure how to handle this specific issue.
I have a requests than does a few things and sends a response back to the client.
In this specific requests i am also doing something after the response is sent back to do some backround stuff. The issue is lying inside this piece of logic / functionality since it requests a third party public API that has a rate limit. Let's say i send 20 requests/s to this endpoint.
10 requests will be processed by the third party public API and processed correctly, but the last 10 requests will not be processed and will return a rate limit error.
My question is - How can I change this logic / endpoint to support my demands. Any feedback and suggestions is much appreciated.
// endpoint /get-data/
await doAlotOfLogicHere();

setTimeout(() => {
      // Do something after 1 seconds
      // This specific action can only take 10 requests / second
      controller.doSomething(req,res)
    }, 1000);

// Send response to client
res.status(200).send(data);

controller.doSomething()
exports.doSomething = (req,res) => {
await sendDataToPublicAPI();
}

A: Your problem is a little big vague... Let me suggest something, though.

*

*Push the user request to a queue (this would be a database table with the resource, payload and timestamp)

*Fire it from a schedule or enter link description here

*Make little asynchronous request to check whether the response is avaiable

*Fetch the result data. It's best if you can cache it in your own database