text:
Q: How to make an Angular Material table responsive I have a simple table with numerous columns, and I would like the columns to shrink automatically when sizing the browser window.  The table-responsive works with Bootstrap, but I am looking for something similar for Angular Material.  I am trying to avoid having 2 table definitions, and do not really want to do this myself in CSS.  Is there a standard way in Angular Material for this?

        Date
        Time
        Park
        Home Team
        Away Team
        Win/Loss

            {{game.GameDate | SLS_Date}}
            {{game.GameTime | SLS_Time:'HH:mm' }}
            {{game.VenueName}}
            {{game.HomeTeamName}}
            {{game.AwayTeamName}}
            {{game.WinLoss}}

Note, I have used the Material Design Lite table here, as Angular Material does not have a table today.  Same problem, including the use of flex and grids.
I guess the new Material world does not like tables, so best option is to change the layout to not use tables.

A: I created a little directive which can be applied to a mat-table table to make it responsive. This way it is easy to only add responsive behavior to some tables in the application (which was a requirement in my case).
So basically the directive duplicates the content of each header cell (column name) as a data attribute so it can be accessed via the CSS content property (inspired by this article). Unfortunately CSS styles can't be applied to a directive, so the styles need to be imported globally.
Features

*

*no extra hard coded column names for mobile view

*reacts on language changes and updates the column names for mobile view

*reacts also on row changes/updates (e.g. add a row)

*in mobile view it only shows the columns which were made sortable via the matSort directive

This should not be seen as a general solution, as it does of course not cover all use cases. Also the styling of the table mobile view is bound to my specific requirements and probably needs to be adjusted. But i just wanted to share it, so that it maybe could serve and help as a starting point for others.
Angular 12+ (TS strict mode)
Because of the request in the comments from the user klaydze, here is an alternative version that supports the requirement to use strict: true in tsconfig.json for Angular 12+.
Stackblitz using TS strict mode
Angular < 12
Stackblitz

A: There is currently no way you can achieve this in MDL, Check out this issue on github.
I am having the same problem with my tables, but I guess I will have to make them responsive my self. There are a lot of tutorials out there & you should do a bit of research which table design would suit your responsive website the best.
Also, I think its worth checking out materializecss's responsive tables

A: An easy solution is to wrap your table with a
 with following styles:
width: 100%;
overflow-x: auto;


text:
Q: Last unbuffered line can't be read I'm trying to read the last line from a command like 'apt-get download firefox'. Normally the output will be like
Get:1 http://archive.ubuntu.com/ubuntu/ utopic/main firefox amd64 32.0+build1-0ubuntu2 [34.9 MB]
2% [1 firefox 646 kB/34.9 MB 2%]

with the last line continuously updating (it is not writing a newline until it reaches 100%). My goal is now to read the progress in realtime. Here is my current example code:
#!/usr/bin/python3 -u
# coding=utf-8

import subprocess, sys

pipe = subprocess.Popen(['apt-get', 'download', 'firefox'], 0, stderr = subprocess.PIPE, stdout = subprocess.PIPE)
while True:
    content = pipe.stdout.read(1).decode()
    if content == '':
        break
    sys.stdout.write(content)
    sys.stdout.flush()
pipe.wait()

I have disabled the output buffering for the subprocess call and also for binary output for the Python process (with the -u argument). But I'm only getting the first line but not the progress of the second line. Does somebody know how I can achieve this?

A: If stdout of apt-get is redirected to a pipe e.g.,
$ apt-get download firefox | cat

then it doesn't report progress (the last line e.g., 2% [1 firefox 646 kB/34.9 MB 2%] will not be in the output). stdout=subprocess.PIPE naturally creates a pipe; therefore apt-get doesn't print the download progress in your case.
If you want both to capture apt-get output and to see it on the screen in real-time with the last line (progress report) present then you could use pexpect module to trick the child process into thinking that it runs in a terminal:
import sys
import pexpect # $ pip install pexpect

output, exitstatus = pexpect.runu('apt-get download firefox',
                                  logfile=sys.stdout,
                                  withexitstatus=1)

You could do the same using only stdlib pty module:
#!/usr/bin/env python3
import os
import pty

output = []
def read(fd):
    data = os.read(fd, 1024)
    output.append(data)
    return data
status = pty.spawn(['apt-get', 'download', 'firefox'], read)

@eryksun on Python Issue tracker suggested apt-get's --quiet option:
#!/usr/bin/env python3
import shlex
from io import TextIOWrapper
from subprocess import Popen, PIPE

output = []
with Popen(shlex.split("apt-get --quiet=0 download firefox"),
           stdout=PIPE, bufsize=1) as p:
    # recognize '\r' as newline but don't convert it to '\n'
    for line in TextIOWrapper(p.stdout, newline=''):
        print(line, end='', flush=True) # print to terminal
        output.append(line) # save for later
print(p.returncode)

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL query become extremely slower with top select  * from RmiMember
  WHERE  [LastName] like ('li%') AND [FirstName] like ('ma%')
  ORDER BY FullName asc

0.3 Sec
This simple query takes 0.300 Sec to run but as soon as I add top 10 it becomes 3.0 Sec and If I change it to top 100 it takes 0.300 sec!
select top 10 * from RmiMember
  WHERE  [LastName] like ('li%') AND [FirstName] like ('ma%')
  ORDER BY FullName asc

3.0 Sec


text:
Q: angular ag-grid event that notifies that all of the cacheblock items are loaded I'm using SSRM ag-grid, and I have data that should be displayed in groups and the groups should be expanded.
I'm using pagination with route query parameters in my ag-grid app-path/component-path?pageNum=2
and then onInit I get the data for the first page, because otherwise the first page's data won't be available. (already tried it).
after loading the first page, I want to go to the page in the query param using the grid's API paginationGoToPage(param).
the issue is, not all of the groups data is loaded fully before moving to the next page, and then when I navigate back to the first page using navigation buttons I see that not all the groups' data is loaded, and since it's cached it won't be loaded again.
my current solution is to use setTimeout to check every 100 ms if the cacheBlock is fully loaded for the first page, and only then moving to the query param's page.
I wanted to know if there's a specific event that can help me get this data and move to the page when all of the cacheblock items are fully loaded.


text:
Q: How do I run a function on multiple columns in a dataframe? I have a database of ~96000 people that I am trying to match to another similar database. Some are missing ID numbers so I need to match columns, however the data is a bit messy and contains trailing spaces and strange capitalizing of letters.
I am using trimws() and capatalizeStrings() from the BBmisc package. But only know how to run these on individual named columns eg
MDB$City<- capitalizeStrings(MDB$City,lower.back = T,all.words = T)

MDB$City<-trimws(MDB$City,which="both")

Is there an easier way to run these functions on every column in MDB that contains character data?

A: We can use lapplyto loop over multiple columns and then assign the output back to the subset of dataset
MDB[nm1] <- lapply(MDB[nm1], function(x)
     trimws(capitalizeStrings(x, lower.back = TRUE, all.words = TRUE), "both"))

where
nm1 <- c("City", "OtherColumn1", "column2") #change the column names accordingly

A: Another option is dplyr::mutate_if. For example:
library(dplyr)

MDB %>%
  mutate_if(is.character, trimws(which = "both"))


text:
Q: Defining string packs with different content but same structure in android resources I have a game where I have a hierarchy where a season has multiple levels and a level has multiple tasks.
Now, I have an Activity that shows a congratulatory message for each of these parts of the hierarchy which are divided in different strings. Each of them have:

*

*Exclamation

*Header

*Description

*Continue Message

For example season:

*

*"HURRAY!"

*"Season Finished"

*"You have successfully finished season X"

*"Continue to season X+1"

My first idea was to create an enum that holds the appropriate values. Like this:
enum class CongratulationsType(val exclamation: String, val header: String) {
    SEASON("HURRAY!", "You finished season %d!!"),
    LEVEL("YAY!", "Well done! Level over!"),
    TASK("NICE!", "This looked too easy")
}
...
val headerString = CongratulationsType.SEASON.header

But strings should be saved in resources. So I would have to put the strings into the resources and correctly link the resources to the enum values.
This would mean that I kinda do the work twice. I would define the strings in the resource file without a "binding structure", just to then put them into the enum to have a "binding structure". By "binding structure" I mean the structure described above where it's mandatory for the specific fields to exist and where I would be able to call something like CongratulationsType.SEASON.header.
My question is: Is it possible to "pack" strings in some defined structure and have that structure be something like an enum or a hashmap? Something like:
Pack definition
<resources>
   <pack_def name="congrats">
      <string name="exclamation"/>
      <string name="header"/>
      ...
   </pack_def>
<resources>

Pack implementation
<resources>
   <pack name="season" type="congrats">
      <string name="exclamation">HURRAY!</string>
      <string name="header">Season Finished</string>
      ...
   </pack>
<resources>

Usage
// In code
//// function definition
fun setMessage(congrats: Congrats) {
    exclamationTextView.text = congratsType.exclamation
    headerTextView.text = congratsType.header
    ...
}

//// function use
setMessage(Congrats.Season)

// In Resources
<TextView
    android:text="@packs/congrats/season/exclamation"
/>

I know that I could use string array resources but they seem a little bit "unclean" because, as I said, I want the structure to be "binding" and called like enums. I'm specifically asking for a way to do it as close to enums as possible without having to assign a resource to each field for each enum value.

A:
My question is: Is it possible to "pack" strings in some defined structure and have that structure be something like an enum or a hashmap? Something like:
android:text="@packs/congrats/season/exclamation"

Short answer - no. Android will not know how to parse and extract values from these new structures.
What you can do:

*

*Create 4 string resource arrays: Exclamations, Headers, Descriptions, Continue Messages;

*Create kotlin data class with 4 string variables. Let's call it Congratulation;

*Map resources to an array with of Congratulations.

Example:
In strings.xml file you declare next arrays:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="exclamations">
        <item>Exclamation 1!!!</item>
        <item>Exclamation 2!!!</item>
        ...
        <item>Exclamation N!!!</item>
    </string-array>

    <string-array name="headers">
        <item>Header 1</item>
        <item>Header 2</item>
        ...
        <item>Header N</item>
    </string-array>

    <!-- etc. -->
</resources>

Or you can use already defined resources in these arrays just to order them:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="exclamations">
        <item>@string/exclamation_1</item>
        <item>@string/exclamation_2</item>
        ...
        <item>@string/exclamation_n</item>
    </string-array>

    <!-- etc. -->
</resources>

Define data class:
data class Congratulation(val exclamation: String, val header: String,
                          val description: String, val continueMessage: String)

Map resources:
val exclamations = context.resources.getStringArray(R.array.exclamations)
val headers = context.resources.getStringArray(R.array.headers)
val descriptions = context.resources.getStringArray(R.array.descriptions)
val continueMessages = context.resources.getStringArray(R.array.continue_messages)

val congratulations = exclamations.mapIndexed { i, exclamation ->
    Congratulation(exclamation, headers[i], descriptions[i], continueMessages[i])
}

Pros

*

*No need to mention each string resource in code, only 4 array resources;

*Following the first point, each time you add new value you don't need to modify your code. You can initialize this array at the moment of application launch once and use later.

Cons

*

*Order of translations must be precise! If you accidentally change order within <string-array> - no warning will appear. You will have to check the order manually or create specific tests;

*If accidentally you add fewer entries to any of the headers, descriptions or continueMessages array - the app will crash with IndexOutOfBoundsException. Although, it will crash as soon as you try to map values and it is easy to debug.

*Using when statements becomes impossible.

A: It's not exactly what you're asking for, but just in case the only things changing in your messages are the season numbers, you can use format strings and pass in the appropriate numbers when you display the messages:
<string name="continue_message">Continue to season %d</string>

continueTextView.text = getString(R.string.continue_message, season+1)

If you do want to be able to set arbitrary strings for each season or whatever, Jenea has it right I think - there's no way to enforce a structure in the strings XML like that (I'm not totally familiar with the XML format in general, you can do some fancy things with it but I think they're limited in what Android will actually interpret and use). You can do runtime validation (maybe only in debug builds, with a thorough check across all locales) but you have to design things so you catch any problems that might occur

edit just to make it clear what I mean about the templates
If you effectively have 4 strings, it's just that you have lots of variations depending on things like season number, level number etc, you might be able to use format strings so you you only need exactly 4 in your strings file:
<string name="season_exclamation">HURRAY!</string>
<string name="level_exclamation">YAY!</string>
<string name="season_header">You finished season %d!!</string>
<string name="level_header">Well done! Level over!</string>

That way you're enforcing a structure, there's no variable length arrays or anything - you have exactly 4 string resources, with 4 specific IDs (and if you end up localising them, it will warn you if you haven't provided them all).
So you can easily make an enum, it's just that your strings are defined in a different place
enum class Congratulations(
    @StringRes private val headerResId: Int,
    @StringRes private val exclamationResId: Int
) {
    SEASON(R.string.season_header, R.string.season_exclamation),
    LEVEL(R.string.level_header, R.string.level_exclamation);

    fun getHeader(context: Context) = context.getString(headerResId)
    // etc
}

The only tricky thing is you need to pass in that context to pull out the appropriate string resources, instead of just declaring string literals. If you want, you could set a Context on the class (early, before you access any strings) and do something like this
enum class Congratulations(
    ...
    ...
    companion object {
        lateinit var context: Context
    }

    val header: String get() = context.getString(R.string.header)
    // or, so you only grab the strings once
    val exclamation: String by lazy { context.getString(R.string.exclamation) }
}

The point about the format strings is that you don't need to create separate string resources for "bla bla season 1" and "bla bla season 2" and constantly add to the strings file, if you can use of a template string you could have a function on your enum like fun getContinueMessage(seasonNumber): String and then you don't need SEASON1, SEASON2, SEASON3 enums. Although at that point, you're better off using a sealed class since not all your Congratulation types will need that, and sealed classes will let you include different objects instead of an enum where everything is the exact same type


text:
Q: How to do assign awk output to variables I would like to search through file.txt find all lines with foo in it then filter out column 3(aaa colum) then assign each instance of aaa to a different variable.
I got as far as filter out all instance of aaa, but it was just a print out. any ideas.  Im guessing it has to be a loop of some sort. my example is below.
grep foo file.txt | awk '{print $3}'

file.txt
1. foo  bar1    aaa1    bbb1    ccc1

2. blablabla...

3. foo  bar2    aaa2    bbb2    ccc2

4. blablabla...

5. foo  bar3    aaa3    bbb3    ccc3

6. blablabla...

A: It sounds like you need a basic tutorial in awk -- a google search 'awk tutorial' will get you a few.
awk '$1=="foo"{$3="someothervalue";}{print;}' file.text

should do what you ask assuming "foo" is always in column  1 and aaa is always in coulmn 3 -- there is no need for grep.  There are two blocks, the first updates the aaa value to something else for the record marked "foo", and the second block prints all record, including the modification if any.
Update: or if all you want is to get the value of "aaa" for the records where "foo" is the key; you simply do this
awk '$1=="foo"{print $3;}' file.text

This will simply find all records which is marked "foo" and print the 3rd column (the "aaa")

A: Based on the OP's comment, there is not really a need to store the matches. You can just do this to use the output of awk as input to grep through other files.
 awk '$3 ~ /aaa/ {print $3}' file.txt  | xargs -I {} grep {}  <OTHER_FILES_HERE>

A:
I would like to search through file.txt find all lines with foo

awk '/foo/

then filter out column 3

awk '/foo/ {print $3

then assign each instance of aaa to a different variable.

aaa=($(awk '/foo/{print $3}'files)
echo ${aaa[0])

A: I am assuming you meant that you wanted to store the values in shell environment variables.
If you really do want to store the values in variables you could use eval to assign the variables:
eval $(grep foo file.txt | awk '{count+=1; print "AAA"count"="$3";"}')

This makes a separate variable for each value it finds.

A: merlin2011's suggestion to use xargs is good, but you can also use a simple shell loop and reuse the same variable name:
awk '/foo/{print $3}' |
while read value; do
  grep "$value" file
done

This assigns the output of awk to the variable "value" and executes the body of the loop once for each line generated by awk.


text:
Q: cucumber.runtime.DuplicateStepDefinitionException: Hello I am new to cucumber and selenium. I am trying to execute my maven project with multiple cucumber feature files. But when I do following error i am getting.
cucumber.runtime.DuplicateStepDefinitionException: Duplicate step definitions in test_cases.invalid_login.close_browser() in file:/D:/rakesh/folder/neon%20workspace/com.maven.cucum/target/test-classes/ and test_cases.valid_loign.close_browser() in file:/D:/rakesh/folder/neon%20workspace/com.maven.cucum/target/test-classes/
at cucumber.runtime.RuntimeGlue.addStepDefinition(RuntimeGlue.java:33)
at cucumber.runtime.java.JavaBackend.addStepDefinition(JavaBackend.java:151)
at cucumber.runtime.java.MethodScanner.scan(MethodScanner.java:68)
at cucumber.runtime.java.MethodScanner.scan(MethodScanner.java:41)
at cucumber.runtime.java.JavaBackend.loadGlue(JavaBackend.java:86)
at cucumber.runtime.Runtime.<init>(Runtime.java:92)
at cucumber.runtime.Runtime.<init>(Runtime.java:70)
at cucumber.runtime.Runtime.<init>(Runtime.java:66)
at cucumber.api.junit.Cucumber.createRuntime(Cucumber.java:80)
at cucumber.api.junit.Cucumber.<init>(Cucumber.java:59)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

And feature file is
Feature: login page functionality
  Scenario: invalid login test
    Given open a browser and goto login page
    When enter "test@techved.com" "Phari@9169"
    Then verify invalid credential message
    And close browser

And
Feature: login page functionlity
  Scenario: valid login test
    Given open a browser and goto login page
    When enter "rakeshm@techved.com" "Phari@9169"
    Then check login user
    And Logout
    And close browser

A: As the error message states you have defined two step definitions methods in separate classes which are matching the same regular expression - test_cases.invalid_login.close_browser() & test_cases.valid_loign.close_browser().
The close_browser method is defined in 2 separate classes with the same expression to match. All the step definitions in a project are loaded globally no matter if the scenario you are running uses them or not.
You could either remove one of these methods or change the expression in the given, when, then annotation with the same changes in the feature file.

A: As one of the solution is to combine the Scenario's and keep 1 feature file for whole project .
if sentence contain same words try to give identical names,if names are same it will consider as 1 and will create 1 method instead of 2 after executing the Runner class.
Without maven project we can execute multiple feature files.


text:
Q: Empty device list on eclipse while I'm running simple android application I get empty device list on eclipse although I'm connecting a device with Android 4.2 running on it. How can I add my device to the list?

A: You need to make sure the device is configured to allow 'USB Debug' Connections (in the Developer options on the device).
Sometimes, you will need to restart ADB once the device is connected if it isn't showing up.  To do this, there is a button in the 'DDMS Perspective'\Devices\rightmost upside down triangle button.
Or from the command line:
adb kill-server
adn start-server

A: You must turn on USB debugging on the device, and install the corresponding USB drivers.
See http://developer.android.com/tools/device.html


text:
Q: Is there a way to create a Clustered Index in Slick? I'm using Slick to create an application which stores a bunch of records about songs in an Hsqldb database.
Currently my tables are defined as:
abstract class DBEnum extends Enumeration {

  def enum2StringMapper(enum: Enumeration) = MappedJdbcType.base[enum.Value, String](
    b => b.toString,
    i => enum.withName(i))
}

class Artist(tag: Tag) extends Table[(Int, String)](tag, "ARTIST") {

  def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
  def name = column[String]("NAME", O.NotNull)

  def nameIndex = index("NAME_IDX", name, unique = true)

  def * = (id, name)
}

class Song(tag: Tag) extends Table[(Int, String, Int)](tag, "SONG") {

  def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
  def name = column[String]("NAME", O.NotNull)
  def artistId = column[Int]("ARTIST_ID")

  def artistFk = foreignKey("ARTIST_FK", artistId, TableQuery[Artist])(_.id)

  def idNameIndex = index("ID_NAME_IDX", (id, name), unique = true)

  def * = (id, name, artistId)
}

object BroadcastType extends DBEnum {

  implicit val BroadcastTypeMapper = enum2StringMapper(BroadcastType)

  type BroadcastType = Value
  val PLAYED = Value("Played")
  val NOW = Value("Now")
  val NEXT = Value("Next")
}

class Broadcast(tag: Tag) extends Table[(Int, Timestamp, BroadcastType.BroadcastType)](tag, "BROADCAST") {

  def songId = column[Int]("SONG_ID")
  def dateTime = column[Timestamp]("DATE_TIME")
  def broadcastType = column[BroadcastType.BroadcastType]("BROADCAST_TYPE")

  def pk = primaryKey("BROADCAST_PK", (songId, dateTime))

  def songFk = foreignKey("SONG_FK", songId, TableQuery[Song])(_.id)

  def * = (songId, dateTime, broadcastType)
}

I'm still just setting things up so not sure if it's correct but hopefully you get the idea.
Now what I want to do is keep my composite primary key on the Broadcast table but I want to create a clustered index on the timestamp. Most of my queries on that table will be filtered by ranges on the timestamp. Rows will be inserted with an increasing timestamp so there is minimal shuffling of records to maintain the physical order.
Is there any abstraction to create a clustered index in Slick? So far it seems like I'm going to have to fall back to using plain SQL.

A: Yes, you'll have to use plain sql now. You can create a feature request or a PR: https://github.com/slick/slick/issues


text:
Q: Recursive call to buff/unbuff? C# Unity3D My goal is to make a single collision detection that will decrease the movement speed of the object it collided with for a specific duration.
What I tried so far:
//Class that detects the collision
if (other.gameObject.tag == "enemy")
{
    EnemyMovement enemyMove = other.GetComponent <EnemyMovement> ();
    if (enemyMove.slowMove != 1) {
        return;
    }

    enemyMove.Slow (2, 0.5f, true);

    //....

//Class that handles the Enemy-Movement
//The slowfactor gets multiplied with the Vector3 that handles the movementspeed of the Character

void FixedUpdate ()
{
    Movement();
}

void Movement()
{
    gegnerRigid.MovePosition (transform.position + (gegnerMove * slowMove));
}

public void Slow (float duration, float slowFactor, bool slowed)
{
    if (slowed)
    {
        if (duration > 0) {
            duration -= Time.deltaTime;
            slowMove = slowFactor;
            Slow (duration, slowFactor, slowed);  //this recursive Call leads to huge performance issues, but how to keep the function going?
        } else {
            slowMove = 1;
            slowed = false;
        }
    }
}

So what I wanted to happen:
Call the Slow-function if collision happens and make it invoke itself until the duration is 0.

A: Note, the key here is that
1. You have the buff/unbuff on the other object.
You just call to the other object from the 'boss' object. Do not put the actual buff/unbuff code in your 'boss' object.  Just "call for a buff".
In other words: always have buff/unbuff code on the thing itself which you are buffing/unbuffing.
2. For timers in Unity just use "Invoke" or "invokeRepeating".
It's really that simple.
A buff/unbuff is this simple:
OnCollision()
  {
  other.GetComponent<SlowDown>().SlowForFiveSeconds();
  }

on the object you want to slow...
SlowDown()
  {
  void SlowForFiveSeconds()
    {
    speed = slow speed;
    Invoke("NormalSpeed", 5f);
    }
  void NormalSpeed()
    {
    speed = normal speed;
    }
  }

If you want to "slowly slow it" - don't. It's impossible to notice that in a video game.
In theory if you truly want to "slowly slow it"...
SlowDown()
  {
  void SlowlySlowForFiveSeconds()
    {
    InvokeRepeating("SlowSteps", 0f, .5f);
    Invoke("NormalSpeed", 5f);
    }
  void SlowSteps()
    {
    speed = speed * .9f;
    }
  void NormalSpeed()
    {
    CancelInvoke("SlowSteps");
    speed = normal speed;
    }
  }

It's that simple.


text:
Q: Create Hbase on Amazon EC2 and use it from python I want to create a database Hbase on Amazon EC2 and write some test data using python Happybase. How to do it?
Please tell me links where I can read about it.
Thanks

A: HappyBase author here.
The official HappyBase docs at http://happybase.readthedocs.org/ should get you started with Happybase. It features a really extensive tutorial including many code examples. I spent a lot of time on this, so I'm quite positive this should get you started.
For setting up HBase on Amazon EC2, you can start with the official Amazon docs at http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/emr-hbase.html


text:
Q: Setting a Tkinter variable throws the " TypeError: set() missing 1 required positional argument: value'" error message A Tkinter GUI where a bunch of 'visual effect' classes call a control panel generator
which produces a panel made up of widgets associated with the effect's parameters to modify the image on screen interactively.
tkvars = [tk.IntVar, tk.DoubleVar, tk.BooleanVar, tk.StringVar] # Available Tk variable types

Each variable-to-be goes through this loop to get the correct type of tk variable
for its intended widget.
val = the value I want to set the variable to. The type of Tk variable required
for that widget is based on the type of that value.
**if** ftype == 1:  ## CHECKBOX
    wvar = tkvars[2]     # Returns a BooleanVar
    wvar.**set**(val)
    **return** wvar          # Returns a Tk var of the correct type set to the correct value

**elif** ftype == 2:  ## RADIO
    wvar = tkvars[0]    # Returns an IntVar
    wvar.set(val)
    self._radiovar.**append**(wvar)
    **return** wvar          # Returns a Tk var of the correct type set to the correct value

**elif** ftype == 3:  ## SLIDERS
    if **str**(type(val)) in vartype: vix = vartype.**index**(str(type(val)))
    # The above line figures which type (int, float)  is required
    wvar = tkvars[vix]
    **print**(">>>>>>>>>>>>>>>SLIDER", tkvars[vix], vix, wvar, val)
    wvar.**set**(val)
    **return** wvar         # Throws an error message:
                        # ***TypeError: set() missing 1 required positional argument: value*'**

Problem is, the printout reveals that I'm attempting to set a Tk variable of the right type with the correct value, but that I now need two arguments for the Tk.variable**.set()** method.
First time I get that, and I have dozens of effect classes set up and working in the GUI. Here's the full traceback message:
Traceback (most recent call last):
  File "C:\Users\miche\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1702, in __call__
    return self.func(*args)
  File "D:/_DOCS/_CODE/ImProc/__PXL/PXL_5.py", line 10473, in clickend
    res = f.dialog()
  File "D:\_DOCS\_CODE\ImProc\__PXL\pxl_classesA.py", line 119871, in dialog
    ShapesFx.pages
  File "D:\_DOCS\_CODE\ImProc\__PXL\pxl_dialogs.py", line 6941, in __init__
    super(Dbuilder, self).__init__(parent, fields, caller, pages, isXpand, title)
  File "D:\_DOCS\_CODE\ImProc\__PXL\pxl_dialogs.py", line 732, in __init__
    self.initial_focus = self.body(body)
  File "D:\_DOCS\_CODE\ImProc\__PXL\pxl_dialogs.py", line 7024, in body
    wvar = self.getvars(parentframe, fix, item)
  File "D:\_DOCS\_CODE\ImProc\__PXL\pxl_dialogs.py", line 7227, in getvars
    wvar.set(val)
**TypeError: set() missing 1 required positional argument: 'value'**

A: Consider this code:
tkvars = [tk.IntVar, tk.DoubleVar, tk.BooleanVar, tk.StringVar]

You are creating a list of classes, not variables.
The reason for the error is that you are calling the method on the class rather than an instance of the class. Like all python classes, when you call the method on an instance python will automatically pass in the value for self. Since you aren't calling the set method on an instance, your val is being passed to the self parameter, and thus there is no argument being passed as the value.
If you wish to put the class of variable in your list (as opposed to instances of the class), you need to instantiate the class before setting the value. For example:
if ftype == 1:  ## CHECKBOX

    cls = tkvars[2]   # returns the variable class
    wvar = cls()      # instantiates the class
    wvar.set(val)     # sets the value of the instance
    return wvar       # returns the instance

Note: you can set the value at the time of instantiation to save one line of code:
wvar = cls(value=val)

If you don't need a new variable instantiated each time this code runs, you can instantiate the classes when you initialize the list:
tkvars = [tk.IntVar(), tk.DoubleVar(), tk.BooleanVar(), tk.StringVar()]


text:
Q: file_get_contents(): SSL operation failed with code 1, Failed to enable crypto I've been trying to access this particular REST service from a PHP page I've created on our server.  I narrowed the problem down to these two lines.  So my PHP page looks like this:
<?php
$response = file_get_contents("https://maps.co.weber.ut.us/arcgis/rest/services/SDE_composite_locator/GeocodeServer/findAddressCandidates?Street=&SingleLine=3042+N+1050+W&outFields=*&outSR=102100&searchExtent=&f=json");

echo $response; ?>

The page dies on line 2 with the following errors:

*

*Warning: file_get_contents(): SSL operation failed with code 1.
  OpenSSL Error messages: error:14090086:SSL
  routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in
  ...php on line 2

*

*Warning: file_get_contents(): Failed to enable crypto in ...php on
  line 2

*Warning:
  file_get_contents(https://maps.co.weber.ut.us/arcgis/rest/services/SDE_composite_locator/GeocodeServer/findAddressCandidates?Street=&SingleLine=3042+N+1050+W&outFields=*&outSR=102100&searchExtent=&f=json):
  failed to open stream: operation failed in ...php on line 2

We're using a Gentoo server.  We recently upgraded to PHP version 5.6.  It was after the upgrade when this problem appeared.
I found when I replace the REST service with an address like https://www.google.com; my page works just fine.
In an earlier attempt I set "verify_peer"=>false, and passed that in as an argument to file_get_contents, as described here:  file_get_contents ignoring verify_peer=>false?  But like the writer noted; it made no difference.
I've asked one of our server administrators if these lines in our php.ini file exist:

*

*extension=php_openssl.dll

*allow_url_fopen = On

He told me that since we're on Gentoo, openssl is compiled when we build; and it's not set in the php.ini file.
I also confirmed that allow_url_fopen is working.  Due to the specialized nature of this problem; I'm not finding a lot of information for help.  Have any of you come across something like this?  Thanks.

A: If your PHP version is 5, try installing cURL by typing the following command in the terminal:
sudo apt-get install php5-curl

A: following below steps will fix this issue,

*

*Download the CA Certificate from this link: https://curl.haxx.se/ca/cacert.pem

*Find and open php.ini

*Look for curl.cainfo and paste the absolute path where you have download the Certificate. curl.cainfo ="C:\wamp\htdocs\cert\cacert.pem"

*Restart WAMP/XAMPP (apache server).

*It works!

hope that helps !!

A: Just wanted to add to this since I ran into the same problem and nothing I could find anywhere would work (e.g downloading the cacert.pem file, setting cafile in php.ini etc.)
If you are using NGINX and your SSL certificate comes with an "intermediate certificate", you need to combine the intermediate cert file with your main "mydomain.com.crt" file and it should work. Apache has a setting specific for intermediate certs, but NGINX does not so it must be within same file as your regular cert.

A: Reason for this error is that PHP does not have a list of trusted certificate authorities.
PHP 5.6 and later try to load the CAs trusted by the system automatically. Issues with that can be fixed. See http://php.net/manual/en/migration56.openssl.php for more information.
PHP 5.5 and earlier are really hard to setup correctly since you manually have to specify the CA bundle in each request context, a thing you do not want to sprinkle around your code.
So I decided for my code that for PHP versions < 5.6, SSL verification simply gets disabled:
$req = new HTTP_Request2($url);
if (version_compare(PHP_VERSION, '5.6.0', '<')) {
    //correct ssl validation on php 5.5 is a pain, so disable
    $req->setConfig('ssl_verify_host', false);
    $req->setConfig('ssl_verify_peer', false);
}

A: Had the same error with PHP 7 on XAMPP and OSX.
The above mentioned answer in https://stackoverflow.com/ is good, but it did not completely solve the problem for me. I had to provide the complete certificate chain to make file_get_contents() work again. That's how I did it:
Get root / intermediate certificate
First of all I had to figure out what's the root and the intermediate certificate.
The most convenient way is maybe an online cert-tool like the ssl-shopper
There I found three certificates, one server-certificate and two chain-certificates (one is the root, the other one apparantly the intermediate).
All I need to do is just search the internet for both of them. In my case, this is the root:
thawte DV SSL SHA256 CA
And it leads to his url thawte.com. So I just put this cert into a textfile and did the same for the intermediate. Done.
Get the host certificate
Next thing I had to to is to download my server cert. On Linux or OS X it can be done with openssl:
openssl s_client -showcerts -connect whatsyoururl.de:443 </dev/null 2>/dev/null|openssl x509 -outform PEM > /tmp/whatsyoururl.de.cert

Now bring them all together
Now just merge all of them into one file. (Maybe it's good to just put them into one folder, I just merged them into one file). You can do it like this:
cat /tmp/thawteRoot.crt > /tmp/chain.crt
cat /tmp/thawteIntermediate.crt >> /tmp/chain.crt
cat /tmp/tmp/whatsyoururl.de.cert >> /tmp/chain.crt

tell PHP where to find the chain
There is this handy function openssl_get_cert_locations() that'll tell you, where PHP is looking for cert files. And there is this parameter, that will tell file_get_contents() where to look for cert files. Maybe both ways will work. I preferred the parameter way. (Compared to the solution mentioned above).
So this is now my PHP-Code
$arrContextOptions=array(
    "ssl"=>array(
        "cafile" => "/Applications/XAMPP/xamppfiles/share/openssl/certs/chain.pem",
        "verify_peer"=> true,
        "verify_peer_name"=> true,
    ),
);

$response = file_get_contents($myHttpsURL, 0, stream_context_create($arrContextOptions));

That's all. file_get_contents() is working again. Without CURL and hopefully without security flaws.

A: This was an enormously helpful link to find:
http://php.net/manual/en/migration56.openssl.php
An official document describing the changes made to open ssl in PHP 5.6
From here I learned of one more parameter I should have set to false:  "verify_peer_name"=>false

Note: This has very significant security implications. Disabling verification potentially permits a MITM attacker to use an invalid certificate to eavesdrop on the requests. While it may be useful to do this in local development, other approaches should be used in production.

So my working code looks like this:
<?php
$arrContextOptions=array(
    "ssl"=>array(
        "verify_peer"=>false,
        "verify_peer_name"=>false,
    ),
);

$response = file_get_contents("https://maps.co.weber.ut.us/arcgis/rest/services/SDE_composite_locator/GeocodeServer/findAddressCandidates?Street=&SingleLine=3042+N+1050+W&outFields=*&outSR=102100&searchExtent=&f=json", false, stream_context_create($arrContextOptions));

echo $response; ?>

A: I fixed this by making sure that that OpenSSL was installed on my machine and then adding this to my php.ini:
openssl.cafile=/usr/local/etc/openssl/cert.pem

A: <?php
    $stream_context = stream_context_create([
        "ssl" => [
            "verify_peer" => false,
            "verify_peer_name" => false
        ]
    ]);

    $response = file_get_contents("https://maps.co.weber.ut.us/arcgis/rest/services/SDE_composite_locator/GeocodeServer/findAddressCandidates?Street=&SingleLine=3042+N+1050+W&outFields=*&outSR=102100&searchExtent=&f=json", false, $stream_context);

    echo $response;
?>

Just tested of PHP 7.2, it's working well.
EDIT: Also tested and working on PHP 7.1

A: You can get around this problem by writing a custom function that uses curl, as in:
function file_get_contents_curl( $url ) {

  $ch = curl_init();

  curl_setopt( $ch, CURLOPT_AUTOREFERER, TRUE );
  curl_setopt( $ch, CURLOPT_HEADER, 0 );
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
  curl_setopt( $ch, CURLOPT_URL, $url );
  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, TRUE );

  $data = curl_exec( $ch );
  curl_close( $ch );

  return $data;

}

Then just use file_get_contents_curl instead of file_get_contents whenever you're calling a url that begins with https.

A: Had the same ssl-problem on my developer machine (php 7, xampp on windows) with a self signed certificate trying to fopen a "https://localhost/..."-file. Obviously the root-certificate-assembly (cacert.pem) didn't work.
I just copied manually the code from the apache server.crt-File in the downloaded cacert.pem and did the openssl.cafile=path/to/cacert.pem entry in php.ini

A: Another thing to try is to re-install ca-certificates as detailed here.
# yum reinstall ca-certificates
...
# update-ca-trust force-enable
# update-ca-trust extract

And another thing to try is to explicitly allow the one site's certificate in question as described here (especially if the one site is your own server and you already have the .pem in reach).
# cp /your/site.pem /etc/pki/ca-trust/source/anchors/
# update-ca-trust extract

I was running into this exact SO error after upgrading to PHP 5.6 on CentOS 6 trying to access the server itself which has a cheapsslsecurity certificate which maybe it needed to be updated, but instead I installed a letsencrypt certificate and with these two steps above it did the trick. I don't know why the second step was necessary.

Useful Commands
View openssl version:
# openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013

View PHP cli ssl current settings:
# php -i | grep ssl
openssl
Openssl default config => /etc/pki/tls/openssl.cnf
openssl.cafile => no value => no value
openssl.capath => no value => no value

A: Working for me, I am using PHP 5.6. openssl extension should be enabled and while calling google map api verify_peer make false
Below code is working for me.
<?php
$arrContextOptions=array(
    "ssl"=>array(
         "verify_peer"=>false,
         "verify_peer_name"=>false,
    ),
);
$url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="
      . $latitude
      . ","
      . $longitude
      . "&sensor=false&key="
      . Yii::$app->params['GOOGLE_API_KEY'];

$data = file_get_contents($url, false, stream_context_create($arrContextOptions));

echo $data;
?>

A: You shouldn't just turn off verification. Rather you should download a certificate bundle, perhaps the curl bundle will do?
Then you just need to put it on your web server, giving the user that runs php permission to read the file.  Then this code should work for you:
$arrContextOptions= [
    'ssl' => [
        'cafile' => '/path/to/bundle/cacert.pem',
        'verify_peer'=> true,
        'verify_peer_name'=> true,
    ],
];

$response = file_get_contents(
    'https://maps.co.weber.ut.us/arcgis/rest/services/SDE_composite_locator/GeocodeServer/findAddressCandidates?Street=&SingleLine=3042+N+1050+W&outFields=*&outSR=102100&searchExtent=&f=json',
    false,
    stream_context_create($arrContextOptions)
);

Hopefully, the root certificate of the site you are trying to access is in the curl bundle.  If it isn't, this still won't work until you get the root certificate of the site and put it into your certificate file.

A: After falling victim to this problem on centOS after updating php to php5.6 I found a solution that worked for me.
Get the correct directory for your certs to be placed by default with this
php -r "print_r(openssl_get_cert_locations()['default_cert_file']);"

Then use this to get the cert and put it in the default location found from the code above
wget http://curl.haxx.se/ca/cacert.pem -O <default location>

A: At first you need to have enabled curl extension in PHP. Then you can use this function:
function file_get_contents_ssl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3000); // 3 sec.
    curl_setopt($ch, CURLOPT_TIMEOUT, 10000); // 10 sec.
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

It works similar to function file_get_contents(..).
Example:
echo file_get_contents_ssl("https://www.example.com/");

Output:
<!doctype html>
<html>
<head>
    <title>Example Domain</title>
...

A: You basically have to set the environment variable SSL_CERT_FILE to the path of the PEM file of the ssl-certificate downloaded from the following link : http://curl.haxx.se/ca/cacert.pem.
It took me a lot of time to figure this out.

A: Regarding errors similar to

[11-May-2017 19:19:13 America/Chicago] PHP Warning:  file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages:
  error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed

Have you checked the permissions of the cert and directories referenced by openssl?
You can do this
var_dump(openssl_get_cert_locations());

To get something similar to this
array(8) {
  ["default_cert_file"]=>
  string(21) "/usr/lib/ssl/cert.pem"
  ["default_cert_file_env"]=>
  string(13) "SSL_CERT_FILE"
  ["default_cert_dir"]=>
  string(18) "/usr/lib/ssl/certs"
  ["default_cert_dir_env"]=>
  string(12) "SSL_CERT_DIR"
  ["default_private_dir"]=>
  string(20) "/usr/lib/ssl/private"
  ["default_default_cert_area"]=>
  string(12) "/usr/lib/ssl"
  ["ini_cafile"]=>
  string(0) ""
  ["ini_capath"]=>
  string(0) ""
}

This issue frustrated me for a while, until I realized that my "certs" folder had 700 permissions, when it should have had 755 permissions. Remember, this is not the folder for keys but certificates. I recommend reading this this link on ssl permissions.
Once I did
chmod 755 certs

The problem was fixed, at least for me anyway.

A: Fix for macos 12.4 / Mamp 6.6 /  Homebrew 3.5.2 / Openssl@3
Terminal
Check version
openssl version -a

Mine was pointing to:
...
OPENSSLDIR: "/opt/homebrew/etc/openssl@3"
...

So I looked through homebrew's dir /opt/homebrew/etc/openssl@3 and found the cert.pem and made sure my Mamp's current version of php's php.ini file was pointing to homebrew's correct openssl version's cert.pem
add to php.ini
openssl.cafile=/opt/homebrew/etc/openssl@3/cert.pem

A: I had the same issue for another secure page when using wget or file_get_contents.  A lot of research (including some of the responses on this question) resulted in a simple solution - installing Curl and PHP-Curl - If I've understood correctly, Curl has the Root CA for Comodo which resolved the issue
Install Curl and PHP-Curl addon, then restart Apache
sudo apt-get install curl
sudo apt-get install php-curl
sudo /etc/init.d/apache2 reload

All now working.

A: For me, I was running XAMPP on a Windows 10 machine (localhost) and recently upgraded to PHP 8.  I was trying to open a localhost HTTPS link via file_get_contents().
In my php.ini file, there was a line that read:
openssl.cafile="C:\Users\[USER]\xampp\apache\bin\curl-ca-bundle.crt"

This was the certificate bundle being used to validate "outside" URLs, and was a package from Mozilla as some people have discussed. I don't know if XAMPP came that way or if I set it up in the past.
At some point I had set up HTTPS on my localhost, resulting in another certificate bundle. This bundle needed to be used to validate "localhost" URLs.  To remind myself where that bundle was, I opened httpd-ssl.conf and found the line that read:
SSLCertificateFile "conf/ssl.crt/server.crt"

(The complete path was C:\Users[USER]\xampp\apache\conf\ssl.crt\server.crt)
To make both localhost and outside URLs work simultaneously, I copied the contents of my localhost "server.crt" file into Mozilla's bundle "curl-ca-bundle.crt".
.
.
.
m7I1HrrW9zzRHM76JTymGoEVW/MSD2zuZYrJh6j5B+BimoxcSg==
-----END CERTIFICATE-----

Localhost--I manually added this
================================
-----BEGIN CERTIFICATE-----
MIIDGDCCAgCgAwIBAgIQIH+mTLNOSKlD8KMZwr5P3TANBgkqhkiG9w0BAQsFADAU
...

At that point I could use file_get_contents() with both localhost URLs and outside URLs with no additional configuration.
file_get_contents("https://localhost/...");
file_get_contents("https://google.com");

A: $csm = stream_context_create(['ssl' => ['capture_session_meta' => TRUE]]);
$sourceCountry = file_get_contents("https://api.wipmania.com/{$ip}?website.com", FALSE, $csm);
echo $sourceCountry;


text:
Q: Access attribute of child of a child using python ElementTree xml file:

<Protocol1 channel="AljazeeraHD">

<frame source="vd01" id="4">

</frame>
<frame id="18" source="vd01">
   <rectangle id="1" height="87" width="976" y="889" x="414"/>
</frame>
<frame id="23" source="vd01">
   <rectangle id="1" x="300" y="886" width="1095" height="89"/>
</frame>
<frame id="35" source="vd01">
   <rectangle id="1" x="316" y="53" width="242" height="34"/>
   <rectangle id="2" x="635" y="886" width="755" height="90"/>
</frame>
</Protocol1>

Want to access value of attribute 'x' from rectangle.
Code to convert xml_to _csv:
def xml_to_csv(path):

xml_list = []
for xml_file in glob.glob(path):
    tree = ET.parse(xml_file)
    root = tree.getroot()
    for member in root.findall('frame'):
        frameNo = root.attrib['channel']+'_'+member.attrib['source']+'_frame_'+member.attrib['id']
        #print(member.find('rectangle').attrib['x'])
        #print(member.getchildren().attrib['x'])
        #print(member.find('rectangle').attrib['x'])
        value = (frameNo,
                 1920,
                 1080,
                 'Artificial',
                 int(member.find('rectangle').attrib['x']),
                 )
        xml_list.append(value)
print(glob.glob(path))
column_name = ['FrameNo', 'imgwidth', 'imgheight',
               'class','X']
xml_df = pd.DataFrame(xml_list, columns=column_name)
print(xml_list)
return xml_df

Where 'member= frame' in a loop.
1.
member.getchildren().attrib['x']

AttributeError: 'NoneType' object has no attribute 'attrib'
2.
member.find('rectangle').attrib['x']

AttributeError: 'list' object has no attribute 'attrib'

A: Since you are using ElementTree and assuming your code looks like this:
members = """
<doc>
   <frame id="18" source="vd01">
      <rectangle id="1" height="87" width="976" y="889" x="414"/>
   </frame>
   <frame id="19" source="vd01">
      <rectangle id="1" height="87" width="976" y="889" x="333"/>
   </frame>
</doc>
"""

Then this should work:
import xml.etree.ElementTree as ET
doc = ET.fromstring(members)
for frame in doc.findall('.//frame'):
       print(frame.attrib['x'])

Output:
414
333

EDIT:
Following your change to the xml, change the forloop to:
for frame in doc.findall('.//frame[rectangle]'):
      for rec in frame.findall('.//rectangle'):
         print(rec.attrib['x'])

Now the output should be:
414
300
316
635


text:
Q: Highstock monthly data step-area chart issue with last point I'm working on an highstock step-area chart.
My data are monthly, so I want them to be plotted as constant from the first to the last day of every month.
However, as you can see in this http://jsfiddle.net/d7292owr/5/:
$(function () {

  $('#container').highcharts('StockChart', {

        title: {
            text: 'Data of the month'
        },

        rangeSelector: {
            selected: 1,
            enabled: false
        },

        series: [{
            name: 'Temperature',
            //data: temperatures,
            step: 'left',
            pointStart: Date.UTC(2004, 3, 1), // first of April
            pointInterval: 3600 * 1000 * 24 * 31, // hourly data
            tooltip: {
                valueDecimals: 1,
                valueSuffix: '°C'
            },
            data:  [
                    [1404194400000.00,9.233],
                    [1406872800000.00,10.699],
                    [1409551200000.00,11.756]
                    ]
        }]
    });
});

the line of the last month always stops on the first day and pointInterval is useless.
Thanks in advance
What's wrong with my code?


text:
Q: Python Selenium Read Values from xPath attributes I am preparing a program that reads values from a time sheet. I am using python 3 and selenium using Chrome webdriver.
I have been able to use the .text method to capture the text values in the first three columns (Time Entry,Category, and Totals). However, using the same method does not work on the input boxes starting in column 4 through to.

Here is the xpath for the first row, fourth column.
/html/body/form/table/tbody/tr/td/table/tbody/tr[2]/td[2]/table[3]/tbody/tr/td[2]/div/table[1]/tbody/tr/td/table[1]/tbody/tr[1]/td[1]/input

Here is the html for the first row, fourth column (with value 7)
<input name="grdDaysProjects$ctl02$txtPrjCol0" type="text" value="7" maxlength="5" readonly="readonly" id="grdDaysProjects_ctl02_txtPrjCol0" class="GridInputsShort" onblur="GetTotalRow('1','grdComboProjects_ctl02_lblHours',2,6,'grdDaysProjects'); VerticalSum(0,'grdTotal',2,1,0); AntiXSS('grdDaysProjects_ctl02_txtPrjCol0')" data-origvalue="7">

Here is the html for the second row, fourth column (with no value)
<input name="grdDaysProjects$ctl03$txtPrjCol0" type="text" maxlength="5" readonly="readonly" id="grdDaysProjects_ctl03_txtPrjCol0" class="GridInputsShort" onblur="GetTotalRow('1','grdComboProjects_ctl03_lblHours',3,6,'grdDaysProjects'); VerticalSum(0,'grdTotal',2,1,0); AntiXSS('grdDaysProjects_ctl03_txtPrjCol0')" data-origvalue="">

It should extract a text value of 7 while any blank cells should extract a zero or null value. Using the .text method with the find_element_by_xpath method results in only null values. The html has the value in two places, the "value" and "data-origvalue". When the value is null, the "value" variable does not appear in the html but the "data-origvalue" does. Any suggestions on getting the value from the "data-origvalue" using selenium?

A: Input tag having attribute value Try  to fetch that value using element.get_attribute("value")
element=driver.find_element_by_xpath("your xpath")
print(element.get_attribute("value"))


text:
Q: error=redirect_uri_mismatch&error_description=redirect_uri%20must%20match%20configuration I am connecting two salesforce orgs with connected app, named credential and Auth Provider.

*

*I have created connected app in target sandbox.

*Created Auth Provider in source org by providing Consumer and secret key from above connected App.

*Updated connected app callback URL with the call back url from Auth provider.

*Created named credential from above Auth provider.

When trying to authorise I am getting following error "error=redirect_uri_mismatch&error_description=redirect_uri%20must%20match%20configuration". Can some one help me understand what I am doing wrong.

A: I had the same problem. I found that callback url in the connected app should be the same as you have in your redirect_uri.
I tested it with a tool called postman, maybe that can help you as well.


text:
Q: Custom object schema visibility We are planning a managed application for Salesforce platform and there are few things that are hazy.
Lets say if a customer install our managed application in their organization will they be able to see our custom objects and its fields and data? If yes, how can we hide the objects and its fields from the customer? Because if he is able to see our custom objects, he can directly use these objects using REST API. (The custom objects will be populated after running the business logic)Also suggest me (if possible) a way to hide the data of our custom objects from the customer organization.
Thanks.

A: Definitely yes, anyone who will install your managed package, can see the complete schema but with a namespace and they are only allowed to view it not edit.
Currently there is no way you can hide your schema.
I would also like to add something here, though the logic backbone is schema but the business logic is not in schema but in triggers, classes etc which is not exposed. So your business logic is definitely safe and you don't have to worry about it.


text:
Q: about android toolbar, how to hide defualt setting menu in toolbar about android Toolbar, how to hide default setting menu in toolbar
in the this activity i hava set a single icon menu,like this –
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
       android:title=""
       android:id="@+id/menu_add"
       android:icon="@drawable/actionbar_add_icon"
       android:showAsAction="ifRoom">
    </item>
</menu>

it is menu/main_home.xml
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_home, menu);
    return super.onCreateOptionsMenu(menu);
}

but it show a three dots menu. i want know why

and how to show sub menu icon image ,it is normal in the Actionbar, but hide in the Toolbar

A: *

*If you want to empty the contents of the menu, go to the res/menu folder and delete the item tags from the menu_main.xml file. You will  also need to delete references to the items in onOptionsItemSelected(MenuItem item). The menu dots will disappear if there are no items.

*If you want to completely remove the three dots menu, then go to the onCreateOptions(...) method in your code and delete it, or simply remove the getMenuInflater().inflate(...); portion of it. You can safely remove the onOptionsItemSelected(MenuItem item) method as well because it will have no purpose.

*The simplest way to make the menu disappear is to have the onCreateOptions(...) method return false.

A: this question is solved   use app:showAsAction ="ifRoom" not android:showAsAction ="ifRoom"
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<item
    android:title=""
    android:id="@+id/menu_button"
    app:actionLayout="@layout/menu_single_button"
    app:showAsAction = "always"
     /></menu>


text:
Q: Pegar script de uma DIV com JS É possivel pegar o SCRIPT de algum elemento.. EX:

Pegar apartir da 'class="box"'

pegar o código completo dentro da divisória id="form"? Que seria:

Pegar apartir da 'class="box"'

A: Se por "script" você quer dizer pegar todo o HTML dentro da div, faça assim:

var form = document.getElementById('form');
var conteudo = form.innerHTML;
alert(conteudo);

Pegar apartir da 'class="box"'

A: Como a pergunta está na categoria "jQuery" vou dar a resposta em jQuery:
var div_form = $('#form');
var html = div_form.html();

se você fizer
console.log(html);

você verá o código html extraído do elemento #form.
Você pode usar a versão simplificada:
var html = $('#form').html();


text:
Q: Maven shade plugin overlapping classes vs. dependency plugin omitted for conflict I'm using the Maven shade plugin, and I get output like the following from mvn package:
[WARNING] kryo-4.0.0.jar, kryo-2.21.jar define 91 overlapping classes:

followed by:
[WARNING] maven-shade-plugin has detected that some class files are
[WARNING] present in two or more JARs.
[WARNING] single version of the class is copied to the uber jar.
[WARNING] Usually this is not harmful and you can skip these warnings,
[WARNING] otherwise try to manually exclude artifacts based on
[WARNING] mvn dependency:tree -Ddetail=true and the above output.

On the other hand, there are many other jars that I would expect to get such warnings for, but I don't. In particular, if I do mvn dependency:tree -Dverbose, I get a lot of output like:
[INFO] |  |  +- (org.apache.commons:commons-lang3:jar:3.3.2:compile - omitted for conflict with 3.5)

My question is, why do some cases of duplicate classes result only in the "overlapping classes" warnings, while other cases result only in the "omitted for conflict" information messages?

A: The groupId of kryo changed from version 2.x to 3.x. This means that technically, kryo 4.0.0 and kryo 2.21 are different artifacts for Maven. No dependency mediation occurs, they are just put both on the classpath. This is why the shade plugin complains.


text:
Q: GridView with only SingleRow and Multiple Column I searched a lot and found many solution but no one fit in my case. actually i am working for Smart TV application. I used HorizontalListView but it not take foucs . but when i use GridView then focus is handled by GridView itself. Then my requirment is for making gridview single row and mutiple column.
Nitin Tyagi

A: Recycler View is like listview but in both orientation i.e. you can have horizontal listview as well as vertical listview.
For this case(horizontal listview), you can make recyclerview horizontal like this -
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));


text:
Q: On partition of integers I came across an example in my textbook where it was asked to find the generating function for the number of integer solutions of:
${2w+3x+5y+7z=n}$ where ${0\le w,  4\le x,y,  5\le z}$
The proposed solution is:
$$\frac1{1-t^2}\cdot\frac{t^{12}}{1-t^3}\cdot\frac{t^{20}}{1-t^5}\cdot\frac{t^{35}}{1-t^7}$$
I do understand the generating functions for these partitions, I do not however grasp the reason why the numerator for instance when ${4\le x,y}$ is ${t^{12}}$ and ${t^{20 }}$ respectively. Or why it is ${t^{35}}$ when ${5\le z}$

A: Take $x$ as an example; it corresponds to the factor $\dfrac{t^{12}}{1-t^3}$. Now
$$\frac1{1-t^3}=\sum_{n\ge 0}t^{3n}=1+t^3+t^6+t^9+\ldots+t^{3k}+\ldots\;.\tag{1}$$
When you multiply the four series together, a typical term $t^{3k}$ of this series would contribute $3k$ to the total exponent of any term in the product in which it's involved; that would correspond to $x=k$. However, you don't want to allow $x$ to be $0,1,2$, or $3$, so you need to get rid of the terms $1,t^3,t^6$, and $t^9$: you want to start with $t^{12}=t^{3\cdot4}$. Multiplying $(1)$ by $t^{12}$ does exactly that: you get
$$\frac{t^{12}}{1-t^3}=t^{12}\sum_{n\ge 0}t^{3n}=\sum_{n\ge 0}t^{12+3n}=t^{12}+t^{15}+t^{18}+\ldots\;.\tag{1}$$
A similar explanation applies to the other numerators that aren't $1$: $20=5\cdot 4$, and $35=7\cdot 5$, in each case giving you the minimum acceptable exponent.


text:
Q: How to make update query using data from two another tables (postgresql) I have 3 tables:

*

*manager with columns:

id serial PK
money int

*facilities_work_data with columns:

id serial PK
income integer

*manager_facilities with colunns:

id serial PK
manager_id references manager(id)
facilities_work_data_id references facilities_work_data(id)
The aim is to update all manager table rows by adding to manager.money column the value from facilities_work_data.income which in turn has to have id column selected as:
SELECT facilities_work_data_id  from manager_facilities WHERE manager.id = manager_facilities.manager_id

At least I found the following request:
UPDATE A AS a SET money = a.money + b.income FROM B AS b WHERE b.a_id = a.id

But its not my case, seems like I need one more join.
Could you help with such a request?

A: you can get data from two tables and add the conditions in the where clause like below
update manager M
set money = money + FWD.income
FROM manager_facilities MF,  facilities_work_data FWD
WHERE  M.id = MF.manager_id
AND MF.facilities_work_data_id = FWD.id


text:
Q: How to convince others to effect change? I'm low man on the totem pole (consultant) who was pulled into a project for a large organization. How do you explain that this large organization practices zero industry standards and follows no software patterns? Yet everyone seems completely happy and convinced that nothing is wrong.
This is the least maintainable, least testable code I have seen in my 20 years of software development.
ALL logic/html/style/js is in the database procedures.
How do I persuade even 1 person that there is a better way?

A:
How do I persuade even 1 person that there is a better way?

You talk to them. You show them.
But it does not matter at all. Two people, even ten people aren't going to shift the culture of a large organization.
The org likes things the way they are now. They've incentivized people to do things the way they are now. People were rewarded and promoted for building what is there now, so see them as good. And the org has been very successful doing things the way things have been done, so see them as good.
The low man on the totem pole is never going to change that in an org of any significant size.

A: It's a long, hard slog to map out the advantages to be had from adopting best practice I'm afraid.  The best advice I can give is to try and find a middleweight problem - a bug which has cost a fair amount of time and trouble to fix for example, maybe with more than one attempt to fix - and map out how much time and money would have been saved were the product correctly structured - or at least structured differently. Try to put it in terms of "this is working for you, but imagine how much more time you would have and how much less stress there would be if we could find a better way".
There are lots of patterns and practices blogs, articles and white papers around from reputable sources which you can use to support your argument, but above all I would advise taking the "wouldn't it be great if..." approach rather than the "you guys must be crazy for..." approach.  You want them to want to improve, not feel like they're being criticized for practices which, as far as they're concerned, are perfectly reasonable and have served them well.
I've recently had to perform some major surgery on a mature product because things were structured badly, and I managed to win through because in tweaking the project I got some significant performance improvements and dramatically improved the stability of the product.  It might be worth finding an area of your product which you can start shaping in this way, but make sure people know what you're doing and why.  Ultimately it's a business decision, and if you can make it a bit of a no-brainer which delivers major improvements in process and output then your task will be all the easier.
Good luck to you!

A:
How do you explain that this large organization practices zero
  industry standards and follows no software patterns? Yet everyone seems completely happy and convinced that nothing is wrong.

Like this: Wow! This large organization doesn't do any of the things I was told are good! And they even do things I was told are bad! But, this very successful organization doesn't seem to mind. What am I overlooking? Can I learn something from them? What problems are they trying to solve by hiring me?

This is the least maintainable, least testable code I have seen in my
  20 years of software development.

I expect mostly anything outside your comfort zone will feel unwieldy and bad to you. But, if you can't break things down and articulate why they're bad for the company, why they're in opposition to its goals, your concern isn't necessarily rational; you're just uncomfortable. And the company can tolerate your discomfort.

How do I persuade even 1 person that there is a better way?

Identify problems the company actually has.
These things are not inherent problems:

*

*Not adhering to standards

*Not using software patterns

*The code isn't unit tested

*"ALL logic/html/style/js is in the database procedures"

Inherently, they're just "things." They only attain the status of "problems" if they lead to more important "actual problems." Problems the company might care about sound like this:

*

*"Chrome is going to choke on our non-standard markup during the next update, and our core web property will totally be unusable."

*"It'll take us about a month to propagate that header change across the whole site."

*"We've been playing whack-a-mole with the same three recurring bugs for like 2 months now..."

If your company recognizes the problems and acknowledges that they are priorities, you can start talking about feasible solutions and how much of a time-investment the solutions are worth. But, be prepared! They may hear you out and say, "What you're calling problems aren't really problems for us," or "What we have is working for now," and "The proposed solutions aren't a net gain for us."
Bear in mind, you've been hired to do a particular job at a company that's already succeeding in some ways. You may have some great concerns and stellar sounding principles, but you may also be missing the company's "big picture." You will get no support from the company if there's no connection between your principles as theirs.

A: First you should probably consider if "your way" actually is better. If everyone is happy and don't perceive any problems, then they must be doing something right. If they are achieving their goals without following the "industry standard", then perhaps they have unwittingly developed a process which is actually better than the industry standard?
It is really hard to sell a process change to somebody who don't perceive a problem with their current approach. You have to be able to show that the changes you suggest actually is an improvement. You definitely have to come up with better arguments than stating the code is not "industry standard" or "doesn't use patterns", since neither is something of value in itself.

A: First, find some evidence for the real problems of the organization. Above you wrote

practices zero industry standards

I don't see a problem here.

and follows no software patterns

Still no problem.

This is the least maintainable, least testable code I have seen in my 20 years of software development.

Thats only a general, opinionated rating, no concrete problem.

ALL logic/html/style/js is in the database procedures

I am pretty sure a team of good software engineers could build a well structured system using PL/SQL and Oracle as a platform - so still no problem given in that sentence.
So in your question, there is not much evidence that there is a need for any kind of change. But in a comment you wrote

constant bugs, unable to fix problems quickly, unable to bring new folks on board, having the core guys overwhelmed yet the rest of us sit around and do nothing

Well, here are the interesting issues you "forgot" to mention in your question. But still you need to find out more about the root causes of these things, then you may be able to improve things.

*

*Constant bugs? Sounds quality assurance and testing needs to be improved. Maybe introducing some automated tests may help (don't tell me this is not possible because everything is in the DB - I wrote testing code in PL/SQL almost 20 years ago).

*Unable to fix problems quickly? Can have different reasons, find the root causes. Maybe debugging and logging tools are missing, maybe the documentation is bad, maybe people need more training, maybe the code is badly readable. Find the cause, then you can work on it.

*Unable to bring new folks on board? Find the cause. Is it because the system is so badly documented? Is more training needed? Or is it because no newcomer knows PL/SQL? Maybe there are possibilities to develop some new parts with a different tool set.
(And often a topic: do these folks have already heard of using source control?)
And so on. Sure, there will be also political problems to solve, which is nothing we can help you with (best recommendation here: find people who support you). But don't try to change the whole organization at once. Find an issue where you have a certain amount of influence, set a realistic goal for a slight improvement, try to implement it and make it public after it works. Rinse and repeat. If you are lucky, others will follow your example after some time.


text:
Q: How to perform join correctly I have the following problem on performing a left join between 2 tables.
Table SC1

COMPANY
PEDIDO
ITEM_NUMBER
VALUE

1
4789
1
100

1
4789
2
120

and Table SD1

COMPANY
PEDIDO
ITEM_NUMBER
DOC_NUMBER

1
7489
1
5874

1
7489
1
5875

1
7489
2
5880

I need to bring the Doc_Number to the SC1 table. But when I use left join and there are more than 1 Doc_Number fot the key, it duplicates the result.
Here's the result I'm getting:

COMPANY
PEDIDO
ITEM_NUMBER
VALUE
DOC_NUMBER

1
7489
1
100
5874

1
7489
1
100
5875

1
7489
2
120
5880

The result I want:

COMPANY
PEDIDO
ITEM_NUMBER
VALUE
DOC NUMBER

1
7489
1
100
5874-5875

1
7489
2
120
5880

Here's the code I'm using:
SELECT COMPANY,
       PEDIDO,
       ITEM_NUMBER,
       VALUE,
       DOC_NUMBER`
FROM SC1
     LEFT JOIN SD1 ON SC1.COMPANY = SD1.COMPANY
                  AND SC1.PEDIDO = SD1.PEDIDO
                  AND SC1.ITEM_NUMBER = SD1.ITEM_NUMBER;
GO


text:
Q: What is the linear algebraic notation for a column-wise subtraction of a vector from a matrix The Matlab code would be:
    X = [1,3;2,4]
X =

   1   3
   2   4

    b = [1;2]
b =

   1
   2

X - b
ans =

   0   2
   0   2

But would it be correct to express this operation as:
${\bf X - b} =\begin{bmatrix}1&3\\2&4  \end{bmatrix}-\begin{bmatrix}1\\2\end{bmatrix}=\begin{bmatrix}0&2\\0&2\end{bmatrix}$?
In other words, I know that you can do...
$\begin{bmatrix}1&3\\2&4  \end{bmatrix}-\begin{bmatrix}1&1\\2&2\end{bmatrix}=\begin{bmatrix}0&2\\0&2\end{bmatrix}$
but I want to express the operation as $f(\bf X, b)$.
It's interesting that the usual problem is how to code a mathematical expression...
Would any mathematician "compelled" to make sense of the non-defined expression $\begin{bmatrix}1&3\\2&4  \end{bmatrix}-\begin{bmatrix}1\\2\end{bmatrix}$ think first of any other answer than $\begin{bmatrix}0&2\\0&2\end{bmatrix}$? Say, if it was part of a sloppy "back of the envelop" calculation...
It would be great to have some simple operator like:
$\begin{bmatrix}1&3\\2&4  \end{bmatrix}{\bf\color{red}{-\,*}}\begin{bmatrix}1\\2\end{bmatrix}=\begin{bmatrix}0&2\\0&2\end{bmatrix}$

A: One approach is to find a simple way to represent the conversion of the vector $y=\begin{bmatrix} a \\ b \end{bmatrix}$ to the matrix $Y=\begin{bmatrix} a & a\\ b & b \end{bmatrix}$. But $\begin{bmatrix} a & a\\ b & b\end{bmatrix}=\begin{bmatrix} a \\ b \end{bmatrix}\begin{bmatrix} 1 &1 \end{bmatrix}$ i.e. $Y=y(e_1+e_2)^T$. So subtracting $y$ from each of the columns of a matrix $X$ is probably most simply represented as $X-y(e_1+e_2)^T$. (If the matrix is larger, you'd probably want to instead write $\sum_k e_k^T$.)


text:
Q: Controlling the consequences of async/await programming in .NET in a team environment I'm currently working on a project in a team of more than 2 people. Each person on the team has varying levels of skill and knowledge with .NET, particularly the async/await keywords for asynchronous programming in C# 5. I personally have learned much about this paradigm and am familiar with some of the intricacies and gotchas of it, but some of the team are not. Has anybody out there come up with a good convention for annotating / attributing code that returns async Task / async void to indicate whether the result of the call must be awaited or whether it can be left to run "fire and forget" in the background ? The project has a lot of heavy (over?) usage of asynchronous programming. We're working on improving performance at the moment, and there's a lot of instances where the results of functions are async Task that are not awaited and left as fire/forget, and async void where the result should really be a task that gets awaited. I should think that the answer to this should be obvious based on return type, but it's not obvious to everyone on the team.

A:
Has anybody out there come up with a good convention for annotating / attributing code that returns async Task / async void to indicate whether the result of the call must be awaited or whether it can be left to run "fire and forget" in the background ?

async void methods are ment for compatability with event handlers. They are in no way an indicator for "use this in a fire and forget scenario". You should only use them when you want to await on an async method inside, as their exception handling mechanism is different than with async Task or async Task<T>. I suggest reading Best Practices in Asynchronous Programming by Stephan Cleary which has a whole paragraph about the use of async void.
To your question, i am really not a fan of fire and forget methods. If you still want to use them, you should make them return a Task and attach a continuation which takes care of error handling to be on the safe side. Something along the lines of:
public async Task FireAndForget()
{
    await Task.Delay(1000);
    Console.WriteLine("Foo")
}

public static void ForgetSafely(this Task task)
{
     // Handle exceptions here.
}

And use it as:
FireAndForget().ForgetSafely();

Fire and forget shouldn't be a common approach in your codebase. If it is, you're doing something wrong. For those cases when you do need them, simply document your method and state it could be used in a fire and forget way but should handle exceptions properly.
Another thing to keep in mind is that when using async Task instead of async void is that emitting the await keyword will cause the compiler to generate an error, which should make fellow developers in your team to question their use of the method:

warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

For more exploring of async void:

*

*async/await - when to return a Task vs void?

*C# Async Tips and Tricks Part 2 : Async Void


text:
Q: jQuery Wrap Elements Created By .Each Method in a Div I want to wrap elements created from a the .each method in a div.
Here's my code:

The basic idea is to create a heading for each year and underneath that list the events for each year, of which there will be varying numbers. I want to wrap the events in a div after they've been parsed from the XML file. How do I do that?

A: Here's my current script:

Here's the HTML output it produces:

1950

        One

        Two

        Three

        Four

1951

        Five

        Six

        Seven

1952

        Eight

        Nine

        Ten

        Eleven

        Twelve

Basically, I am trying to parse this XML file:
<?xml version="1.0"?>
<Years>
    <Year year="1950">
        <Events>
            <Event>
                One
            </Event>
            <Event>
                Two
            </Event>
            <Event>
                Three
            </Event>
            <Event>
                Four
            </Event>
        </Events>
    </Year>
    <Year year="1951">
        <Events>
            <Event>
                Five
            </Event>
            <Event>
                Six
            </Event>
            <Event>
                Seven
            </Event>
        </Events>
    </Year>
    <Year year="1952">
        <Events>
            <Event>
                Eight
            </Event>
            <Event>
                Nine
            </Event>
            <Event>
                Ten
            </Event>
            <Event>
                Eleven
            </Event>
            <Event>
                Twelve
            </Event>
        </Events>
    </Year>
</Years>

My goal is to create a  with a  on it for each year in the XML file with a sub-list  for each list of events corresponding with that year and a  for each event on that list.


text:
Q: Laravel passport oauth multiple database connection So, I'm building this api where each client use the same system (controllers, models). Each client has his own database and a website that connect's to this database.
Now that's the problem, this api must serve all this websites with different database connections and since I'm new to Laravel, I'm facing a hard time. What's the best way to do that?
Should I save each database in a file (for example client's id is 1, so we have a folder with a file named 1.env with database info)?
PS.: I'm using oauth2

A: The solution I found was: each client with his own database and a folder with "users" and a subfolder for each client. Inside, a file with database info, in login we use a global table that indicates where's the database from that user. Next step is load the database connection and check user/password. That was a quick solution.
However in my research  I stumped into "multi tenancy" thing that seams way better, you can find it more on this link.


text:
Q: How to Programatically Update an XML Body and print the updated body Below is my input XML body, which is stored in src/test/resources:
<Customer>
    <Id>1</Id>
    <Name>John</Name>
    <Age>23</Age>
</Customer>

I want to pass this XML body into the below java method, re-set the name & then post it to a HTTP URL:
public void updateXMLBodyAndPost(String newName(){
    File file = new File("src\\test\resources\\customerDetails.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Customer customer1 = (Customer) jaxbUnmarshaller.unmarshal(file);
    customer1.setName(newName);
    System.out.println("Customer details: " + customer1.toString());
}

Above, i am able to set the new name.
Then, I am trying to print out the updated XML body
But, instead what's being printed out is:

Customer details: Customer@7ba4f24f

What changes do I need to make to my code so the following is printed out in the console:
<Customer>
    <Id>1</Id>
    <Name>updatedName</Name>
    <Age>23<Age>
</Customer>

A:
Customer details: Customer@7ba4f24f

You get this because you are calling .toString() and you have not included an implementation for it.
By default, every object, in your case Customer, has a default toString() which will result in a similar response as you have. You can read about the default toString() here.
Overriding toString:
public class Customer {

    private String name;
    private String id;
    private String age;

    @Override
    public String toString() {
        return "Customer{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

You can go in modifying the default toString() and make it return an xml, but I don't think that is a good idea, as toString() is not meant for that.
I would rather create a separate method where you unmarshal your xml from the file and marshal it back with the modifying customer data.
You can do the marshaling as:
    File file = Paths.get("src/main/resources/customer.xml").toFile();
    JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Customer customer1 = (Customer) jaxbUnmarshaller.unmarshal(file);
    customer1.setName(newName);

    // overriding toString
    System.out.println("Customer details with toString: " + customer1.toString());

    // print it nicely using JAXB
    final Marshaller marshaller = jaxbContext.createMarshaller();
    StringWriter sw = new StringWriter();
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(customer1, sw);
    String xmlString = sw.toString();
    System.out.println("Customer details with JAXB.marshal: \n" + xmlString);

which would print:
Customer details with toString: Customer{name='dsadadada', id='1', age='23'}
Customer details with JAXB.marshal:
<Customer>
    <Name>dsadadada</Name>
    <Id>1</Id>
    <Age>23</Age>
</Customer>


text:
Q: Synchronize Nodes within the same NodeGroup in SymmetricDS I have a symmetricds configuration where there are two Node Groups.

*

*Server : has a static ip

*Stores (have two nodes) : Don't have static ips, hence they push data to the server using server's sync url and pulls updates from the server. (No sync url is configured for nodes in this group as they don't have static ips)

The setup works fine, in following cases.

*

*When data is added directly to Server (not from a Store node) they get updated in two Stores nodes

*When data is added to one of the Stores, they push those to Server node.

My problem is in 2nd case above, the data that was added to one store doesn't sync to the other store though data get updated fine at the server. Is there any solution for this?

A: For those tables declare triggers for bi-directional synchronization using SYNC_ON_INCOMING_BATCH set to 1.


text:
Q: Creating a re-usable feature file which can accept different json payloads I want to create a re-usable feature which can be called by other feature files and that re-usable feature file should accept different json payloads
I want the analyticPayload to accept json file which is passed from createAnalytic.feature
1) createAnalytic.Feature -->
Given url xyz
And headers abc
And header Content-Type = 'multipart/form-data'
And multipart field analytic = analyticPayload
And multipart file file = templateJar
When method POST
Then status 200

2) createAnalytic.Feature -->
Scenario Outline:

* def analyticEntry= call read('classpath:tests/commonFeatures/createAnalytic.feature') {analyticPayload:<analyticPayload>}

Examples:
|analyticPayload|
|read('classpath:payloads/analyticCreation/createPowerAnalytic.json')|

Getting the error : :1:97 Missing close quote
com/ge/KraftTests/commonFeatures/createAnalytic.feature') {analyticPayload:powerAnalyticTemplate}
                                                                                ^ in  at line number 1 at column number 97

A:
that re-usable feature file should accept different json payloads

In my opinion, no it should not. Can you please read this answer carefully - and if you still want to go down this path, open a new question.
https://stackoverflow.com/a/54126724/143475


text:
Q: Wordpress like system templating for a SaaS application I'm in the process of creating an application that will be deployed as a service (SaaS)
and I would like to offer the capability to the user of having their own templates and plugin to the system ( with setting up template and plugin market in the future ) something similar to what wordpress and Joomla is doing. The application is done in Codeigniter and I'm looking for similar implementation and guide on how to achieve this.
The question is how do I do it, as in how do you design the system with this kind of requirements. Any resource and sample implementation will be much appreciated.
Disclaimer: I'm a newbie to templating world


text:
Q: How can I make my website's background image (wallpaper/skin) clickable? I am trying to make the background/skin/wallpaper of my site http://www.outpostmagazine.com/ clickable so that when a user click the background they are sent to another site.

A: When I open your page, the left and right images you wish to make clickable are not even visible. From the little I can see of them, it appears that you have overlapping elements. I would suggest you take a look  here  to ensure you have correct positioning of your elements, and then attempt to make your images clickable. If you are still having issues, post your relevant scripting.


text:
Q: Hiding a static class behind an interface - EventHandlers I'm doing some maintenance on an existing project that has static service classes coming out the waazoo.
Basically I've had some success hiding them behind an interface + wrapper class that calls through directly to the existing static.
BUT
There are some of the existing static classes that have event handlers and wrapping these inside a property will not work since the EventHandler can only be on the left hand side of a += or -=.
The only way around this I can think of is to provide methods for adding and removing EventHandlers in the wrapper class which then accesses the static class event handler.
Is there a way to do it so the existing += and -= does not need to be changed?
eg, the existing use of the static classes is
SomeExistingStaticClass.SomeEventHandler += MyMethod;

refactored to
IStaticInterface myClass = new WrapperSomeExistingStaticClass();
myClass.SomeEventHandler += MyMethod;

and inside the wrapper I've tried to have SomeEventHandler as a property with a getter like this
public EventHandler SomeEventHandler
{
    get
    {
        return SomeExistingStaticClass.SomeEventHandler;
    }
}

Is there something I am missing, or is the best solution here to use an AddHandler and RemoveHandler method on the wrapper class?

A: How about implementing a new event in your wrapper class, and then implement custom event accessors? in here you could reroute the events from the static service class, and keep your eventhandlers in sync. See here (custom event accessors) for a simple example.


text:
Q: C# parsing existing timestamp from db? I am trying to parse an existing timestamp from my database to a DateTime but it isn't going to well. As far as I know the following is a valid timestamp.
2017-03-27 02:23:37

What have I tried?
Convert.ToDateTime(row["last_used"])

And this
DateTime.Parse(Convert.ToString(row["last_used"]))

Both throw errors about it not being a valid DateTime?
How I save them:
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

A: If you use custom pattern to format DateTime for saving, you may use the same pattern for parsing it back from string to DateTime:
var date = DateTime.ParseExact("row["last_used"]", "yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture);

I would suggest you to use ISO standard formatting date.ToString("o") which will produce string like 2009-06-15T13:45:30.0000000Z, then you may parse it without problems using DateTime.Parse(dateStr)


text:
Q: How to use mapbow-gl-draw 'draw.create' event in Angular with MapLibre
I'm trying to create an app with Angular, including MapLibre and mapbox-gl-draw. I tried to follow [this example][1] and adapt it to my project, but I run into an issue. When I call the event 'draw.create' on my map
this.map.on('draw.create', this.updateArea);

I have the following error

No overload matches this call.
Overload 1 of 3, '(type: keyof MapEventType, listener: (ev: (MapLibreEvent<MouseEvent | TouchEvent | WheelEvent> | MapLibreEvent<MouseEvent | TouchEvent> | ... 10 more ... | MapWheelEvent) & Object) => void): Map', gave the following error.
Argument of type '"draw.create"' is not assignable to parameter of type 'keyof MapEventType'.
Overload 2 of 3, '(type: MapEvent, listener: Listener): Map', gave the following error.
Argument of type '"draw.create"' is not assignable to parameter of type 'MapEvent'.

It seems like Angular won't let me use mapbox-gl-draw events. How can I call the draw.create event ? Or alternatively, how can I detect that a polygon has been draw ?
You can find a stackblitz copy of my code here : https://stackblitz.com/edit/angular-ivy-p2jfgk


text:
Q: How to get server datetime without postback using JSOM or services My application page may be long time without reloading, and user changed system date and time. And I need to know datetime from server, not from client.

A: You could just create a custom webservice that returns the server time and call this through JS.


text:
Q: MATLAB: Are there any problems with many (millions) small files compared to few (thousands) large files? I'm working on a real-time test software in MATLAB. On user input I want to extract the value of one (or a few neighbouring) pixels from 50-200 high resolution images (~25 MB).
My problem is that the total image set is to big (~2000 images) to store in RAM, consequently I need to read each of the 50-200 images from disk after each user-input which of course is way to slow!
So I was thinking about splitting the images into sub-images (~100x100 pixels) and saving these separately. This would make the image-read process quick enough.
Are there any problems I should be aware of with this approach? For instance I've read about people having trouble copying many small files, will this affect me to i.e. make the image-read slower?

A: rahnema1 is right - imread(...,'PixelRegion') will fasten read operation. If it is not enough for you, even if your files are not fragmented, may be it is time to think about some database?
Disk operations are always the bottleneck. First we switch to disk caches, then distributed storage, then RAID, and after some more time, we finish with in-memory databases. You should choose which access speed is reasonable.


text:
Q: How do I add custom SYNTAX to OpenLDAP? When defining an attribute in OpenLDAP, you have to provide a SYNTAX OID so OpenLDAP knows what kind of string it can accept for that attribute.
How can I create a new SYNTAX for OpenLDAP?

A: You can't. You have to stick to the syntax OIDs that it already understand. You can add new attributes that obey existing syntaxes, and new objectClasses that use those new attributes, but that's it.


text:
Q: Why does AWS use { "Key" : key, "Value" : val} syntax? I am used (in Python and Java) to seeing dicts/hashmaps defined as { key : value}
AWS uses the format { "Key" : key, "Value" : val }
Where does this approach come from?  It adds complexity, is there a benefit to be gained from that complexity?
EDIT: an example is the format for tags:
Tags=[
    {
        'Key': 'string',
        'Value': 'string'
    },
]

A: One possibility: AWS tends to use the same formats for data structures on the wire for different cases, for consistency, reducing overall system complexity by reducing variability.  Blatant examples of this are S3 event notifications and Lambda@Edge triggers, where the event data structure (shown here as { ... }) is unnecessarily wrapped in an outer object with one key and an inner array with one member as {"Records": [{ ... }]} even though by definition in these cases the Records array can never have more or less than one inner object.  They do this for consistency.
Another possible explanation: the low-level APIs that the SDK is using to communicate with the service use XML¹, where this structure makes more sense.
From the EC2 API Reference, DescribeTags action, here's a sample response:
<tagSet>
  <item>
     <resourceId>ami-1a2b3c4d</resourceId>
     <resourceType>image</resourceType>
     <key>webserver</key>
     <value/>
  </item>
  <item>
     <resourceId>ami-1a2b3c4d</resourceId>
     <resourceType>image</resourceType>
     <key>stack</key>
     <value>Production</value>
  </item>
  ...
</tagSet>

It's an array of objects with multiple attributes.  That isn't always the case, but this takes us back to the "consistency" argument, above.
It's admittedly often very awkward to work with, and a dictionary would seem much more straightforward, but the SDKs appear to be simply preserving the underlying data format that's used on the wire with minimal transformation, and that format was adopted many years ago in an XML-centric world.
Another possibility: As can be seen, here, there are also multiple candidates for keys, which could use a nested dictionary structure:
{
  "image": {
    "ami-1a2b3c4d": {
        "webserver: "",
        "stack": "production",
        ...
    }
  }
}

This structure does not lend itself to response pagination.  Many API actions return a limited result set and a continuation token.
This "improved" nested structure is also arguably harder to scan for all tags where "key" equals "stack" because you have to traverse up and down the tree.

¹ XML... there are exceptions, and largely undocumented is the fact that many XML service APIs secretly support JSON and some of them even support sending a request in XML and receiving a response in JSON by signaling your intentions using HTTP request headers... but in the case of JSON interactions on the wire, there's this same evidence that they appear to be transforming XML into JSON on the service side, preserving the structure, or otherwise using the same native structure for both formats, which would make sense in the interesting of making the service interactions identical regardless of the serialization.

A: One benefit to that approach is that you don't need to know the key in advance, so you can be more flexible/modular, allowing third party to add keys and values.