text:
Q: Return a list of lists from elements grouped by another column I don't know how to describe my question, so I will just show an example here.
A B
1 3
1 4
2 5
2 8
2 6
3 6
3 8
4 10
4 1

The data frame has two column A and B. I want to make it return a list like this.
[[3,4],[5,8,6],[6,8],[10,1]]

As you see, this is grouped by A and returns a list of numbers in B column. To be noticed, the order of elements in B DOESN'T CHANGE. Also the sub-lists have the same order as shown in column A. ([3,4] from group 1, [5,8,6] from group 2, etc)
Suppose dataframe is ordered by A already. I know how to use for loop to do it, but my dataset has 1 billion records. So I am looking for some efficient and clean code for this problem.

A: You first need to group on the first column A, then get the unique values in B (assuming you only want unique values and not duplicates).  After you've done that, use a lambda expression to convert each of the np.array values to lists, and then convert the resulting series to a list using .tolist().
>>> df.groupby('A', sort=False)['B'].apply(list).tolist()

Or,
>>> [list(v) for v in df.groupby('A', sort=False)['B'].unique()]

Or,
>>> df.groupby('A', sort=False)['B'].apply(lambda x: x.unique().tolist()).tolist()

[[3, 4], [5, 8, 6], [6, 8], [10, 1]]

I would also recommend not sorting the groupby operation.
Here are some timing comparisons for anyone who is interested:
df_ = pd.concat([df] * 10000)  # Set-up larger dataframe with 90k rows.

%timeit df_.groupby('A', sort=False)['B'].unique().apply(list).tolist()
# 100 loops, best of 3: 5.9 ms per loop

%timeit df_.groupby('A', sort=False)['B'].apply(list).tolist()
# 100 loops, best of 3: 6.79 ms per loop

%timeit list(map(list, df_.groupby('A', sort=False)['B'].apply(list)))
# 100 loops, best of 3: 8.02 ms per loop

A: An alternative to @Alexander's solution is to apply list to each element of a groupby.apply(list) object.
In general, I would prefer this solution to a lambda based solution, which is just a loop.
res = list(map(list, df.groupby('A', sort=False)['B'].apply(list)))

Result:
[[3, 4], [5, 8, 6], [6, 8], [10, 1]]

A: For large datasets I recommend using Numpy as it is faster.
I also recommend not using a for-loop to sort, df.sort_values() is way faster.
Here is a comparison of a 15 Million row dataset I worked on.
Via Numpy
import numpy as np
df = df[['a','b']]

keys, values = df.sort_values('a').values.T
ukeys, index = np.unique(keys, True)
arrays = np.split(values, index[1:])
df = pd.DataFrame({'a':ukeys,'b':[list(a) for a in arrays]})

NUMPY
Total time: 102.379 s for 15,397,309 rows
Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     3         1    1205208.0 1205208.0      1.2
     4         1   60671365.0 60671365.0     59.3
     5         1   16897187.0 16897187.0     16.5
     6         1    1430774.0 1430774.0      1.4
     7         1   22174794.0 22174794.0     21.7
     8         1          4.0      4.0      0.0

With Pandas 'Groupby'
df.groupby('a')['b'].apply(list)

PANDAS GROUPBY
Total time: 146.23 s for 15,397,309 rows

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     3         1    1181714.0 1181714.0      0.8
     4         1  145048477.0 145048477.0     99.2
     5         1          3.0      3.0      0.0

A: There are different approaches :
data is:
with open('textrr','r') as f:
    data=[line.split() for line in f.readlines()]

first approach using collections.defaultdict()
d=collections.defaultdict(list)

for item in data:
    d[item[0]].append(item[1])

print([i for i in d.values() if i[0].isdigit()])

output:
order will be not same :
[['10', '1'], ['6', '8'], ['3', '4'], ['5', '8', '6']]

using itertools.grouby:
import itertools
print([[sub[1] for sub in i] for j,i in itertools.groupby(data,key=lambda x:x[0]) if list(j)[0].isdigit()])

output:
order will be same
[['3', '4'], ['5', '8', '6'], ['6', '8'], ['10', '1']]

At last if you don't want to use any import then you can try manual approach:
groupby={}

for item in data:
    if item[0].isdigit() and item[0] not in groupby:
        groupby[item[0]]=[item[1]]
    elif item[0].isdigit():
        groupby[item[0]].append(item[1])

print(groupby.values())

output:
[['10', '1'], ['3', '4'], ['6', '8'], ['5', '8', '6']]


text:
Q: How to run .sql script file in c++? I want to execute a script file of mysql in my code, written in c++. How i can do it ?

A: You can always use the system function to call the mysql program to do it for you.

A: Well, if you want the optimal solution, simply iterate over each line (your SQL file shall have only ONE command for each line) using the standard C++ file handlings.
You simply pass each line to the MySQL library calls. This is what I do for my SQLite initialization scripts.
You can even add a very minimal comment support (like --) and skip any line starting with those characters.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to click on  inside  Python I want to click on a certain option by id.. the problem is above the select I've got

....

thats what becomes visible when if I click the dropdown button
and than I have the select
<select id="ControlGroupContact_ContactInputView_DropDownListStateProvince" name="ControlGroupContact$ContactInputView$DropDownListStateProvince" readonly="false" class="jqTransformHidden"><option selected="" value="">Escolha um</option>
                <option value="BR|AC">Acre</option>...

I've tryied to use that code:
countries_dropdown = self.browser.find_element_by_class_name('countryBR')
    countries_dropdown.click()
    country_dropdown = Select(countries_dropdown.find_element_by_id('ControlGroupContact_ContactInputView_DropDownListCountry'))

    country_dropdown.select_by_value(payer_details.country_code.upper())

so I'm even opening the dropdown even if I open and even if I dont open the drop down, the error im getting is
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated
  (Session info: chrome=44.0.2403.125)
  (Driver info: chromedriver=2.15.322448 (52179c1b310fec1797c81ea9a20326839860b7d3),platform=Windows NT 6.3 x86_64)

A: It looks like the jqTransformHidden class makes it hidden. Remove the class and make it visible:
dropdown = countries_dropdown.find_element_by_id('ControlGroupContact_ContactInputView_DropDownListCountry')
driver.execute_script("arguments[0].className = '';", dropdown)


text:
Q: What does "the expansion of a vector relative to a basis is unique" mean in this proof of the Fundamental Theorem of Linear Algebra? In the following proof, what does "But the expansion of a vector relative to a basis is unique" mean?

Let$$T:V\to W$$ be a linear transformation. Then $$dim(Im(T))+dim(ker(T))=dim(V)$$
$\mathbf{Proof:}$
Let $dim(Ker(T)) = k$. We start by choosing a basis$$\{v_1,v_2,...,v_k\}$$ for the kernel.
If $k = 0$, then $Ker(T) = \{0\}$ and the basis is empty, so the vectors
$v_1, . . . , v_k$ do not appear in the rest of the proof.
Let $dim(V) = n$. If $n = k$, then every vector in V is in the kernel and so $Im(T) = \{0\}$ has dimension 0. Then there is nothing to prove.
If $n>k$ then we can add an additional $n − k$ vectors to the basis for $Ker(T)$ to get a basis for V:
$$\{v_1, . . . , v_k, v_{k+1}, . . . , v_n\}$$
We claim that
$$\{T(v_{k+1}), . . . , T(v_n)\}$$
is a basis for $Im(T)$.
Proof that this is a spanning set for Im(T):
Every vector in $Im(T)$ has the form $w = T(u)$ for some $u ∈$ V. We can expand $u$ using the basis for $V$:
$$u = c_1v_1 + · · · + c_kv_k + c_{k+1}v_{k+1} + · · · + c_nv_n$$
Since vectors $v_1, . . . , v_k$ are in the kernel of $T$, this gives
$$w = T(u) = c_{k+1}T(v_{k+1}) + · · · + c_nT(v_n)$$
So every vector in $Im(T)$ is a linear combination of
$T(v_{k+1}), . . . , T(v_n)$.
Proof that this is a linearly independent set:
Suppose we have
$$a_{k+1}T(v_{k+1}) + · · · + a_nT(v_n) = 0$$
Then, since T is linear,
$$T(a_{k+1}v_{k+1} + · · · + a_nv_n)= 0$$
So the vector $a_{k+1}v_{k+1} + · · · + a_nv_n$ is in the kernel of $T$.
Since ${v_1, . . . , v_k}$ is a basis for the kernel, it must be possible to write
$$a_{k+1}v_{k+1} + · · · + a_nv_n = b_1v_1 + · · · + b_kv_k$$
But the expansion of a vector relative to a basis is unique, so all the $a_i$ and all the $b_j$ must be zero.
Therefore
$${T(v_{k+1}), . . . , T(v_n)}$$
is a basis for $Im(T)$.
Hence $$dim(Im(T)) = n − k$$
And
$$dim(Ker(T)) = k, dim(V) = n$$
which shows that
$$dim(Im(T)) + dim(ker(T)) = dim(V)$$

EDIT:
If
$$a_{k+1}v_{k+1} + · · · + a_nv_n = b_1v_1 + · · · + b_kv_k$$
is possible for some constants, then that means
$$-b_1v_1 - · · · - b_kv_k+a_{k+1}v_{k+1} + · · · + a_nv_n = 0$$
is possible for some constants. But that cant be the case as $v_1,...,v_k,v_{k+1},...,v_n$ form a basis for $V$ and thus no non-zero constants should satisfy the equation.
Is that correct?

A: It means that for a fixed basis $\{v_1,\dots,v_n\}$, there is only one way to express a given vector $u$ as a linear combination of the $v_i$. In other words, the basis uniquely determines the coefficients in $u=\sum_i c_iv_i$.
So, if you move all of the terms to one side of the equation, you get an expansion of the zero vector in terms of the chosen basis of $V$, but there's only one such expansion, for which all of the coefficients are zero.
Frankly, although this part of the argument is valid, I don't really like it. I think that your use of linear independence of the $v_i$ to reach the same conclusion is more direct (and more commonly used). It simply uses the definitions of basis and linear independence instead of relying on some other result that is itself a consequence of those definitions.


text:
Q: Unable to read properties in logback-spring.xml in Springboot I am trying to create logging functionality using logback-spring.xml in my Springboot application,but unable to read the property values(Eg: log.dest.path) in the logback-spring.xml file.
Approach I tried:
I am dynamically loading the property file(YAML) for different environments(dev,stage,prod) based on profiles through @PropertySource.
Profiling is working fine and the right YAML file is loaded (Eg:- application.dev.yml)
logback-spring.xml :
    <configuration debug="true">
  <property name="PROFILE" value="-${spring.profiles.active}" />
  <timestamp key="timestamp" datePattern="yyyy-MM-dd" />
 <springProperty scope="context" name="destination"
        source="log.dest.path" />
    <springProperty name="fileName" scope="context"
        source="spring.application.name" />
    <springProfile name="dev">
        <appender name="FILE" class="ch.qos.logback.core.FileAppender">
            <file>${destination}/log${PROFILE}/${fileName}_${PROFILE}-${timestamp}.log</file>
            <encoder>
                <pattern>%date %level [%thread] %logger{10} [%file : %line] %msg%n</pattern>
            </encoder>
        </appender>
    </springProfile>
    <springProfile name="production">
        <appender name="FILE" class="ch.qos.logback.core.FileAppender">
            <file>${destination}/log${PROFILE}/${fileName}_${PROFILE}-${timestamp}.log</file>
            <encoder>
                <pattern>%date %level [%thread] %logger{10} [%file : %line] %msg%n</pattern>
            </encoder>
        </appender>
    </springProfile>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%msg%n</pattern>
        </encoder>
    </appender>

    <logger name="com.test" additivity="true">
        <appender-ref ref="FILE" />
    </logger>

    <root level="debug">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>
</configuration>

Config file:
@Configuration
public class Config {

    @Configuration
    @Profile({ "dev", "default" })
    @PropertySource(factory = YamlPropertySourceFactory.class, value = { "classpath:application.dev.yml" })
    static class DevConfig {
    }

    @Configuration
    @Profile("stage")
    @PropertySource(factory = YamlPropertySourceFactory.class, value = { "file:////D://file//config.yml" })
    static class StageConfig {
    }
}

I used the @PropertySource approach to load proeprty files because,property files are  externally placed in one of the environment.
When the application starts the log file is not getting created in the specified path provided in the properties file,instead a  folder with destination_IS_UNDEFINED is created in the project root directory.
But I am getting the environment properties through below code:
@SpringBootApplication
public class ProfileProject extends SpringBootServletInitializer {

    public static void main(String[] args) {
        ConfigurableApplicationContext configurableApplicationContext = new SpringApplicationBuilder(
                ProfileProject.class).sources(ProfileProject.class).run(args);
        ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment();
        System.out.println("Env variables Log Dest path ----> : " + environment.getProperty("log.dest.path"));

    }

}

application.dev.yml: - sample
server:
  port: 7999
app:
  name: DEVELOPMENT
spring:
  application:
    name: ProfileDEV
log:
  dest:
    path: D:\development
logging:
 config: classpath:logback-spring.xml

Approach Worked :
Have all the profile level properties to respective yaml file(Eg:-application.{env}.yml) and have a application.properties file where properties required for logback-spring.xml are placed.
Note:-
SpringBoot- logging , doesn't wait for the @ProperySource to finish configuration. As a result the property file loaded through this approach will not be read by logback-spring.xml but will read application.properties.

A: you can use the scope attribute with context value to access the property from the Environment.
you can also set the defaultValue attribute.
For example:
<springProperty scope="context" name="destination"
                source="log.dest.path" defaultValue="\temp"/>

if logback-spring.xml not loaded add a property in the application.properties file.
logging.config: classpath:./logback-spring.xml


text:
Q: c# methods declaring variables i am making a class in which i have used method .they variables are declared directly in method paramter.why i cant declare int below like string.
class studentinfoget
{
    static void Getstudnetinformation(string firstname, string lastname, string birthday, string address, int cellnumber, int homenumber)

    {
        Console.WriteLine("enter your first name");
        firstname = Console.ReadLine();
        Console.WriteLine("enter your LAST NAME");
        lastname = Console.ReadLine();
        Console.WriteLine("enter your brithday ");
        birthday = Console.ReadLine();
        Console.WriteLine("enter birthday");
        address = Console.ReadLine();
        Console.WriteLine("enter address");
        cellnumber = Console.ReadLine();
        Console.WriteLine("enter adress");

    }

Error for this code is

CS0029  C# Cannot implicitly convert type 'string' to 'int'

A: You can use int.TryParse() to convert the input into an integer.
int.TryParse(Console.ReadLine(), out cellnumber);

However, if the test fails, cellnumber will be 0.
A cell number may not necessarily be an integer though - you could have somebody entering the cell number as "XXX-XXX XXXX", or it may have more than 10 digits, in which case you may exceed the int.MaxValue of 2,147,483,647. Also, the starting digit might be a 0, which would then be stripped out when stored and render the phone number invalid.
In this case I would recommend storing the value as a string as at least then the user-entered format will be preserved.

A: cellnumber is declared as an int but Console.ReadLine returns a string. You need to convert the entered text to a number:
int.TryParse(Console.ReadLine(), out cellnumber);

TryParse is used to handle invalid input - if the user enters Phone or something that isn't a number TryParse won't throw an exception, it will return false but execution will continue.

A: you may use
cellnumber = Int32.Parse(Console.ReadLine());
but you should change cellnumber and homenumber to string variable.


text:
Q: How to add new Pod property in yaml in kubernetes I want to add new pod property in yaml file while creating pod in Kubernetes.
By looking at old properties I did all required changes in the kubernetes source code but I still get below parsing error:
error: error validating "podbox.yml": error validating data: found invalid field newproperty for v1.Pod
Example Pod yaml file :

apiVersion: v1
kind: Pod
metadata:
  name: podbox
  namespace: default
spec:
  containers:
  - image: busybox
    command:
      - sleep
      - "3600"
    imagePullPolicy: IfNotPresent
    name: podbox
    resources:
      requests:
        memory: "64Mi"
        cpu: "250m"
      limits:
        memory: "128Mi"
        cpu: "1"
  restartPolicy: Always
  newproperty: false

`newproperty`

not getting parsed while creating Pod.
Is there any specific changes required?

A: You don't want to add new fields to kind: Pod, because then your Kubernetes code will be on a fork and your config will be non-portable.
If you are planning a contribution to submit to the code Kubernetes code, you should first join the appropriate SIG (sig-node or sig-apps for Pod changes) and get support for your proposed change.  Someone there can point you to example PRs that you can follow to add a field.
If you just need to put some extra information in a Pod that you or your own programs can parse, then use an annotation.
If you want to create a new type in your Kubernetes cluster, use a Custom Resource.

A: Just remove the line
newproperty: false

from your YAML and you should be fine.

A: As far as I know you should be declaring then inside data:
apiVersion: v1
kind: Pod
metadata:
  name: podbox
  namespace: default
data:
  newproperty: false

if you want an enviroment variable to be passed to the docker use this structure:
....
 containers:
  - name: name
    image: some_image
    env:
    - name: SOME_VAR
      value: "Hello from the kubernetes"
....


text:
Q: Не могу установить ссылку Скачал в Visual Studio 2017 Xamarin. Создал проект на Android. И сразу же проблема
Нету Xamarin.Support.V7.App. Посмотрел в ссылках проекта - нету. Посмотрел в нагете. Вот такая картина
Надеюсь чем то поможете


text:
Q: Why am I unable to import an exported array in my script? Getting [ERR_MODULE_NOT_FOUND]: Cannot find module error I have a translations.ts file located at project/src/services/translations.js that exports the following array:
export const supportedLocales = ['en', 'es'];

And I am attempting to import it in generateStrings.mjs file which is located at project/src/scripts/generateStrings.mjs like this:
import { supportedLocales } from '../services/translations';

But I get an error:
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/Users/User/Desktop/Projects/mobile/src/services/translations' imported from /Users/User/Desktop/Projects/mobile/src/scripts/generateStrings.mjs

My IDE couldn't automatically import the array either only in that specific file. I wonder if it is because the file has .mjs extension?

A: mistype, import from translationS, and file named translation.js without S at the end


text:
Q: Google Map not showing the marker title I'm trying to show the title on hovering over the marker. I'm okay if it's open by default too.
I do not want infoWindow.
Here's what I have so far unsuccessfully.
function myMap() {
  var map = new google.maps.Map(document.getElementById("map"), mapOptions);
  var myCenter = new google.maps.LatLng(34.131730, -117.910127);
  var mapCanvas = document.getElementById("map");
  var mapOptions = {
    center: myCenter,
    zoom: 16,
    panControl: false,
    zoomControl: false,
    mapTypeControl: false,
    scaleControl: false,
    streetViewControl: false,
    overviewMapControl: false,
    rotateControl: false
  };
  var map = new google.maps.Map(mapCanvas, mapOptions);
  var image = {
    url: 'images/marker.png',
    scaledSize : new google.maps.Size(60, 60),
  };
  var marker = new google.maps.Marker({
    position:myCenter,
    title: "Hello World!",
    icon: image
  });
  marker.setMap(map);
}

A: function initialize() {

var myLatlng = new google.maps.LatLng(48.89364, 2.33739);

var mapOptions = { zoom: 13, center: myLatlng } var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

var marker = new google.maps.Marker({ position: myLatlng, map: map, title: 'Hello World!' }); }

google.maps.event.addDomListener(window, 'load', initialize); initialize();

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Hello World!'
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
initialize();


text:
Q: Sign up a new user but return http error if username or email already exists I'm trying to learn spring but I have a hard time understanding how to use it.
I currently have a react frontend, a sign up page, that accepts username, password and an email and on submit it creates a post request on route /signup (using fetch).
On the backend side, I have a user model class and a controller that has a method on this route that accepts users and saves them on a PostGreSQL database.
@Controller
@RequestMapping("/")
public class SignUpController {

    @Autowired
    UserRepo repo;

    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    @ResponseBody
    public void signUp(@Valid @RequestBody User user) {
        repo.save(user);
        System.out.println("NEW USER SUBMISSION!!!");
    }
}

So, now I want 2 things:

*

*The username is the table's id. However, if the username or the email is already inside the table, i want to prevent the submission. Not only that, i want to return an http error respose (i guess a 403) with the specific message so that i can update the frontend to give a feedback to the user. So, it would be a different message in case username or/and email already exists.

*After that, i would like to filter the submissions on my needs. For example i would like to restrict username's or password's length or filter them based on a regex. Again, how am i to do that and create a http error response with a specific message that would describe the violation that occurred?
Please, if you are going to post any code from the internet, make sure to explain it.

A: You could add a query in your repository that will try to fetch a User for each parameter.
Optional<User> findByUsername(String username);
Optional<User> findByEmail(String email);

Then, you can program the logic in the case username or email already exists in the database.
@Controller
@RequestMapping("/")
public class SignUpController {

@Autowired
UserRepo repo;

@RequestMapping(value = "/signup", method = RequestMethod.POST)
@ResponseBody
public void signUp(@Valid @RequestBody User user) throws Exception {
    Optional<User> usernameEntry = repo.findByUsername(user.getUsername());
    Optional<User> emailEntry = repo.findByEmail(user.getEmail());
    if(usernameEntry.isPresent()){
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Username already exists!");
    }
    if(emailEntry.isPresent()){
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Email already exists!");
    }
    if(validateInputs(user)){ // filter as you need in this method
        repo.save(user);
        System.out.println("New user submission!");
    }
}

private boolean validateInputs(User user) throws Exception{
    // validations and exceptions as you need here
}

The logic for your exceptions with your filters work the same, throwing the needed exception within the method. That being said, I think it would be easier if you just set the lenght of the input directly in the front end. Also, I don't think you should limit how strong a user wants their password to be, and if you're concerned about the lenght in your storage, encryption algorithms like BCrypt have set lenghts. For further reading about the ResponseStatusException I took for this example, you can read this Baeldung article.


text:
Q: How to match blank characters with regex in bash? I need to match something like "?xml  'this is what I want'?", and get the strings between the single quotes.
I try this:
if [[ '?xml   abc def?' =~ \?xml(.*)\? ]]; then
    echo ok;
    echo "${BASH_REMATCH[1]}";
fi

result:
ok
   abc def

I just want 'abc def'. So I try:
if [[ '?xml    abc def?' =~ \?xml[:blank:]+(.*)\? ]]; then #nothing matched
if [[ '?xml    abc def?' =~ \?xml\[:blank:\]+(.*)\? ]]; then #nothing matched
if [[ '?xml    abc def?' =~ \?xml\s+(.*)\? ]]; then #nothing matched

How do I fix this?Help!

A: You need  to  include [:blank:] inside another bracket (character class).
$ if [[ '?xml   abc def?' =~ \?xml[[:blank:]]+(.*)\? ]]; then     echo ok;     echo "${BASH_REMATCH[1]}"; fi
ok
abc def

A: You can use [[:space:]] to remove all whitespace:
if [[ '?xml   abc def?' =~ \?xml[[:space:]]*(.*)\? ]];
                                ^^^^^^^^^^^^

Note 2 square brackets on both ends of the bracket expression (or POSIX character class). As per the regular-expressions.info:

The POSIX syntax... can only be used inside a bracket expression.
[x-z0-9] is an example of what this tutorial calls a "character class" and what POSIX calls a "bracket expression".

See demo
The [:space:] POSIX character class matches [ \t\r\n\v\f] characters.
See more about POSIX character classes at regular-expressions.info.


text:
Q: Using variables from another page I have two pages, these are called "page1.xaml.cs" and "page2.xaml.cs"
In page1, I have variable like this;
public string var1="hello world";

In page2, I have a button, and whenever I click that button, it should bring "var1" from page1.
I can't use "Frame.Navigate(typeof" function because I need to use that value whenever I need it.
So how can I use that variable from another page?

A: If you want to access a variable defined in a specific page from another page, you should simply define that variable as static.
public static string var1 = "hello world";

Now you can easily access it's content, like this : page1.var1
Variables declared as static are commonly shared across all instances of a class, and this way when you navigate onto the Page2, you will not be required to still hold a reference to the instance of the Page1 that you just navigated from.
And, since it seems your intention for your string variable is for it to have the same content despite the different instantiations that will occur to your Page1 class during your application execution, it would be a completely waste to not mark it as static!


text:
Q: How do I use the Google Closure Compiler to build one file? The question is a little more complicated than the title suggests, so allow me to elaborate. I have a project that is split into two repositories. The both use Google Closure for dependency management and compilation. I need to deliver a compiled version of project A to project B. Project B does advanced optimizations, so project A must be whitespace only. The problem is that I can't find a way to satisfy all my requirements for compiled A, which are:

*

*It must be ordered by dependency

*There can be no goog base code, i.e., var goog=goog||{}...

*Similarly, there can be no goog.provides or goog.requires

*It must be whitespace-only compiled

So far I've tried:

*

*Closurebuilder.py

*

*pros: can be whitespace only

*problem: Has base code; getting duplicate namespace issues

*Compiler.jar

*

*problem: whitespace-only mode keeps goog.provides and requires in

*problem: any optimizations of project A break project B

Has anyone made a similar setup work?

A: I solved it by getting the dependencies from closurebuilder.py and simply concatenating them together, in order, into one file. It gets shipped to a built repo, where B can pick it up via npm, and it gets run through a closure script (that adv. optimizes it and splits it into modules).


text:
Q: String manipulation: calculate the "similarity of a string with its suffixes" For two strings A and B, we define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings "abc" and "abd" is 2, while the similarity of strings "aaa" and "aaab" is 3.
The problem is to give an algorithm to calculate the sum of similarities of a string S with each of it's suffixes. For example, let the string be : ababaa. Then, the suffixes of the string are ababaa, babaa, abaa, baa, aa and a. The similarities of each of these strings with the string ababaa are 6,0,3,0,1,1, respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.

A: You want to consider suffix arrays. The suffix array of a word is the array of the indices of suffixes sorted in lexicographical order. In the linked wikipedia article, the algorithms compute the LCP (longest common prefix) as they compute the suffix array. You can compute this in O(n) using similarities with suffix trees, as shown in this paper.
EXAMPLE: Your string is ababaa, so the suffix array looks like this:
5 | a
4 | aa
2 | abaa
0 | ababaa
3 | baa
1 | babaa

where the number on the left is the index at which the suffix begins. Now it's pretty each to compute prefixes since everything is stored lexicographically.
As a side note, this is closely related to the longest common substring problem. To practice for your next interview, think about ways to solve that efficiently.

A: Read this link about z-algorithm first.
An O(n) solution based on the algorithm from the link implemented on python:
def z_func(s):
    z = [0]*len(s)
    l, r = 0, 0
    for i in range(1,len(s)):
        if i<=r:
            z[i] = min(r-i+1, z[i-l])
        while (i + z[i] < len(s) and s[z[i]] == s[i + z[i]]):
            z[i] += 1
        if z[i]+i-1 > r:
            l, r = i, z[i]+i-1
    return sum(z)+len(s)


text:
Q: How does exactly maven creates effective plugin configuration for the same execution ids? I have the following plugin configuration in my project:
        <plugin>
            <groupId>net.revelc.code</groupId>
            <artifactId>impsort-maven-plugin</artifactId>
            <version>1.4.0</version>
            <configuration>
                <includes>
                    <include>AA</include>
                </includes>
            </configuration>
            <executions>
                <execution>
                    <id>the_same_id</id>
                    <phase>process-test-classes</phase>
                    <goals>
                        <goal>check</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

and the following plugin configuration in my parent pom:
        <plugin>
            <groupId>net.revelc.code</groupId>
            <artifactId>impsort-maven-plugin</artifactId>
            <version>1.5.0</version>
            <configuration>
                <lineEnding>LF</lineEnding>
                <includes>
                    <include>A</include>
                    <include>B</include>
                    <include>C</include>
                </includes>
            </configuration>
            <executions>
                <execution>
                    <id>the_same_id</id>
                    <phase>process-sources</phase>
                    <goals>
                        <goal>sort</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

When I run mvn help:effecive:pom this is the merged configuration of my plugin:
<plugins>
  <plugin>
    <groupId>net.revelc.code</groupId>
    <artifactId>impsort-maven-plugin</artifactId>
    <version>1.4.0</version>
    <executions>
      <execution>
        <id>the_same_id</id>
        <phase>process-test-classes</phase>
        <goals>
          <goal>check</goal>
          <goal>sort</goal>
        </goals>
        <configuration>
          <includes>
            <include>AA</include>
          </includes>
          <lineEnding>LF</lineEnding>
        </configuration>
      </execution>
    </executions>
    <configuration>
      <includes>
        <include>AA</include>
      </includes>
      <lineEnding>LF</lineEnding>
    </configuration>
  </plugin>

According to this the default merging behavior of the plugins configuration:

is to merge the content of the configuration element according to element name.

which is shown in the includes section as it only contains the ones from the project pom and not from the parent pom. However following that logic I don't understand why the effective-pom configuration contains two goals rather than only the one from the project configuration.

A: EDIT: It is properly documented in POM reference, plugins section. Thanks Karl  for pointing this out!
In the codebase responsible for merging it is slightly different for each of the properties.
If your goals are not excluded, then these will be merged together.
Also, your configuration may be merged differently, given the plugin's lifecycle configuration too.


text:
Q: Initialize several objects at once I have a Type called Mark, and a 4 variables initialized to null. They are declared as:
var markA: Mark = _
var markB: Mark = _
var markC: Mark = _
var markD: Mark = _

Currently, I am initializing them in a method:
markA = new Mark()
markB = new Mark()
markC = new Mark()
markD = new Mark()

What's the right way to initialize them all without writing "= new Mark()" repeatedly?  I was trying to do something like the following inside a method
List(markA,markB,marcC,mardD).foreach(_ = new Mark())

But the compiler warns me that this is a reassignment to a val, which makes sense. How can I initialize them all at once?

A: var markA, markB, markC, MarkD = new Mark()

Will assign to each one a new instance of Mark.
E.g. with mutable.Map
scala> var a,b,c = collection.mutable.Map("a"->1)
a: scala.collection.mutable.Map[String,Int] = Map(a -> 1)
b: scala.collection.mutable.Map[String,Int] = Map(a -> 1)
c: scala.collection.mutable.Map[String,Int] = Map(a -> 1)

scala> a += ("b"->1)
res1: scala.collection.mutable.Map[String,Int] = Map(b -> 1, a -> 1)

scala> a
res2: scala.collection.mutable.Map[String,Int] = Map(b -> 1, a -> 1)

scala> b
res3: scala.collection.mutable.Map[String,Int] = Map(a -> 1)

scala> c
res4: scala.collection.mutable.Map[String,Int] = Map(a -> 1)

A: If it is acceptable for storing the variables in a List/Array, you can seperate declaration and initialization into 2 stages:
declare:
var marks = Array.fill[Mark](4)(null)

initialize:
marks = marks map (x => new Mark)


text:
Q: Writing custom rules related to Java variable declaration I am working on solution for Avoid assigning several variables to the same value in a single statement. any java class containing variable declared like below program should display error. I am going through sonar cube custom rules. Please help me if there is any other way to achieve this
String a,b,c="test";

A: S1659 "Multiple variables should not be declared on the same line" should do what you want, although it will raise an issue whether or not a value is assigned at declaration.


text:
Q: How to find coefficients in partial fraction? I have the expression
$$\frac{P(s)}{Q(s)}=\left(a_0~\sum\limits_{i=1}^n\frac{c_i}{s+\alpha_i}+1-a_0\right)\frac{B_1(s)}{\prod\limits_{i=1}^m s-\beta_i}$$ where $\alpha_i\neq\beta_i$ are all distinct roots and $deg(B_1(s))<m$. Using partial fraction method, I write
$$\frac{P(s)}{Q(s)}=\sum\limits_{i=1}^n\frac{D_i}{s+\alpha_i}+\sum\limits_{i=1}^m\frac{E_i}{s-\beta_i}$$ where $D_i=\frac{P(s)}{Q(s)'}|_{s=-\alpha_i}$ and $E_i=\frac{P(s)}{Q(s)'}|_{s=\beta_i}$ .
Simplifying the expression, I got $$D_k=\frac{a_0~c_k~B_1(-\alpha_k)}{\prod\limits_{j=1}^m(-\alpha_k-\beta_j)}$$ and
$$E_k=\frac{\left(a_0~\sum\limits_{i=1}^n c_i\prod\limits_{j=1,j\neq i}^n(\beta_k+\alpha_j)+(1-a_0)\prod\limits_{j=1}^n \beta_k+\alpha_j\right)B_1(\beta_k)}{\prod\limits_{j=1}^n(\alpha_j+\beta_k)\prod\limits_{j=1,j\neq k}^m(\beta_k-\beta_j)}$$
Can any one please check the correctness of the coefficients and suggest some alternatives?


text:
Q: Get the last subscription renewal order information in Woocommerce 3 We are trying to pass woocommerce subscription renewal data to a loyalty rewards program and are having all kinds of issues and have been unable to get relevant woocommerce subscription information or anything to work. Our full loyalty code for zinrelo works with manual data.
FUll code with your suggestions runs in functions file
add_action( 'woocommerce_subscription_renewal_payment_complete', 'custom_add_subscription_points', 10, 1 );
  function custom_add_subscription_points( $subscription ) {
    if ( ! $subscription )
        return;

    // Get related orders
    $orders_ids = $subscription->get_related_orders();

    // Get the last renewal related Order ID
    $order_id = reset( $order_ids );

    $order = wc_get_order($order_id);
    $order_id = $order->get_id();
    $order_email = $order->get_billing_email();
    $order_date = $order->get_date_completed();
    $order_total = $order->get_total();
    $order_subtotal = $order->get_subtotal();

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "https://api.zinrelo.com/v1/loyalty/purchase");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "user_email={$order_email}&activity_id=made_a_purchase&order_{id=$order_id}&total={$order_total}&subtotal={$order_subtotal}");
    curl_setopt($ch, CURLOPT_POST, 1);

    $headers = array();
    $headers[] = "Partner-Id: 000000";
    $headers[] = "Api-Key: 000000";
    $headers[] = "Content-Type: application/x-www-form-urlencoded";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);
}

A: As WC_Subscription get_related_orders() method gives an array of order IDs, you need to use reset() function, to get the last renewal order ID and avoid an error with wc_get_order() funtion that expect a unique order ID as argument (but not an array).
So try:
add_action( 'woocommerce_subscription_renewal_payment_complete', 'custom_add_subscription_points', 10, 1 );
function custom_add_subscription_points( $subscription, $last_order ) {
    if ( ! $subscription )
        return;

    $order_email    = $last_order->get_billing_email();
    $order_date     = $last_order->get_date_completed();
    $order_total    = $last_order->get_total();
    $order_subtotal = $last_order->get_subtotal();
}

It should work now with:
curl_setopt($ch, CURLOPT_POSTFIELDS, "user_email={$order_email}&activity_id=made_a_purchase&order_{id=$order_id}&total={$order_total}&subtotal={$order_subtotal}");


text:
Q: Save GeoDataFrame to .jpg file I have a GeoPandas DataFrame (loaded from a shapefile) containing a number of polygons which looks like this:
                                            geometry  raster_val
0  POLYGON ((8.56799 47.80800, 8.56799 47.77200, ...         1.0
1  POLYGON ((6.73199 47.12400, 6.73199 47.08800, ...         1.0
2  POLYGON ((10.36799 47.01600, 10.36799 46.98000...         1.0
3  POLYGON ((8.60399 46.51200, 8.60399 46.47600, ...         1.0

Is there any elegant way to print/plot those polygons into a .jpg file?

A: Taking a look at the geopandas mapping documentation, it seems that you can plot a GeoDataFrame by calling the plot() method on it. Here is one example from the documentation:
import geopandas
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
world.plot()

To export the plot as a .jpg file, you can simply use the matplotlib.pyplot.savefig() function. The code would be similar to:
import matplotlib.pyplot as plt
plt.savefig('world.jpg')

You can, of course, modify the plot by passing several arguments to the plot() method.


text:
Q: Convert Equivalent Rails ORM command for SQL Query I have a SQL query to be converted to Rails ORM (ActiveRecord)
SELECT * FROM txactions
  INNER JOIN accounts
  WHERE accounts.item_accountId = 15845388
    AND accounts.id = txactions.account_id

A: You can try this
Txaction.joins("INNER JOIN accounts ON accounts.id = txactions.account_id").where("accounts.item_accountId = ?", 15845388)

OR
Txaction.joins(:accounts).where("accounts.item_accountId = ?", 15845388)


text:
Q: $X$ is complete iff $\sum_{n=1}^\infty \|x_n\| < \infty \implies \sum_{n=1}^\infty x_n$ converges (Carothers, Theorem $7.12$) I have some questions to ask about the second part of the proof, i.e. $[\Leftarrow]$ direction:

*

*The author says, "As always, it is enough to find a subsequence of $(x_n)$ that converges". What do they mean by "As always"? Where else is this technique employed and why is it so obvious? Suppose I do find a subsequence $(x_{n_k})$ that converges. That does not imply that $(x_n)$ converges as well. $\color{blue}{\text{(Resolved).}}$

*The author asks us to choose a subsequence $(x_{n_k})$ such that $$\|x_{n_{k+1}} - x_{n_k}\|< 2^{-k}, \text{ for all }k$$
What allows us to do this? Given a Cauchy sequence $(x_n)$, I know that $$\forall \epsilon > 0 \exists N\in\Bbb N \forall m,n\ge N (\|x_m-x_n\| < \epsilon)$$
I could put $\epsilon = 2^{-k}$ and find the corresponding $N$, but that doesn't give me a subsequence! $\color{blue}{\text{(Resolved).}}$
Attached is the proof for reference:

Thanks a lot!

A: By taking $\epsilon = 2^{-k}$ as you suggest, you find that for every $k$, there exists $N_k$ such that for all $n,m \ge N_k$ we have $\|x_n - x_m\| < 2^{-k}$.
Taking $x_{N_k}$ as your subsequence almost works, except that the $N_k$ are not necessarily increasing so it may not actually be a subsequence.  To fix this, we can use Korone's idea of "making sure the next index is larger than both the previous index and the threshold!" Define $n_k$ recursively by $n_0 = N_0$, $n_{k+1} = \max(N_{k+1}, 1+n_{k})$.  Then you can check that the desired property holds for the subsequence $x_{n_k}$, since $n_{k+1} \ge n_k \ge N_k$.


text:
Q: How to create slanted Images with CSS? What I am going for ?

We have 4 column, that needs to appear with certain degree of Slant on the background Images.
What I have tried ?
Using CSS Property clip-path, I am able to create layout presented on the Image. However, the width is not full-screen.
HTML

CSS
.ktk-slanted-column__item {
    position: relative;
    -webkit-box-flex: 0;
    height: 540px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.ktk-slanted-column__item::after {
    content: '';
    background: #0079C1;
    position: absolute;
    height: 100%;
    width: 100%;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    opacity: 0;
    transition: opacity 0.4s ease-in-out 0s;
}

.ktk-slanted-column__item:hover::after {
    opacity: 0.66;
}

.ktk-slanted-column__item {
    width: 25%;
}

#ktk-slant-col-2 {
    left: -95px;
}

#ktk-slant-col-3 {
    left: -190px;
}

#ktk-slant-col-4 {
    left: -284px;
}

And the result is :

A: I have found an article about the slanted images and here you go :
Flexible Captioned Slanted Images
.ktk-slanted-column__item {
    position: relative;
    -webkit-box-flex: 0;
    height: 540px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    width: 31.5%;
    margin-right: -8.5%;
}

.ktk-slanted-column__item::after {
    content: '';
    background: #0079C1;
    position: absolute;
    height: 100%;
    width: 100%;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    opacity: 0;
    transition: opacity 0.4s ease-in-out 0s;
}

.ktk-slanted-column__item:hover::after {
    opacity: 0.66;
}

In Codepen https://codepen.io/crisnaxtha/pen/OJgwawB


text:
Q: How To Align Text And Images Within A H3 Element I would like to align an image and the text that appears alongside it. Currently the image is where I would like it, in the middle, however the text "Back To Top" appears much lower down than the image. Ideally I would like the text to be moved up and become aligned with the image. I have tried wrapping the two elements in separate divs and a classes but nothing seems to work.
I have included the code below:

©  2015 - 2016 Blankesque . All rights reserved . Policies

Back To Top

My blog URL is as follows : http://www.blankesque.com

A: There are several approaches you can take.
If you don't need to support IE8/IE9, you can use flexbox, and give the .backtotop class CSS rules of display: flex and align-content: center and they should align up.
You can also put the link text in a  tag and give that span tag CSS properties of display: inline-block and vertical-align:top.


text:
Q: Ruby replace if block with guard I've got a service object which creates the CSV file from assigned data. The call method is pretty simple:
  def initialize(data)
    @data = data
  end

  def call
    CSV.generate(headers: true, col_sep: ';') do |csv|
      csv << csv_headers

      data.uniq.each do |contract|
        next if contract.transient

        payment_details = [
          next_payment_date(contract),
          I18n.t("contracts.interval_options.#{contract.recurring_transaction_interval&.name}"),
        ]
        csv << payment_details
      end
    end
  end

  private

  def next_payment_date(contract)
    if contract.upcoming_installment.nil?
      I18n.t('tables.headers.no_next_payment_date')
    else
      contract.upcoming_installment.transaction_date.to_s
    end
  end

It works well but I don't think next_payment_date is really fancy if block, I'm wondering is it possible to replace it with some guard instead?
Because of rubocop I cannot use:
contract.upcoming_installment.nil? ? I18n.t('tables.headers.no_next_payment_date') : contract.upcoming_installment.transaction_date.to_s

A: In my opinion, the method looks fine as it is. Having better readability is a profitable trade-off for increasing LOCs or introducing methods. That said, there are ways where you can make it an one liner if you really fancy.
contract.upcoming_installment&.transaction_date || I18n.t('tables.headers.no_next_payment_date')

Ruby's safe navigation &. will return nil if upcoming_installment is nil which should fallback to the I18n.


text:
Q: Only run program if input is single letter I've been working on a java project for me class, and I am almost done. the program is a hangman game, where the user inputs a letter, and the program continues depending whether the letter is in the word or not. The issue I am having is that I cannot figure out how to make it so when the user enters more than one letter, a number or a symbol, the program prints out a statement that says "Invalid input, try again" and has the user input something again, instead of showing it to be a missed try or the " letter" not being in the word. Here is my code:
import java.util.Scanner;
import java.util.Random;
import java.io.*;

public class Hangman {

    private Scanner in = new Scanner(System.in);
    private boardPiece[] board = {new boardPiece(0),new boardPiece(0),new boardPiece(3),
            new boardPiece(1),new boardPiece(2),new boardPiece(0)};
    private String puzzle;
    private String puzzleWord;
    private int puzzleIndex;
    private Random generator = new Random(System.currentTimeMillis());
    private boolean win;
    private boolean over;
    private String correct = "";
    private char guesses[] = new char[26];
    private int guessed;
    private int misses;
    private String puzzles[] = new String[5];

    public static void main(String [] args){

        String letter;
        String again = "y";

        Hangman game = new Hangman();

        try{
            BufferedReader in =
                new BufferedReader(new FileReader("puzzles.txt"));

            int count = 0;
            while (in.ready()) { //while there is another line in the input file
                game.puzzles[count] = in.readLine(); //get line of data
                count++; //Increment CWID counter
            }
            in.close();
        }
        catch(IOException e){
            System.out.println("Error during reading/writing");
        }

        System.out.println("Welcome to HangMan!");
        System.out.println("To play, guess a letter to try to guess the word.");
        System.out.println("Every time you choose an incorrect letter another");
        System.out.println("body part appears on the gallows. If you guess the");
        System.out.println("word before you're hung, you win");
        System.out.println("If you get hung, you lose");
        System.out.println();
        System.out.println("Time to guess...");

        while(again.charAt(0) == 'y'){
            game.displayGallows();

            while(!game.over){
                game.printBoard();
                game.printLettersGuessed();
                System.out.println("The word so far: " + game.puzzle);
                System.out.println("Choose a letter: ");
                letter = game.in.next();

                game.guesses[game.guessed] = letter.charAt(0);
                game.guessed++;
                game.sort();

                if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
                    game.correct = game.correct + letter.charAt(0);
                    game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
                    if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
                        game.win = true;
                        game.over = true;
                    }

                }
                else
                    game.PrintWrongGuesses();
            }
            game.printBoard();
            System.out.println("Solution: " + game.puzzleWord);
            if(game.win)
                System.out.println("Congratulations! You've solved the puzzle!");
            else
                System.out.println("You failed, failer!");

            System.out.println();
            System.out.println("Congratulations, you win!");
            System.out.println("Do you want to play again? (y/n)");
            again = game.in.next();
        }
        System.out.println("Goodbye!");
    }

    public void displayGallows(){

        win = false;
        over = false;

        board[0].piece = "    ______ ";
        board[1].piece = "    |    | ";
        board[2].piece = "         | ";
        board[3].piece = "         | ";
        board[4].piece = "         | ";
        board[5].piece = "  _______| ";

        puzzleIndex = generator.nextInt(puzzles.length);
        puzzleWord = puzzles[puzzleIndex];

        puzzle = puzzleWord.replaceAll("[A-Za-z]","-");
        correct = "";
        for(int x=0;x<26;x++)
            guesses[x] = '~';
        guessed = 0;
        misses = 0;
    }

    public void printBoard(){
        for(int x =0;x<6;x++)
            System.out.println(board[x].piece);
    }

    public void PrintWrongGuesses(){
        misses++;
        System.out.println();
        if(misses == 1){
            board[2].piece = "    0    | ";
            System.out.println("Number of misses: " + misses);
        }
        else if(misses == 2){
            board[2].piece = "   \\0    | ";
            System.out.println("Number of misses: " + misses);
        }
        else if(misses == 3){
            board[2].piece = "   \\0/   | ";
            System.out.println("Number of misses: " + misses);
        }
        else if(misses == 4){
            board[3].piece = "    |    | ";
            System.out.println("Number of misses: " + misses);
        }
        else if(misses == 5){
            board[4].piece = "   /     | ";
            System.out.println("Number of misses: " + misses);
        }
        else if(misses == 6){
            board[4].piece = "   / \\   | ";
            System.out.println("Number of misses: " + misses);
            over = true;
        }

    }

    public void printLettersGuessed(){
        System.out.print("Letters guessed already: ");
        for(int x=0;x<26;x++){
            if(guesses[x] != '~')
                System.out.print(guesses[x] + " ");
        }
        System.out.println();
    }

    public void sort(){
        boolean doMore = true;
        while (doMore) {
            doMore = false;  // assume this is last pass over array
            for (int i=0; i<guesses.length-1; i++) {
                if (guesses[i] > guesses[i+1]) {
                    char temp = guesses[i];
                    guesses[i] = guesses[i+1];
                    guesses[i+1] = temp;
                    doMore = true;  // after an exchange, must look again
                }
            }
        }
    }

    class boardPiece{
        public String piece;
        public int total;
        public int used;

        boardPiece(int x){
            used = 0;
            total = x;
        }
    }
}

A:         System.out.println("Choose a letter: ");
        letter = game.in.next();

        if(letter.length() == 1)
        {
            game.guesses[game.guessed] = letter.charAt(0);
            game.guessed++;
            game.sort();

            if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
                game.correct = game.correct + letter.charAt(0);
                game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
                if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
                    game.win = true;
                    game.over = true;
                }

            }
            else
                game.PrintWrongGuesses();
        }else
        {
            System.out.println("Invalid input, try again");
        }

A: You can use a regular expression to check the input.
if (!letter.matches("[a-zA-Z]{1}")) {
     System.out.println("Invalid Input") {
else {
    <your other code>
}

A: Try this,
import java.util.Scanner;
import java.util.Random;
import java.io.*;

public class Hangman {

    private Scanner in = new Scanner(System.in);
    private boardPiece[] board = {new boardPiece(0),new boardPiece(0),new boardPiece(3),
            new boardPiece(1),new boardPiece(2),new boardPiece(0)};
    private String puzzle;
    private String puzzleWord;
    private int puzzleIndex;
    private Random generator = new Random(System.currentTimeMillis());
    private boolean win;
    private boolean over;
    private String correct = "";
    private char guesses[] = new char[26];
    private int guessed;
    private int misses;
    private String puzzles[] = new String[5];

    public static void main(String [] args){

        String letter;
        String again = "y";

        Hangman game = new Hangman();

        try{
            BufferedReader in =
                new BufferedReader(new FileReader("puzzles.txt"));

            int count = 0;
            while (in.ready()) { //while there is another line in the input file
                String input = in.readLine();
                if(input.length() == 1){
                   game.puzzles[count] = ; //get line of data
                   count++; //Increment CWID counter
                }
                else{
                System.out.println("INVALID INPUT");
                }
            }
            in.close();
        }
        catch(IOException e){
            System.out.println("Error during reading/writing");
        }

        System.out.println("Welcome to HangMan!");
        System.out.println("To play, guess a letter to try to guess the word.");
        System.out.println("Every time you choose an incorrect letter another");
        System.out.println("body part appears on the gallows. If you guess the");
        System.out.println("word before you're hung, you win");
        System.out.println("If you get hung, you lose");
        System.out.println();
        System.out.println("Time to guess...");

        while(again.charAt(0) == 'y'){
            game.displayGallows();

            while(!game.over){
                game.printBoard();
                game.printLettersGuessed();
                System.out.println("The word so far: " + game.puzzle);
                System.out.println("Choose a letter: ");
                letter = game.in.next();

                game.guesses[game.guessed] = letter.charAt(0);
                game.guessed++;
                game.sort();

                if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
                    game.correct = game.correct + letter.charAt(0);
                    game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
                    if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
                        game.win = true;
                        game.over = true;
                    }

                }
                else
                    game.PrintWrongGuesses();
            }
            game.printBoard();
            System.out.println("Solution: " + game.puzzleWord);
            if(game.win)
                System.out.println("Congratulations! You've solved the puzzle!");
            else
                System.out.println("You failed, failer!");

            System.out.println();
            System.out.println("Congratulations, you win!");
            System.out.println("Do you want to play again? (y/n)");
            again = game.in.next();
        }
        System.out.println("Goodbye!");
    }

    public void displayGallows(){

        win = false;
        over = false;

        board[0].piece = "    ______ ";
        board[1].piece = "    |    | ";
        board[2].piece = "         | ";
        board[3].piece = "         | ";
        board[4].piece = "         | ";
        board[5].piece = "  _______| ";

        puzzleIndex = generator.nextInt(puzzles.length);
        puzzleWord = puzzles[puzzleIndex];

        puzzle = puzzleWord.replaceAll("[A-Za-z]","-");
        correct = "";
        for(int x=0;x<26;x++)
            guesses[x] = '~';
        guessed = 0;
        misses = 0;
    }

    public void printBoard(){
        for(int x =0;x<6;x++)
            System.out.println(board[x].piece);
    }

    public void PrintWrongGuesses(){
        misses++;
        System.out.println();
        if(misses == 1){
            board[2].piece = "    0    | ";
            System.out.println("Number of misses: " + misses);
        }
        else if(misses == 2){
            board[2].piece = "   \\0    | ";
            System.out.println("Number of misses: " + misses);
        }
        else if(misses == 3){
            board[2].piece = "   \\0/   | ";
            System.out.println("Number of misses: " + misses);
        }
        else if(misses == 4){
            board[3].piece = "    |    | ";
            System.out.println("Number of misses: " + misses);
        }
        else if(misses == 5){
            board[4].piece = "   /     | ";
            System.out.println("Number of misses: " + misses);
        }
        else if(misses == 6){
            board[4].piece = "   / \\   | ";
            System.out.println("Number of misses: " + misses);
            over = true;
        }

    }

    public void printLettersGuessed(){
        System.out.print("Letters guessed already: ");
        for(int x=0;x<26;x++){
            if(guesses[x] != '~')
                System.out.print(guesses[x] + " ");
        }
        System.out.println();
    }

    public void sort(){
        boolean doMore = true;
        while (doMore) {
            doMore = false;  // assume this is last pass over array
            for (int i=0; i<guesses.length-1; i++) {
                if (guesses[i] > guesses[i+1]) {
                    char temp = guesses[i];
                    guesses[i] = guesses[i+1];
                    guesses[i+1] = temp;
                    doMore = true;  // after an exchange, must look again
                }
            }
        }
    }

    class boardPiece{
        public String piece;
        public int total;
        public int used;

        boardPiece(int x){
            used = 0;
            total = x;
        }
    }
}

A: You can use String.length() for checking the length of the input, e.g. in your case
if(letter.length() != 1) {
     // do something to handle error
}

A: String.length() can be used to determine, if the input has one letter. To check if the read String is a letter you can use Character.isLetter(char):
    try{
        BufferedReader in =
            new BufferedReader(new FileReader("puzzles.txt"));

        int count = 0;
        String line = null;
        while (in.ready()) { //while there is another line in the input file
            line = in.readLine();

            if (line.length() == 1 && Character.isLetter(line.charAt(0)) {
                game.puzzles[count] = line; //get line of data
                count++; //Increment CWID counter
            } else {
                // handle the else-case
            }

        }
        in.close();
    }
    catch(IOException e){
        System.out.println("Error during reading/writing");
    }


text:
Q: Set Responsive Width For Linkedin Company Profile plugin I want to use LinkedIn Company Profile plugin in my responsive website. I have added the data-width="300" for desktop view, now I want to set some different width value for tablet and mobile devices.
Can anyone help me on how can I set different values in data-width for different views.

A: Here is an example of what you can do :

        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>test</title>

Also don't forget to use:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

in your page so that the content is scaled appropriately on devices with high pitch.
I've choosen this solution because it's quick to set up and easy to understand. To my mind it should be also possible to do it with a javascript that would initialize data-with but it is a bit more tricky.


text:
Q: Bash - send all output to a log file, BUT show errors Is it possible within a bash script, to make all output, except the output i specifically output with echo, go to a log file, BUT if there's errors in the output it should show in the terminal (and the log file also ofcourse)?

A: Here is what you can do by using an additional file descriptor:
#!/bin/bash

# open fd=3 redirecting to 1 (stdout)
exec 3>&1

# redirect stdout/stderr to a file but show stderr on terminal
exec >file.log 2> >(tee >(cat >&3))

# function echo to show echo output on terminal
echo() {
   # call actual echo command and redirect output to fd=3
   command echo "$@" >&3
}

# script starts here
echo "show me"
printf "=====================\n"
printf "%s\n" "hide me"
ls foo-foo
date
tty
echo "end of run"

# close fd=3
exec 3>&-

After you run your script it will display following on terminal:
show me
ls: cannot access 'foo-foo': No such file or directory
end of run

If you do cat file.log then it shows:
=====================
hide me
ls: cannot access 'foo-foo': No such file or directory
Fri Dec  2 14:20:47 EST 2016
/dev/ttys002

*

*On terminal we're only getting output of echo command and all the errors.

*In the log file we're getting error and remaining output from script.

A: UNIX terminals usually provide two output file decriptors, stdout and stderr, both of which go to the terminal by default.
Well behaved programs send their "standard" output to stdout, and errors to stderr. So for example echo writes to stdout. grep writes matching lines to stdout, but if something goes wrong, for example a file can't be read, the error goes to stderr.
You can redirect these with > (for stdout) and 2> (for stderr). So:
 myscript >log 2>errors

Writes output to log and errors to errors.
So part of your requirement can be met simply with:
 command >log

... errors will continue to go to the terminal, via stdout.
Your extra requirement is "except the output i specifically output with echo".
It might be enough for you that your echos go to stderr:
 echo "Processing next part" >&2

The >&2 redirects stdout from this command to stderr. This is the standard way of outputting errors (and sometimes informational output) in shell scripts.
If you need more than this, you might want to do something more complicated with more file descriptors. Try: https://unix.stackexchange.com/questions/18899/when-would-you-use-an-additional-file-descriptor
Well behaved UNIX programs tend to avoid doing complicated things with extra file descriptors. The convention is to restrict yourself to stdout and stderr, with any further outputs being specified as filenames in the command line parameters.


text:
Q: About redefining a name of Java method with a typo for simplicity sake I type fast and usually make a lot of typos that I have to fix constantly while printing. For instance, if I work with method getCompany(), I often write it as getComapny() that irritates me greatly. Is it considered to be a good practice to wrap getCompany() method into getComapny() not to bother about this typo anymore? Like having
public Company getCompany(){
  Company company = new Company();
  //do some really important stuff in here
  return company;
}

and to wrap it with
public Company getComapny(){
  return getCompany();
}

I think my fellow colleagues who will support the code after me wil be thankful, they have the same problems as far as I aware.
BTW, how to conceal getComapny() from JavaDoc to display getCompany() only?

A: I'm really hoping that this post is a joke.  I pity the poor person who would have to maintain that code in the future.  How many misspellings do you want to support?
public Company getComapny(){
public Company getCmopany(){
public Company getCompayn(){
public Company getCoampny(){
public Company getCimpany(){
public Company getCimapny(){
public Company getCimapyn(){

Especially when any decent IDE has things like CTRL-SPACE autocomplete for method names.  Which would be faster than actually typing the method name yourself.  Please tell me this is a joke.  I think my brain is melting.

A: Typing fast with a lot of typos isn't typing fast at all, it is typing slowly. Very slowly, taking into account the correction cycle.
Slow down and speed yourself up.
And don't build your own personal bugs into the application. Take them out.

A: Would it be good to add misspellings to your dictionary in MSOffice so you don't see so many red lines.
Other people should be able to read what you said anyway.
Bad bad idea.

A:
Is it considered to be a good practice
  to wrap getCompany() method into
  getComapny() not to bother about this
  typo anymore?

I don't think you could do worse than this. Take a look at Logback news. New version breaks compatibility with previous verions because of one measly misspelled letter (version pre 0.9.28 had "bithTime" instead of "birthTime"). You should do the same yourself. Rename every instance of your misspelled method to a proper one and force your users to use the new version.
Wrapping an existing problem will only make it worse in the long run, maintenance wise.
By the way: invest more time in proper typing. You can be the fastest typer in the world, but if you're making mistakes in every sentence, your speed won't do you much good.

A: You suggest taking a mistake (the typo) and rather than eliminate it, allow it to propagate instead. Code that is not rejected by the compiler tends to be copy/pasted, used as an example and so on. After a while, the typos will be all over the place, regardless if they exist in the "official" documentation.
Not to mention any newcomers that will be confused about the "proper" names that should be used. There are quite a few people out there that have had to settle with mispelled identifiers that has sneaked in legacy code - these people would not see anything extremely strange in using a mispelled name routinely.
In short: unless you already have tons of legacy code that cannot be reasonably converted, you should not allow typos to propagate, let alone introduce them as a matter of course.

A: Dont do the type-o. That is just annoying.
Maybe you should call the method createCompany(), or buildCompany(), or some other builder/factory (depending on what is done in the commented out section) standard.
As for concealing it, the only way I know of is to make the method private.

A: Wrap the code like you explained above, mark the getComapny method as deprecated, and remove it as soon as possible.
Unless your code is externally published and needs to retain compatibility, go through a signature correction on all your code, wich is plainless with pretty much any IDE. Guess you'll be happier then.
But still, a typo may look bad, but it will only bother the coders if the code itself is nice. If you are talking about spaghetti code, nobody will care about a typo.


text:
Q: Can I create several levels of nested objects? Working on a project where I need to create an object containing several data sets that each have their own subsequent data sets. Not sure if this is excessive but I need to be able to accomplish something along these lines.
Here's an example of what I mean, this doesn't work but it should give an idea:
var menu = {
    "appetizers": {
        soup: {
            num1: "beef",
            num2: "chicken",
            num3: "vegetarian": {
                v1: "soy",
                v2: "tomato",
            };
        },
        "salad": {
            sal1: "apple",
            sal2: "egg",
        }
    }
};

A: Yes, look at the object below. You can do something like that.
Only remember that objects are key value pairs and so for that it has to be in the form of:
{key1:value1,
 key2:{valueKey: valueValue}
}

Hence the following works:

var menu = {
"appetizers": {
    "soup": {
        "num1": "beef",
        "num2": "chicken",
        "num3": "vegetarian",
        "num4": {
            "v1": "soy",
            "v2": "tomato",
        }
    },

    "salad": {
        "sal1": "apple",
        "sal2": "egg",
    }

}

};

console.log(menu);


text:
Q: Excel Function running with Blank cells I have this Function in excel
=(IF(AND(E6>=8.91,E6<=9.09),"Pass","Fail"))

This code works perfectly. However, I do not wish for "Fail" to show up when no data is entered in my E6 column.
Any help is appreciated

A: Here is a simple way :
=IF(E6="","",IF(AND(E6>=8.91,E6<=9.09),"Pass","Fail"))


text:
Q: Correct way to get single (first) value from functions that returns a tuple What is the Pythonic way to get a single (the first) value from a function that returns a tuple?
I have come up with two solutions that work
Byte=unpack_from('B',Inbuff,42)[0]

VS
Byte,=unpack_from('B',Inbuff,42)

Personally I prefer the first because it will not break if the return tuple has more than one value (Not going to happen here but possible in a more generic case)

A: For Python 3.x I would favour a third:
byte, *_ = unpack_from('B',Inbuff,42)

This stores the rest of the tuple in the variable _, which is the most commonly used value for a throwaway variable.
The second seems odd to me. It seems unlikely that the function would only ever return tuples with only one element. The first has the advantage that it is more readable to people who are unused to Python and features specific to it such as iterable unpacking.
For Python 2.x, I think that the first is better. "Readability counts", and it is more robust.

A: If you specifically want the first value (it seems that you do, but your question just said "a single value" rather than "the first value"), your first method is better. The second one is more like a Python party trick (and will, as sweeneyrod pointed out, will break if it receives a tuple longer than one element).


text:
Q: Export dynamic metadata using x265 I am working on ffmpeg and x265 for video encoding. From the release note of x265:

HDR10+ supported. Dynamic metadata may be either supplied as a bitstream via the userSEI field of x265_picture, or as a json jile that can be parsed by x265 and inserted into the bitstream; use --dhdr10-info to specify json file name, and --dhdr10-opt to enable optimization of inserting tone-map information only at IDR frames, or when the tone map information changes.

But I dont know how to export the dynamic metadata from a video sequence as a userSEI or json file. Hope to get solution from you.


text:
Q: Return string from catch System.Net.Sockets.SocketException I have a button that should convert a list of hostnames to the matching IP addresses in a textbox. How can I just return string "No host is known" for the hostname that is really not known to the textbox?
I use try-catch block in which I catch System.Net.Sockets.SocketException. But as far that I know, catch block cannot return any string value. So, I usually catch the exception by output a messagebox. But this time, I just want it to display a string in the specified textbox. This is the code that I've tried:-
private void btnConvertHosttoIP_Click(object sender, Eventrgs e)
{
    try
    {
        string ips = null;
        List<string> ipList = new List<string>();
        string[] hostList = Regex.Split(txtHost.Text, "\r\n");
        foreach (var h in hostList)
        {
            // Check DNS
            if (h.Contains(".xxxx.com"))
            {
                hostName = h;
            }
            else
            {
                string code = txtHost.Text.Substring(0, 3);
                if (code == "ABC" || code == "CDE")
                    hostName = h + ".ap.xxx.com";
                else
                    hostName = "Unknown domain name";
            }

            IPHostEntry host = Dns.GetHostEntry(hostName);
            IPAddress[] ipaddr = host.AddressList;

            // Loop through the IP Address array and add the IP address to Listbox
            foreach (IPAddress addr in ipaddr)
            {
                if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    ipList.Add(addr.ToString());
                }
            }
        }
        foreach (var ip in ipList)
        {
            ips += ip + Environment.NewLine;
        }
        txtIP.Text = ips;
    }
    catch (System.Net.Sockets.SocketException ex)
    {
        MessageBox.Show(ex.Message);
    }
}

I want the unknown host to be displayed in the textbox only not as an exception. Is it possible or any other suggestions?

A: You can modify your code as below.
try
{
    string ips = null;
    List<string> ipList = new List<string>();
    string[] hostList = Regex.Split(txtHost.Text, "\r\n");
    foreach (var h in hostList)
    {
        // Check DNS
        if (h.Contains(".xxxx.com"))
        {
            hostName = h;
        }
        else
        {
            string code = txtHost.Text.Substring(0, 3);
            if (code == "ABC" || code == "CDE")
                hostName = h + ".ap.xxx.com";
            else
                hostName = "Unknown domain name";
        }
        try
       {
        IPHostEntry host = Dns.GetHostEntry(hostName);
        IPAddress[] ipaddr = host.AddressList;

        // Loop through the IP Address array and add the IP address to Listbox
        foreach (IPAddress addr in ipaddr)
        {
            if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                ipList.Add(addr.ToString());
            }
        }
      }
      catch (System.Net.Sockets.SocketException ex)
     {
         ipList.Add("Invalid Host");
     }
    }
    foreach (var ip in ipList)
    {
        ips += ip + Environment.NewLine;
    }
    txtIP.Text = ips;
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}


text:
Q: Quais ramos se pode trabalhar o profissional de ti estou inciando Engenharia de software e gostaria de tirar algumas dúvidas referente ao que posso fazer para ser um profissional muito bem qualificado
Além do curso que estou fazendo qual um bom primeiro passo a ser feito paralelamente ao curso?
O que seria front, back entre outros é possível se especializar em front ou back etc...?
Seria bom aprender mais de uma linguagem?
Eu espero aprender algumas coisas sobre software, e poder me especializar em um setor


text:
Q: How to add link on menu items in magento? I have added Offer section in menu items. I treated Offer has one of the category and added 2 sub section i.e 1) 100 and 2) 50 percent offer.
Now I want to add link for sub section 100 and 50 percent

A: 1) Create a static block for your sub category from Cms->Static Blocks
2) Open your sub category from Catalog->Manage Category.
3) Under Display Setting change Display Mode to Static block only.
4) From CMS Block select your created block.
Hope this helps you.


text:
Q: Sum of selected row in Access? Just a question:
Is it in anyway possible to get a SUM of selected row/cell on the fly in Access form?
I have a db like this:
  | ID | PRICE  |  TAX
  |  1 |  20$   |   5$
> |  2 |  30$   |   6$
> |  3 |  40$   |   7$

Would it be possible to get the sum of row SUM(PRICE + TAX) in selected row (2,3).
I am using access 2007 and prefer something as native as possible, without using VBA since it's a networked DB and it's a bit hard to implement VBA in network DB.  If there are no native access way of doing it then what's the VBA solution? Could it be possible if I migrate to MSSQL?

A: You can add a boolean field to mark if the record is selected.
Then use this expression:
SelectedSum: Sum(IIf([Selected]=True,[Price]*[Tax],0))

or, if you prefer:
SelectedSum: Sum([Price]*[Tax]*Abs([Selected]))


text:
Q: Fedora 33: Use custom DNS addresses In Fedora 32, I used to edit /etc/resolv.conf in order to modify DNS addresses:
nameserver [IP1]
nameserver [IP2]

But In Fedora 33 this file has been changed and it has a warning saying Do not edit:
# This file is managed by man:systemd-resolved(8). Do not edit.
#
# This is a dynamic resolv.conf file for connecting local clients to the
# internal DNS stub resolver of systemd-resolved. This file lists all
# configured search domains.
#
# Run "resolvectl status" to see details about the uplink DNS servers
# currently in use.
#
# Third party programs should typically not access this file directly, but only
# through the symlink at /etc/resolv.conf. To manage man:resolv.conf(5) in a
# different way, replace this symlink by a static file or a different symlink.
#
# See man:systemd-resolved.service(8) for details about the supported modes of
# operation for /etc/resolv.conf.

nameserver 127.0.0.53
options edns0 trust-ad

How can I modify nameservers so I can use custom DNS addresses?

A: resolvectl dns
Global:
Link 2 (enp2s0):
Link 3 (wlp1s0): 192.168.43.63

sudo resolvectl dns wlp1s0 8.8.8.8 4.4.4.4

resolvectl dns
Global:
Link 2 (enp2s0):
Link 3 (wlp1s0): 8.8.8.8 4.4.4.4


text:
Q: Can we extract Envelope ID from DOCUSIGN Link How can i find the envelope id from docusign link , https://na3.docusign.net/Member/EmailStart.aspx?a=&er=&data=04|01||||0|0|637393960640614189|Unknown||1000&sdata==&reserved=0

A: Its not possible to extract it from such a link. Easiest way is to go to the envelope itself within the web console and click on "Envelope Id"


text:
Q: Can capacitively coupled voltages on mains cables harm devices? In my bedroom, I have a ceiling LED light with three switches. One at the door, and one at each side of the bed.
The LED light contains a constant current supply (simple switching supply), which failed these days. Until the new one arrives, I have replaced the light with  a simple fluorescent light bulb in a simple socket.
Now, I hear a quite ticking at 25Hz from the bulb when the light is OFF. Further investigation shows that the neutral line and earth is OK, there is no voltage between them. But the hot gives 40V with the bulb connected, and 70V without. (And yes, the switches act on the hot wire!)
So OK, this clearly indicates some capacitive coupling from other cables in the walls.
My question is:
Can those low voltages harm power supplies or other devices over time? It's already enough to let the fluorescent light tick at 25Hz. I could imagine that this has also caused the death of my LED light, though this could also be just by chance.

A: "Voltage when turned off" effects could come from capacitance or "leakage".
If yo assume a 10 megOhm meter impedance, and 110 VAC supply then measuring 70 VAC open circuit with only meter load suggests that
R_leakage_equivalent = (Vmains-Vmeter) / Vmeter * Rmeter
= (110-70)/70 x 10 M ~= 5.7 megOhm.  ie say
5 megOhm  with a 10 megOhm input resistance meter.
50 megOhm  with a 100 megOhm input resistance meter.
Very roughly - if capacitive coupling is causing this then, very arrproximately, about 0.5 nF would cause this degree of leakage with a 10 megOhm input resistance meter.
Death-watch-beetle like lightbulb ticking:
Either capacitive coupling or leakage resistance will cause reservoir capacitors in electronically driven lightbulbs (CFL or LEDs) to charge. This is well known to cause ticking and/or flashing with CFL bulbs as the charged capacitor triggers the bulb circuitry but there is not enough current to maintain it. I have not heard or seen this happening with LED bubs but the same principle applies. Designers my by now have taken precautions to prevent this. eg a small load at voltages below firing point which are enough to drain stray capacitance or leakage charging would be "easily enough" implemented.

Capacitive coupling CAN cause harm in specific situations, but it is usually when purposefully added capacitance is added.
Electronic mains driven supplies often have "Y" capacitors connected phase to ground and neutral to ground.  If the ground lead is grounded these serve their intended function as noise filters. If the "ground" lead is not returned to installation ground the device ground will connect to the midpoint of the two Y capacitors across the supply. In the absence of any loading a high impedance meter will measure about Vmains/2 RMS relative to either neutral or phase.
Y capacitors are typically 1 nF (0.001 uF). This is small enough to not do much harm most of the time and to destroy some equipment sometimes. Long long ago I had a brand new printer destroyed the first time it was connected to a PC via a printer cable. The printer had Y capacitors but a 2 wire plug. The Y capacitors were terminated on the printer ground. The PC had a 3 wire cord. Printer death ensued.
The Y capacitor current is theoretically too small to kill you BUT will give a nasty "nip".
Stray capacitance from cabling will generally not be an issue but will cause measurable voltages with high impedance meters. Capacitances are in the order of nFs per km. Most device cables and house wiring runs are << 1 km.

A: Capacitive Coupling should not harm devices.
But considering, you can hear some sound from your bulb, there's a slight possibility, that some components will be stressed.
What factors can theoretically lead to failure?
Warning: highly speculative, as it depends on the design of the used circuitry

*

*triggering a switch on. Every time the hot wire exceeds some triggering voltage level, the electronics try to start the circuit. They eventually fail, because after applying real load to the hot wire, the voltage collapses and the circuitry looses power before all buffering capacitors get properly loaded. You can try to verify that using a good scope. This switch on process may be deteriorating to some of the components.

*deformed waveforms. A capacitive coupled voltage has a high internal impedance if you want to put it that way. Circuitry with a lot of semiconductors and capacitors as LED bulbs will deform the waveform easily leading to sharp spikes i.e. the derivative of the voltage on the hot wire is partially very high. This can be heard, because it poses additional mechanical stress on capacitors and inductors. Perhaps this mechanical stress also increases the probability of failure.

*Perhaps you don't deal with capacitive current but with leakage due to damaged wiring. From your statement that you still measure 40 V when a load is applied, I think leakage currents are within the realms of possibility. You should rule that out, soon! Leakage currents may damage the bulb and your health as well.


text:
Q: Intended interpretation of one-mode, three-way (dis)similarities? I have what I think is a very simple question, the answer has just eluded me so far. A two-way similarity, $s_{ij}$ (for objects $i$ and $j$) can be interpreted fairly straightforwardly as the degree to which $j$ resembles $i$. When I've seen discussion of three-way similarities, however, the various authors I have read have never given a clear interpretation. They'll say something like "a three-way [similarity] is defined as the resemblance between objects taken three at a time" (slightly paraphrased from de Rooij & Heiser (2000)).
In most presentations the triadic distances are a function of the dyadic ones, e.g., $d_{ijk} = max ( d_{ij}, d_{ik}, d_{jk} ) $, where $d_{ij}$ is the Euclidean distance between the points representing $i$ and $j$. Triadic distances can also be treated axiomatically, however, and obey generalizations of the usual metric axioms. From Heiser and Bennani (1997), the triadic distance function $d : O \times O \times O \to \mathbb{R}_{\geq 0}$ is such that for all $i,j,k \in O$, and for all permutations $\pi$ on $\{i,j,k\}$,  we have:
$$
d_{ijk} \geq 0,
$$
$$
d_{ijk} = d_{\pi(i) \pi(j) \pi(k)},
$$
$$
d_{iji} = d_{ijj},
$$
$$ d_{ijk} = 0 \text{ only if } i = j = k, and$$
$$ 2d_{ijk} \leq d_{ikl} + d_{jkl} + d_{ijl}.$$
This last one is called the tetrahedral inequality and generalizes the triangle inequality.
I think I get the math behind the notion, unfortunately I can't make sense of "resemblance between objects taken three at a time". Is there a natural language gloss on this ternary similarity relation that might help me to get an intuitive grasp on it?

de Rooij & Heiser, 2000, "Triadic distance models for the analysis of asymmetric three-way proximity data"
Heiser & Bennani, 1997, "Triadic distance models: axiomatization and least squares represenation"

A: One way to think of distance is that A and B are close if there is a  short line segment that includes both of them.  You  could scale this up  a dimension by saying that A, B, and C are mutually close if there is small (in area) triangle including them.
This idea was  what I first thought of, and also seems to be the motivation for the tetrahedral inequality in the paper on axiomatizion: it relates the area of  the face with corners $(i,j,k)$ to the sum of the three other areas. The paper  says (just after equation 3b)

This compares, in the tetrahedron formed by four corners i,j,k, andl,
the size of the face made up by i, j, and k  with the sum of the sizes of
the faces that join at corner l.

There's a problem with this idea, though. Actual areas of faces of tetrahedra don't satisfy the 'tetrahedral inequality'. Instead, they satisfy the inequality that each area is less than the sum of the other three (no factor of two). To visualise this, imagine a very flat tetrahedron, almost two-dimensional. The base  area will be only very slightly less than  the sum of  the  three areas that make up the 'roof', not less than half as big. So the tetrahedral inequality is ...  well, not wrong, since it's  an axiom ... not a good representation of the motivating idea.


text:
Q: How do I perform a signed right shift(>>) in c? how do I perform a signed right shift in c?
like -25 >> 3.
I tried like this:
10011001 >> 3 == 00010011
But the result is -4.

A: According to the standard 6.5.7p5

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 /2E2. If E1 has  a  signed type and a negative value, the resulting value is implementation-defined.

The result is implementation-defined, and you should look up how it is defined there.
Assuming twos complement and signed right shift, -25 is 11100111, shifting it by 3 will lead to 11111100 which is -4.

A: That is a signed right shift. In signed shifting, a negative number (identified by the '1' in the highest bit) is often filled from the left. (Although this depends on the specific compiler. It looks like this is what your compiler is doing.)
11100111 -->
11110011 -->
11111001 -->
11111100
What it sounds like you're looking for is an unsigned shift. If you use (signed char)(((unsigned char)-25)>>3) you probably will get the results you're looking for.

A: As the right shift of the signed integer is implementation defined from my experience the result depends on the availability of the arithmetic shift on the target machine. Because nowadays is rather hard to find any computers or uC without it is almost always the result of the arithmetic shift right
From Wikipedia:


text:
Q: Create a SQL Trigger to reverse a previous Trigger I am trying to create multiple triggers. One trigger updates the 'ysnAcknowledged' field when the (hidden) field 'Reprint' in the same form gets updated by Crystal Reports. The second trigger needs to update the 'Reprint' field if the 'ysnAcknowledged' field is manually updated by the user (form checkbox). I have the first trigger, my issue is if I update the 'ysnAcknowledged' field, it will trip my second trigger effectively reversing the first trigger before I want it to.
1st trigger:
CREATE TRIGGER SOPickListReprint
ON dbo.SalesOrder
AFTER UPDATE
AS

IF UPDATE(Reprint)
UPDATE dbo.SalesOrder
SET ysnAcknowledged = 1

2nd Trigger:
CREATE TRIGGER SOPickListUpdate
ON dbo.SalesOrder
AFTER UPDATE
AS

IF UPDATE(ysnAcknowledged)
UPDATE dbo.SalesOrder
SET Reprint = 0

A: CREATE TRIGGER SOPickListUpdate
    ON dbo.SalesOrder
    AFTER UPDATE
AS

-- Update only rows where Reprint changed or ysnAcknowledged changed
-- > If ysnAcknowledged changed, force Reprint to 0, otherwise leave it as it is
-- > If Reprint changed, force ysnAcknowledged to 1, otherwise leave it as it is
UPDATE
    SalesOrder
SET
    Reprint         = CASE WHEN inserted.ysnAcknowledged <> deleted.ysnAcknowledged THEN 1 ELSE inserted.Reprint END,
    ysnAcknowledged = CASE WHEN inserted.Reprint         <> deleted.Reprint         THEN 0 ELSE inserted.ysnAcknowledged END
FROM
    SalesOrder
INNER JOIN
    inserted
        ON  inserted.<primary_key> = SalesOrder.<primary_key>
INNER JOIN
    deleted
        ON  deleted.<primary_key>  = SalesOrder.<primary_key>
WHERE
       inserted.ysnAcknowledged <> deleted.ysnAcknowledged
    OR inserted.Reprint         <> deleted.Reprint

A: My solution:
CREATE TRIGGER SOPickListReprint
ON dbo.SalesOrder
AFTER UPDATE
AS

UPDATE dbo.SalesOrder
SET ysnAcknowledged = CASE WHEN deleted.Reprint = 0 AND inserted.Reprint = 1 THEN 1 ELSE inserted.ysnAcknowledged END,
Reprint = CASE WHEN deleted.ysnAcknowledged = 1 AND inserted.ysnAcknowledged = 0 THEN 0 ELSE inserted.Reprint END
FROM SalesOrder
INNER JOIN
inserted
    ON  inserted.SalesOrderID = SalesOrder.SalesOrderID
INNER JOIN
deleted
    ON  deleted.SalesOrderID  = SalesOrder.SalesOrderID


text:
Q: Using the SMO DependencyWalker to load TreeView In a windows forms application, using C# I want to programmtically pass the SMO DependencyWalker a single object ( table, View, etc ), discover the dependencies related to that object and then load a WinForms TreeView with the results where the TreeView looks exactly like the TreeView within the SQL Server 2008 Management Studio "View Dependencies" dialog. An good example would be to view the dependencies of the "Employees" table in the Northwind database with Management Studio. I have used something like the below code snippett to get started :
UrnCollection col = new UrnCollection();

foreach (Table table in database.Tables) {
    if(table.Name == "Employees")
       col.Add(table.Urn);
}

DependencyTree tree = sp.DiscoverDependencies(col, DependencyType.Children);
DependencyWalker walker = new DependencyWalker(server);
DependencyCollection depends = walker.WalkDependencies(tree);

//Iterate over each table in DB in dependent order...
foreach (DependencyCollectionNode dcn in depends)

This does return me all the dependencies that I would need for my TreeView, but I am unable to see how to iterate the results of the "depends" object or any of the other associted SMO objects so that I would be able to load The TreeView Nodes in the correct order with the correct parent/child node relationships. Maybe I am going about this in the wrong way. Is there anyone out there that has been able to do something like this successfully?

A: I post this answer to possibly help some one is looking for it.
DependencyCollection is a flat list so you should use DependencyWalker to have tree structure.
Use FirstChild and NextSibling to traverse the tree.
This is my sample code:
private void button2_Click(object sender, EventArgs e)
{
    String srvName = "xxxxxxxxxxxxx";
    String dbName = "yyyyy";
    Server srv = new Server(new ServerConnection() { ServerInstance = srvName });
    Database db = srv.Databases[dbName];

    DependencyWalker dependencyWalker = new DependencyWalker(srv);
    DependencyTree dependencyTree = dependencyWalker.DiscoverDependencies(
        new Urn[] { db.StoredProcedures["test", "dbo"].Urn }, DependencyType.Parents);

    var dep = new DependencyPrinter(dependencyTree);
    treeView1.Nodes.Clear();
    dep.PrintDependency2(treeView1);
    treeView1.ExpandAll();
}

And the code is using this class
class DependencyPrinter
{
    private DependencyTree _dependencyTree;
    public DependencyPrinter(DependencyTree dependencyTree)
    {
        _dependencyTree = dependencyTree;
    }

    public void PrintDependency2(TreeView treeView)
    {
        var n = treeView.Nodes.Add("");
        AddToTreeNode(n, _dependencyTree.FirstChild);
    }

    private void AddToTreeNode(TreeNode treeNode, DependencyTreeNode node)
    {
        treeNode.Text = String.Format("({0}).{1}.{2}.{3}"
            , node.Urn.Type
            , node.Urn.XPathExpression.GetAttribute("Name", "Database")
            , node.Urn.XPathExpression.GetAttribute("Schema", node.Urn.Type)
            , node.Urn.XPathExpression.GetAttribute("Name", node.Urn.Type));

        if (node.FirstChild != null)
        {
            var n = treeNode.Nodes.Add("");
            AddToTreeNode(n, node.FirstChild);
        }

        if (node.NextSibling != null)
        {
            var n = treeNode.Parent.Nodes.Add("");
            AddToTreeNode(n, node.NextSibling);
        }
    }
}

A: As far as I know, the Dependency Walker retrieves a flat list of objects.
It is not a recursive or composite "tree" structure.
You would have to build that yourself.


text:
Q: Can we define $\ln(x)$ as a solution of $\frac{d}{dx}(f(x))=\frac{1}{x}$? Can we define $\ln(x)$ as the solution of the differential equation $$\frac{d}{dx}(f(x))=\frac{1}{x}$$ such that $\ln(1)=0$?

A: If you want, I know another interesting way to define the logarithm map.
We fix $\mathbb{R}^+$ with the following operations:
$a+b:=ab$
$a\cdot b:=b^a$
It is easy to check $1$ is the neutral element with respect the sum and this object is a real vector space of dimension $1$.
In fact an isomorphism is the linear map
$exp : \mathbb{R}\to \mathbb{R}^+$
The element of a  base will be $\{e\}$ and we define the logarithm as the element of the dual base of $\{e\}$ in $(\mathbb{R}^+)^*$, i.e. that map $f: \mathbb{R}^+\to \mathbb{R}$ that satisfy
$f(e)=1$
$f(ab)=f(a)+f(b)$
$f(b^a)=af(b)$
This corresponds exactly to the logarithm because
$f(a)=f(e^{log(a)})=f(log(a)\cdot e)=log(a)f(e)=log(a)$
In general the map $log_a(x)$ can be defined as the element of the dual base $\{a\}$ of $(\mathbb{R}^+)^*$


text:
Q: Parse some information from dynamically created page with JavaScript I work in service-now ITSM tool and the URL is always the same: example.service-now.com/navpage.do it means, that content updates dynamically in the web page.
Here is the part of code from Incident's page:

        Number:

        <input id="sys_original.u_incident_ict.number" value="ICT0169881" type="hidden" name="sys_original.u_incident_ict.number">
        <input id="sys_readonly.u_incident_ict.number" value="ICT0169881" class="disabled" style="direction:ltr; background-color:tomato; " readonly="readonly">
        <input id="u_incident_ict.number" value="ICT0169881" name="u_incident_ict.number" style="visibility: hidden; width: 1px;" onchange="onChange('u_incident_ict.number');">

My final task is:
I want to write a javascript bookmarklet to parse information from open Incident's page and show it in a new tab of browser.
But first, I couldn't get the value of the last <input>. I tried the command:
document.getElementById("u_incident_ict.number")

in developer's console of Google Chrome, I receive the 'null' answer.
I tried with variable:
var x = document.getElementById("u_incident_ict.number")
x.value

But receive the error because of null:
Uncaught TypeError: Cannot read property 'value' of null

So, my question is:
How to parse information from this page with the help of javascript.

A: It is working fine please check the code. Try to use JavaScript code after document ready, it might be possible you are accessing HTML element before load
Link to example > http://jsfiddle.net/nme8tcpn/

Number:

<input id="sys_original.u_incident_ict.number" value="ICT0169881" type="hidden" name="sys_original.u_incident_ict.number">

<input id="sys_readonly.u_incident_ict.number" value="ICT0169881" class="disabled" style="direction:ltr; background-color:tomato; " readonly="readonly">

<input id="u_incident_ict.number" value="ICT0169881" name="u_incident_ict.number" style="visibility: hidden; width: 1px;" onchange="onChange('u_incident_ict.number');">

- - - - - - - - - - - - - - - - - - - -

var x = document.getElementById("u_incident_ict.number")
alert(x.value)