text:
Q: how to reverse array | slice in golang without using for statement I'm looking for a way to reverse [][]string|int in Golang without using any for statement.
I couldn't find any solution. I found this post How do I reverse a slice in go?, but every solution is used for statement. I know the best way to handle this problem is using for, but I'm looking for other solutions without having for
 list := [][]int{
            {2,3,4},
            {6,8,1},
        }

the result is like this: [[2 3 4] [6 8 1]].
but I need something like this: [[6 8 1] [2 3 4]].
What should I do without using the for statement? Is there any idea?

A: Using for loop here - is the simplest solution.
PS: You can try to use hardcoded solution like this one:
list2 := [][]int{list[1], list[0]}

but it's rather hack than solution,
so better to use nice and concise programmatic solution base on for loop.

A:
What should I do without using the for statement? Is there any idea?

recursive calls
package main

import (
    "fmt"
)

func main() {
    list := [][]int{
        {2, 3, 4},
        {6, 8, 1},
    }
    reverse(list)
    fmt.Println(list)
}

func reverse(d [][]int) {
    j := len(d) - 1
    i := 0
    var h func()
    h = func() {
        if i<j {
            d[i], d[j] = d[j], d[i]
            i, j = i+1, j-1
            h()
        }
    }
    h()
}

goto statements
package main

import (
    "fmt"
)

func main() {
    list := [][]int{
        {2, 3, 4},
        {6, 8, 1},
    }
    reverse(list)
    fmt.Println(list)
}

func reverse(d [][]int) {
    j := len(d) - 1
    i := 0
START:
    if i < j {
        d[i], d[j] = d[j], d[i]
        i, j = i+1, j-1
        goto START
    }

}

if you read that far, read about a regular solution https://stackoverflow.com/a/28058324/4466350


text:
Q: Problem with Python module "Schedule" for timed fan control I wrote the code below to control a fan.
import schedule
import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(14, GPIO.OUT) #set pin 14 as output

def aan():
    GPIO.output(14,0)    #set pin 14 to "low", fan comes on
    print(time.strftime("%H:%M")+" aan") #print time in hours and minutes, aan=on in Dutch

def uit():
    GPIO.output(14,1)    #set pin 14 to "high", fan goes off
    print(time.strftime("%H:%M")+" uit") #print time in hours and minutes, uit=off in Dutch

schedule.every().hour.at(":00").do(aan)
schedule.every().hour.at(":01").do(uit)
schedule.every().hour.at(":15").do(aan)
schedule.every().hour.at(":16").do(uit)
schedule.every().hour.at(":30").do(aan)
schedule.every().hour.at(":31").do(uit)
schedule.every().hour.at(":45").do(aan)
schedule.every().hour.at(":46").do(uit)

try:
    while True:
        if int(time.strftime("%H")) in range(9,21): #only preform the schedule between 9 and 21 hours
            schedule.run_pending()
            time.sleep(1)
        else:
            time.sleep(1)

finally:
   print("clean up")
   GPIO.cleanup() # cleanup all GPIO pins

It is supposed to run for 1 minute at the 4 specified times in the schedule. The code works, but I've noticed from the print in the terminal that it also comes on 4 times on 09:00 (see below).
09:00 aan
09:00 uit
09:00 aan
09:00 uit
09:00 aan
09:00 uit
09:00 aan
09:00 uit

I've tried changing the :00 "on" and :01 "off" schedules, but this doesn't seem to make a difference. It would be greatly appreciated if someone could help me!

A: I would address the problem a little differently as illustrated below:
def fan():
    # Operate the fan
    on_time = 60  # Runtime in seconds
    if int(time.strftime("%H")) in range(9,21): #only preform the schedule between 9 and 21 hours
        GPIO.output(14,0)    #set pin 14 to "low", fan comes on
        print(f'Turn on Fan at {time.strftime("%H:%M")}')
        time.sleep(on_time)
        GPIO.output(14,1)    #set pin 14 to "high", fan goes off
        print(f'Turn Off Fan at {time.strftime("%H:%M")}')

Then:
schedule.every().hour.at(":00").do(fan)
while True:
        run_pending()
        time.sleep(1)

else:
   print("clean up")
   GPIO.cleanup() # cleanup all GPIO pins

I can't fully test this code because I don't have your fan device, but this seems to work with just print statements.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I put Column Data to rows and assign fixed ID to them in Netezza? My Data looks like this -
Game      | P1  | P2    | P3    | P4    | P5
Cricket   | Vk  | St    | Mw    | Sg    | Nm
Football  | Cl  | Zn    |   | Un    | Rb
Hockey    | Gd  | Sg    | Mu    |   | Hl

I want to convert them like this -
Game    | Players   | Id
Cricket   | Vk  | 1
Cricket   | St  | 2
Cricket   | Mw  | 3
Cricket   | Sg  | 4
Cricket   | Nm  | 5
Football  | Cl  | 1
Football  | Zn  | 2
Football  | Un  | 4
Football  | Rb  | 5
Hockey    | Gd  | 1
Hockey    | Sg  | 2
Hockey    | Mu  | 3
Hockey    | Hl  | 5

Could anybody please help me on this?
Not sure if you are able to understand this, basically it's the table i want to put but it din't allow me to put it in table manner so I have used | as breakers. For reference please view images attached

Thank You

A: I think your question has already been answered   here .
Anyway, you might probably want to do a union all.
select *
into target
from (
Select Game, P1 as Players, '1' as Id
from source

union all

Select Game, P2 as Players, '2' as Id
from source

union all

Select Game, P3 as Players, '3' as Id
from source

union all

Select Game, P4 as Players, '4' as Id
from source

union all

Select Game, P5 as Players, '5' as Id
from source
)

A: Here is another approach that doesn't use UNION ALL. The first part here is just creating some sample data to work with. This would be an ideal format for future questions as it makes it super easy for others to work on your issue.
declare @Something table
(
    Game varchar(10)
    , P1 varchar(10)
    , P2 varchar(10)
    , P3 varchar(10)
    , P4 varchar(10)
    , P5 varchar(10)
)

insert @Something values
('Cricket', 'Vk', 'St', 'Mw', 'Sg', 'Nm')
, ('Football', 'Cl', 'Zn', null, 'Un', 'Rb')
, ('Hockey', 'Gd', 'Sg', 'Mu', null, 'Hl')

Now using CROSS APPLY we can simulate the UNPIVOT functionality. I find this approach a lot easier to remember and understand than the UNPIVOT function which is just incredibly obtuse syntax for me.
select s.Game
    , MyValues.Name
from @Something s
cross apply (values(s.P1), (s.P2), (s.p3), (s.p4), (s.p5)) MyValues(Name)
where MyValues.Name is not null
order by s.Game
    , MyValues.Name

For completeness I put together how you could do this using UNPIVOT.
select Game
    , u.Name
from (select Game, P1, P2, P3, P4, P5  from @Something) s
unpivot (MyValues for Name in (P1, P2, P3, P4, P5)) as u


text:
Q: WebStorm 8 showing errors for a correct HTML tag I am new to WebStorm 8. In my current project, everything is working fine except this :
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css"/>

WebStorm show errors with it. When I inspect the code, it says :
Selector matches unknown element bower_components

Nevertheless, this code works. What's wrong with this tag for WebStorm ?
Update :
to Iena
Here is a simple example where WebStorm 8.0.2 shows errors :
Selector matches unknown element http (at line 4)

The code :
<!doctype html>
<html>
<head>
  <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css">
</head>
<body>
<button class="btn btn-primary">Works fine</button>
</body>

A: Place your caret on that unknown element and Press Alt+Enter then choose Un-inject Language.

A: As per your latest screenshot -- for some reason you have SASS language injected into href attribute of the link tag. Possibly (quite likely) it was done accidentally when typing a lot and not paying enough attention (e.g. not looking at the screen at that particular moment).
Either use Un-inject Language/Reference from that popup menu .. or (which is better) delete that unwanted rule completely from Settings | Language Injections -- 4th one from the top, the one that has "global" in "Type" column.


text:
Q: How to write API to find international TimeZone I need to write a API in php to get the timezone. I did some research found

*

*google API.

*Timezonedb.com

*time-zone-api
I need to write API in php and ASP.net to get the TimeZone. It will be used for commercial site. I am looking for free service for this task.
If some one can help me the right functions to do this task in php or asp.net.
I would still appreciate that.
Thanks

A: You can use base http://www.php.net/manual/en/class.datetimezone.php DateTimeZone Class as the base Class for your API.


text:
Q: Why is change of entropy of a mixture of water at 2 different temperatures sum of their individual change of entropy? If 1kg water at 7°C is mixed with a 2kg water at 70°C, lets say that the temperature of the mixture becomes 40°C and change of entropy of water that was at 7°C is $S_1$ and that of the other is $S_2$. Then why is the total change of entropy of the systen is $S_1+S_2$ but not $S_1×S_2$ considring entropy as permutation of microstates? Or why isn't it something higher or lower than the sum as water molecules are identical?

A: Actually, the final temperature is 49 C.  If C is the heat capacity of the liquid water and $T_R$ is taken an absolute reference temperature for zero entropy for water, then the initial entropy of the 1 kg of water is $(1)(C)\ln{[(273+7)/T_R]}$, the initial entropy of the 2 kg of water is $(2)(C)\ln{[(273+70)/T_R]}$, and the final entropy of the 3 kg mixture is $(3)(C)\ln{[(273+49)/T_R]}$.  So the change in entropy from the initial state to the final state is $$\Delta S=(3)(C)\ln{[(322)/T_R]}-$(1)(C)\ln{[(280)/T_R]}-$(2)(C)\ln{[(343)/T_R]}$$$$=(1)C\ln{\left(\frac{322}{280}\right)}+(2)C\ln{\left(\frac{322}{343}\right)}$$Note that the reference temperature cancels out of the calculation.


text:
Q: How can I use similar routes with different namespaces in Laravel 8? I have a problem with routes in Laravel 8.
I have 2 controllers with the same controller name and same function name but in different namespaces.
Route 1:
Route::namespace('Frontend')->group(function () {

    //Frontend Category Route
    Route::get('{main}/{slug}', 'CategoryController@one')->name('category.1');

});

Route 2:
Route::namespace('Backend')->group(function () {

    //Backend Category Route
    Route::get('categories/{level?}/{id?}', 'CategoryController@index')->name('categories');

});

Namespace line of Category Controller in Frontend:
namespace App\Http\Controllers\Frontend;

Namespace line of Category Controller in Backend:
namespace App\Http\Controllers\Backend;

When I call "index" function in backend category controller the function named "one" in frontend category controller works.
Is there any solution other than changing the controller name?
PHP Version: 7.3.10
Laravel Version: 8.83.13

A: You could prefix both route groups like this:
  /* --- Frontend --- */
  Route::prefix('/backend')->namespace('Backend')->group(function(){
    Route::get('categories/{level?}/{id?}', 'CategoryController@index')->name('categories');
  });

  /* --- Frontend --- */
  Route::prefix('/front')->namespace('Frontend')->group(function(){
    Route::get('{main}/{slug}', 'CategoryController@one')->name('category.1');
  });

If you don't want to prefix the "front" routes, just put the backend routes on top. Backend routes will be evaluated first and if there's no match, the requested url will fall to the frontend routes.


text:
Q: Codenameone SpanButton uiid not working I created a form initially with a normal Button and applied a uiid to the button.
This was working.
Now when I change the button to a SpanButton, the uiid stops working.
Is there anything that I am missing here ?

A: SpanButton is a composite component, this effectively means it is composed of several separate components and when you change its UIID you only change the UIID of the parent container and not the individual elements within it.
You need to also use setTextUIID & setIconUIID.


text:
Q: Spring Data Neo4j Repository Composition error: No property XXXX found for type YYYY This should be a simple question about something that I'm probably missing from the Spring Data documentation.
I'm trying to implement a repository extension as described in: http://docs.spring.io/spring-data/data-neo4j/docs/3.0.2.RELEASE/reference/html/programming-model.html#d0e2970.
The code is really simple. I just have a repository and an extension interface (and implementation).
First a repository for MyType class:
public interface MyTypeRepository extends
        GraphRepository<MyType>, MyTypeRepositoryExtension { }

Then the extension interface:
public interface MyTypeRepositoryExtension {
    void anyMethodNameForQuery();
}

And its implementation:
public class MyTypeRepositoryExtensionImpl {

     public void anyMethodNameForQuery() {
          //custom query code
     }
 }

With this code, Spring Data throws an error while bootstrapping its mapping infrastructure:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property any found for type MyType!
As what I'm understanding from this error, any method that is added to the extension interface Spring Data tries to map to a property of the respective type. But that is the only use of repository extensions? That is not what I was understanding from the documentation (linked above). If that is true what are the alternatives for custom queries?
A final observation is that I'm aware of @Query annotation, but my use case require a specific traversal and dynamic query composition.

EDIT: FURTHER INFORMATION
Looking at the documentation again I found some information that might be related to this. In order to configure repository composition it is necessary to change repository scan path from org.example.repository to org.springframework.data.neo4j. That is why any method that I put in the MyTypeRepositoryExtension interface Spring Data was trying to map to a MyType property.
I've set Spring Data Neo4j repository scan path as documented, but I've got many runtime class not found errors such as: java.io.FileNotFoundException: class path resource [javax/enterprise/inject/spi/Extension.class] cannot be opened because it does not exist".
In a try-and-error-totally-adhoc manner I have managed to find some dependencies that could fill out the missing classes. I've ended up with these dependencies:
    <dependency>
        <groupId>com.mysema.querydsl</groupId>
        <artifactId>querydsl-core</artifactId>
        <version>3.3.3</version>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>com.mysema.querydsl</groupId>
        <artifactId>querydsl-lucene4</artifactId>
        <version>3.3.3</version>
        <optional>true</optional>
        <exclusions>
            <exclusion>
                <groupId>org.apache.lucene</groupId>
                <artifactId>lucene-core</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.mysema.querydsl</groupId>
        <artifactId>querydsl-apt</artifactId>
        <version>3.3.3</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>1.0-SP1</version>
    </dependency>

That eliminated the class not found errors, but now, since I changed the repository path, Spring is not able to inject the repositories.
The documentation tries to say something about this I think, but I couldn't understand what "put it behind" means in the phrase (from the documentation): "If you use <context:component-scan> in your spring config, please make sure to put it behind <neo4j:repositories>, as the RepositoryFactoryBean adds new bean definitions for all the declared repositories, the context scan doesn't pick them up otherwise".
To sum up I really need some orientation here :-) ... Also, I think that the documentation needs to define the needed dependencies. And describe how extension repositories and standard repositories (interface only) can be mixed in a project.

A: I know after one year probably the answer won't be useful for you, but maybe can help other people who is struggling with spring-data-neo4j, like myself these days (see question)
Just point two things you need to change:
1) Following the spring-data repository naming conventions, the name of the implementation of your custom repository has to be EntityRepsitoryImpl (although the default sufix Impl can be changed by configuration). So, you need to change MyTypeRepositoryExtensionImpl for MyTypeRepositoryImpl
2) You don't need to change the neo4j:repositories package. org.example.repository is fine. Don't use org.springframework.data.neo4j
3) Concerning the dependencies needed, if you don't change the package repository as mentioned in the point 2, is enough with the basics:

*

*org.springframework.data.spring-data-neo4j

*javax.validation.validation-api

*com.sun.jersey.jersey-client

I agree with you that spring-data-neo4j repository composition is a bit confusing and there are very few good examples online... So, finally I've decided to create a sample project on GitHub, with a basic example showing how we can do that.
Hope it help other people in the future.
See on GitHub: neo4jCustomRepository


text:
Q: How do I use Pandas to organize and sort rows? I am trying to use Pandas to organize and sort rows. My code takes items from a list and sorts them by how many times each item is recurring. Here is the code:
from collections import Counter
import time
filename = input("Enter name to save this file as:\n\n")
print("Your file will be saved as: " + filename + ".csv\n\n")
time.sleep(0.5)
print("Please copy/paste ids directly into this")
contents = []

def amount():
    while True:
        try:
            line = input()

        except EOFError:
            break
        contents.append(line)

    return

amount()

count = Counter(contents)
print(count)

import pandas as pd

d = count
df = pd.DataFrame.from_dict(d, orient='index').reset_index()
df.columns =['column1', 'column2']

df = df.sort_values(by=['column2'],ascending=False)

print(df)
df.to_csv(filename + ".csv", encoding='utf-8', index=False)

If we inputted names, for example: 1, 1, 1, 2, 2, 2 , 3 - it would come out like this on the sheet:
1: 3
2: 3
3: 1
Is there any way to make it so instead of showing individually that there are 3 instances of 1 and 3 instances of 2, it just lists that there are 2 numbers on the page that occur 3 times and 1 number that occurs once? Sorry if this is long and confusing.


text:
Q: MSSQL: выбрать несколько последних записей В MSSQL лежит чуть больше десятка таблиц, последние 3 записи каждой из которых я хотел бы просмотреть. Первые три я выбираю запросом:
SELECT TOP 3 * FROM table_name;

Когда одно из полей содержит идентификатор-инкремент, можно отсортировать данные по убыванию идентификатора и опять же сделать запрос SELECT TOP...
Однако не во всех таблицах есть этот самый инкремент. Есть, к примеру, таблица, в которой всего два поля: [name] и [type].
Есть ли какой-нибудь вариант увидеть последние записи в этом случае?
UPD. Огорюсь, что для меня пока загадка, как MSSQL хранит данные. Я знаю, что данные писались в таблицы последовательно и предполагаю, что запрос SELECT TOP... выбирает первые (иными словами, самые ранние из записанных в БД) записи. Соответственно, меня интересуют последние записанные в таблицы данные.
A: В общем случае - нет. Одна запись ничем не лучше другой, так что если нет identity или хотя бы даты или timestamp, то нет причин думать, что какая-то из них добавлена раньше.
A: @Denis Khvorostin не думаю, что порядок добавления действительно гарантирован  в M$Sql. то что вам везло еще ничего не значит.
тут эмоциональное рассследование поведения mssql на эту тему(eng)


text:
Q: How to implement checklist like feature similar to "google keep notes" app checklist feature? I have a notepad app and in that I want to implement checklist feature like keep notes app that consists of a checkbox and the text which the user will enter.
I am confused as to how to design the layout. Will the UI be dynamic? because the user can enter as many checklist items as they can

A: You can add a CheckBox programmatically in another view every time the user press enter.
See How to programmatically add views to views, OnEditorActionListener

A: Use recycleview to do this. When user adds a new value update the recycleview item. A list contain a checkbox with a textview. you can set onCheckChangeLisener to determine whether the user checked an item then change the value of checked status and call notifydatasetChanges(). Recycleview will automatically do everything for you. you just have put right logic initially when setting up the recycleviewAdapter


text:
Q: My indexing fails when my grid is non-square I made this program. It finds words in a grid.
It works if the grid's dimensions are equal, but it it doesn't work whenever I give the grid unequal dimensions.
With grid.txt as
WEDJCIOSDC
PVCEWOMNVU
VOWNRYCOWM
CJIMQPLDIW
QNIEOCMOFJ
FEWMQOPCNE
CIENWMEQBV
IVMENBSPLD
NOEFOQMFIE
JSCNIUSCGP

My program colors the words red. But with grid.txt as
WEDJCIOSDC
PVCEWOMNVU
VOWNRYCOWM
CJIMQPLDIW
QNIEOCMOFJ
FEWMQOPCNE
CIENWMEQBV
IVMENBSPLD
NOEFOQMFIE

It won't work.

My code:
import pygame

pygame.font.init()

wn = pygame.display.set_mode((600, 600))

class Cell():
    def __init__(self, x, y, s, text=' ', color=(0, 0, 0)):
        self.input_box = pygame.Rect(x, y, s, s)
        self.x = x
        self.y = y
        self.s = s
        self.color = color
        self.text = text
        self.active = False
        self.font = pygame.font.Font(None, s)

    def draw(self):
        txt = self.font.render(self.text, True, self.color)
        x, y = self.x+(self.s-txt.get_width())//2, self.y+(self.s-txt.get_height())*5//7
        wn.blit(txt, (x, y))
        pygame.draw.rect(wn, self.color, self.input_box, 2)

class Grid():
    def __init__(self, x, y, size, letters, color=(0, 0, 0)):
        rows = len(letters)
        cols = len(letters[0])
        self.grid =  [[Cell(i*size+x, j*size+y, size, letter) for i, letter in enumerate(row)] for j, row in enumerate(letters)]
        self.cells = [cell for row in self.grid for cell in row]
        self.rows = rows
        self.cols = cols

    def adj(self, cell, idx, lstlst, wrd):
        x, y = self.cells.index(cell) // self.rows, self.cells.index(cell) % self.rows
        y1 = x - 1 if x else 0
        y2 = self.rows + 2 if x > self.rows + 2 else x + 2
        x1 = y - 1 if y else 0
        x2 = self.cols + 2 if y > self.cols + 2 else y + 2

        adjs = []
        for row in self.grid[y1:y2]:
            for c in row[x1:x2]:
                if c != cell:
                    adjs.append(c)

        taillst = lstlst[-1]
        for cell in adjs:
            if len(wrd) > idx:
                if cell.text == wrd[idx]:
                    lst = taillst[:]
                    lst.append(cell)
                    lstlst.append(lst)
                    self.adj(cell, idx+1, lstlst, wrd)

    def draw(self):
        for cell in self.cells:
            cell.draw()

with open('grid.txt', 'r') as r:
    letters = [row.strip() for row in r]

grid = Grid(50, 50, 32, letters)
word = 'NEW'

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                for cell in grid.cells:
                    lstlst = [[cell]]
                    grid.adj(cell, 1, lstlst, word)
                    for lst in lstlst:
                        if ''.join([c.text for c in lst]) == word:
                            for c in lst:
                                c.color = (255, 0, 0)

    wn.fill((255, 255, 200))
    grid.draw()
    pygame.display.flip()

A: Your grid is a row major order grid, not a column major order grid. Therefore, the indexes of the grid need to be calculated by dividing by the number of columns, not the number of rows:
x, y = self.cells.index(cell) // self.rows, self.cells.index(cell) % self.rows
x, y = self.cells.index(cell) // self.cols, self.cells.index(cell) % self.cols

With these changes, the original calculation of the adjanced cells also works:
adjs = [cell for row in self.grid[y1:y2] for cell in row[x1:x2] if cell != self.grid[x][y]]

In fact, the first index for the subscription is the row (y) and the second is the column (x), so I recommend renaming and swapping the variables (x / y):
class Grid():
    # [...]

    def adj(self, cell, idx, lstlst, wrd):
        y, x = self.cells.index(cell) // self.cols, self.cells.index(cell) % self.cols
        x1, x2 = max(0, x - 1), min(x + 2, self.cols + 2)
        y1, y2 = max(0, y - 1), min(y + 2, self.rows + 2)

        adjs = [cell for row in self.grid[y1:y2] for cell in row[x1:x2] if cell != self.grid[y][x]]

        taillst = lstlst[-1]
        for cell in adjs:
            if len(wrd) > idx:
                if cell.text == wrd[idx]:
                    lstlst.append(taillst[:] + [cell])
                    self.adj(cell, idx+1, lstlst, wrd)

A: The problem in the code is the classic confusion between x and y axis, and incorrectly equating x-axis with rows.
Here is the exact problem:
x, y = self.cells.index(cell) % self.rows, self.cells.index(cell) // self.rows

Edit:: @Rabbid76 pointed out correctly that we need to divide by columns rather than rows:
x, y = self.cells.index(cell) // self.cols, self.cells.index(cell) % self.cols

Please upvote @Rabbid76's answer instead of mine.

fixes the highlighting issue as we are now able to find the actual cell with correct (x,y) coordinates. In a way this also explains why it worked for a square.
However, having said that, I think there might be some improvements needed wrt the DFS algo for finding the word.
For starters, I couldnt figure out why you start with idx=1 here:
grid.adj(cell, 1, lstlst, word)

But since, this was not really part of this question, I'll leave this to you.
Edit:: Adding a screenshot for the non-square game:


text:
Q: Continuously monitor linux console logs using C/C++ application I have one third party library application which runs continuously and generates console print when some event occurs.
I want to take some action when some specific event occurs so I need to monitor console prints continuously to trigget my action.
Is it possible to write application which can continuously monitor string dumper on console(stdout) and do processing when one line is detected.
I have tried to use 'popen' function but it keeps waiting until library application stops execution.
Here is my sample code using open
#include <stdio.h>

int main()
{
    FILE *fd = NULL;
    char buf[512] = {0};

    fd = popen ("./monitor","r");
    while (fgets (buf, 512, fd) != NULL)
    {
        printf ("__FILE__ : message : %s\n",buf);
    }

    printf ("EOF detected!\n");
    return 0;
}

Can anyone please let me know proper way of monitoring console logs and take action.
Thanks in advance.
Pratik

A: Here is an example piece o code I 've written recently that reads from stdin and prints to stdout .
void echo(int bufferSize) {
    // Disable output buffering.
    setbuf(stdout, NULL);
    char buffer[bufferSize];
    while (fgets(buffer, sizeof(buffer), stdin)) {

        printf("%s", buffer);
    }
}

As I understand you have a similar issue as I had initially getting delayed output because I didn't use:
setbuf(stdout, NULL);

You can also read from stdin(that's what my example code does ) just pipe your command to your c code or if you just want to filter output pipe it to grep. If it's a standardized syslog log you could also use tail on the log file:
tail -f <logfile>| <your c prgoramme>

or
for just filering
tail -f <logfile>|grep "<your string here>"

or if without log file pipe stdout logs this way:
  <your app>|<your c prgoramme>

or
  <your app>| grep "<your string here>"

A: 3rd party program simulated by a shell script that writes to stdout
#!/bin/bash
while true; do
    echo "something"
    sleep 2
done

You want to write something like this to capture the output from the 3rd party program and then act on the information:
#!/bin/bash

while read line; do
    if [[ $line == "something" ]]; then
        echo "do action here"
    fi
done

Then combine them with a pipe operator:
./dosomething.sh | act.sh


text:
Q: How can I add something to my code so there are no repeats every 6 times when it adds to a list? Me and a buddy of mine are just beginners trying to make something so we don't have to make the list by hand but we cant figure out how to make the code does not repeat the first 5 letters of a name for at least for the next 5 names added to the list
import random

num_in_list = int(20)

data = [

]

blacklist = [

]

preferred = [

]

not_preferred = [

  ]

def generate_list(num_in_list, blacklist, preferred):
  list = []

  while len(list) < num_in_list:
    index = random.randint(0, len(data) - 1)

    data = data[index]

    if name not in blacklist:

       if data in preferred:

         if random.random() < 0.75:

           list.insert(0, data)
       else:

         if random.random() < 0.50:
           list.insert(0, data)
         else:
           if data in not_preferred:
             if random.random() < 0.25:
               rotation.insert(0, data)

  return list

list = generate_list(num_in_list, blacklist, preferred)

I tried searching around but it is too hard for me to understand and cant figure out how to impliment other peoples solutions.

A: Let's break the solution down into steps:

*

*Generate a starting name (and store its first 5 letters)

*Generate 4 more names (making sure not to generate names with the same first 5 letters)

*Repeat step 1 until you have enough names

import typing
import random

def generate_names(n: int) -> typing.List[str]:
    l: typing.List[str] = []
    while len(l) < n:
        new_name: str = random.choice(NAMES)
        first_five: str = new_name[0:5]
        l.add(new_name)
        for _ in range(0, 4):
            non_similar_name: str = random.choice(NAMES)
            while non_similar_names.startswith(first_five):
                non_similar_name = random.choice(NAMES)
            l.add(non_similar_name)
    return l


text: Q: How to get pivot table entry using row and column's index in pandas I want to access pivot table entries through row and column number. How can I get the value that corresponds to row = 1 (userID = 2110) and column = 1 (ISBN = 0001046438)? Thank you.


text:
Q: What is the difference between hybrid application and a phone-gap cardova application? If I need to explain my self whats the difference between a hybrid app and a application built using phonegap, how I am going to explain ?

A: Phonegap is an implementation of a hybrid approach. It is best to consider it a "hybrid framework". Another version of a hybrid application could be build mainly native and then use webviews (UIWebView on iOS, WebView on Android) for certain cross-platform pages. There are still many other frameworks and designs for "hybrid".
Generally the more important comparison is web vs. native vs. hybrid.
These should help you as well:
http://www.asyncdev.net/2012/10/phonegap-a-misunderstood-hybrid-framework/
http://www.icenium.com/blog/icenium-team-blog/2012/06/14/what-is-a-hybrid-mobile-app-

A: Phonegap
PhoneGap is basically a Hybrid Application.
What is PhoneGap Trying To Accomplish?
The purpose of PhoneGap is to allow HTML-based web applications to be deployed and installed as native applications. PhoneGap web applications are wrapped in a native application shell, and can be installed via the native app stores for multiple platforms. Additionally, PhoneGap strives to provide a common native API set which is typically unavailable to web applications, such as basic camera access, device contacts, and sensors not already exposed in the browser.
To run a PhoneGap application on a native emulator/simulator, developers will generate a project for each of the native platforms they wish to support, configure that project's "web root" directory in Xcode, Eclipse, or whatever native toolchain is needed, and then run the project using that tool.
Strengths of the PhoneGap Approach
Any native platform that supports a web view or web runtime can be a PhoneGap platform. Anyone who can write HTML, CSS, and even a small bit of JavaScript can wrap up a web page in a native app and distribute it as such. The barrier to entry in using PhoneGap to package web pages as native apps is extremely low.
Weaknesses of the PhoneGap Approach
The quality of the user interface in a PhoneGap application will vary based on the quality of the web view and rendering engine on the platform. The Webkit-based rendering engine on iOS is strong, and provides the best performance. The Android web view is functional, but has some notable limitations.
PhoneGap also cannot be extended with native user interface. The end developer's application its self lives inside a web view, and user interface is rendered in HTML.
Check this link for more Info : Phonegap Tutorial

A: Phonegap is environment where we can implement hybrid application. You can say Phonegap is implementation tool. Hybrid App which run on cross platform. Hybrid app create through CSS,javascript,html which run on multiple plateform. A hybrid application (hybrid app) is one that combines elements of both native and Web applications.
More Details you can see :
https://developer.salesforce.com/page/Native,_HTML5,_or_Hybrid:_Understanding_Your_Mobile_Application_Development_Options
http://docs.phonegap.com/en/3.5.0/guide_overview_index.md.html#Overview
http://public.dhe.ibm.com/software/in/events/softwareuniverse/resources/Native_web_or_hybrid_mobile-app_development.pdf


text:
Q: Error en calidad de canvas
Por qué la calidad de letra del filltext se ve así?

Código:

/* Área de programación */

$(function(){
 var w = window;
    var d = document;
    var dW = d.body.clientWidth;
    var dH = d.body.clientHeight;
    console.log(dW);
 var c = d.getElementById("can");
 var ctx = c.getContext("2d");
    /* Dibujando el fondo */
ctx.fillStyle = "#111111";
 ctx.fillRect(0,0,dW,dH);
    /* Dibujando el título */

    ctx.font = "7px monospace";
    ctx.fillStyle = "#FFFFFF";
    ctx.fillText("Programando en Cosmos Theories !",20,50);
    ctx.fill();

});

/* Fin */

A: la calidad de visualización se debe a que canvas maneja pixeles hay que tener siempre cuidado con la dimensiones.
Por ejemplo si ajustaste el tamaño del canvas con css.
Este es resultado que obtuve yo usando tú ejemplo y en html solo incluí la etiqueta canvas.


text:
Q: How to calculate average from webelement list? I chose the price list from WebElements. How can I calculate the price average?
I try use len() and sum() but it's not working.
price = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")
for i in price:
    value = i.text
    print(value)

output:
€4.44
€3.32
€3.93
€3.78
€4.06

Edit.
I find WebElement list using a CSS selector:
price = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")

This element list have 5 prices:
€4.44
€3.32
€3.93
€3.78
€4.06

I want to calculate average prices but I can't because this is WebElement List. I tried to extract this number without € by decimals:
price = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")
for i in price:
    value_price = i.text
    value = Decimal(sub(r'[^\d.]', '', value_price))
    print(value)

Output:
4.44
3.32
3.93
3.78
4.06

And now I want to calculate average this numbers:
price = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")
for i in price:
    value_price = i.text
    value = Decimal(sub(r'[^\d.]', '', value_price))
    print(value)
avg = sum(value)/len(value)
print(avg)

Output:
Traceback (most recent call last):
  File "C:\Users\sokal\PycharmProjects\pythonProject1\login_sorare.py", line 56, in <module>
    avg = sum(value)/len(value)
          ^^^^^^^^^^
TypeError: 'decimal.Decimal' object is not iterable

I'm not sure what's wrong because I can't use sum()/len().

A: sum() and len() are expecting a list but you are passing in just one value. That's why you are getting the object is not iterable error. There are a number of ways you can do this. One way is to take your existing code, add each .text value to an array, and then use sum() and len() to calculate the average.
price_elements = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")
text_prices = [price_element.text for price_element in price_elements]
prices = [float(text_price.replace('€', '')) for text_price in text_prices]
average = sum(prices)/len(prices)
print(average)

...and it prints
3.9059999999999997


text:
Q: p overflowing out of div Dear community
I recently wanted to create a div with an image, a title and text.
As shown in the image, the image should be aligned left and on the right side the title followed by a text.
But, the text overflows the parent div. How can the p element set to the exact max-height, so that the element "ends" when "touching" the parent div? Like that, I want to set text-overflow: ellipsis;, which stops the text from overflowing - ellipsis is important, that the text does not abruptly stop so that it creates the 3 dots at the end.
In the screenshot, you can see the dotted line, which indicates my intention (with a bit of margin of the p at the bottom to div). The blue box is the size of the p element (from the Google Chrome element inspector).

div {
      border: 1px solid black;
      width: 35em;
      height: 10em;
    }

    img {
      float: left;
      width: 40%;
      height: 100%;
      margin-right: 1em;
    }

    p {
      height: 100%;
      overflow: hidden;
      margin-right: 2em;
    }

Title

    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Thank you all for your help. If you have any improvements in the question, feel free to edit it to make it clearer to the public.

A: You can create a separate

 for your content and set overflow-y to scroll. If you don't want the text to be visible at all, set overflow-y to hidden. Here's how you do it:

.container {
    border: 1px solid black;
    width: 35em;
    height: 10em;
}

.content {
    height: 100%;
    overflow-y: scroll;
}

img {
    float: left;
    width: 40%;
    height: 100%;
    margin-right: 1em;
}

Title

        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.


text:
Q: Braintree update subscription from monthly to yearly Hi all Braintree experts (and others)
We are currently working on this app which uses Braintree for all the payment stuff.
The idea is pretty simple; an user can either subscribe for a monthly or yearly membership.
For some reason Braintree decided us not to update an existing subscription from monthly to yearly and visa versa so easily.
If you are stubborn like me and try it any way, you'll receive the following error message:
Cannot update subscription to a plan with a different billing frequency.
Updating a subscription within the same billing cycle comes with the neath option; proratedCharges, which calculates and handles the difference in price.
Now my question is: What is the best way to change from monthly to yearly (and visa versa) with the difference in price calculated and handled (like proratedCharges does)?
I was thinking of:

*

*Checking the balance of the current subscription

*Canceling the current subscription

*Creating a new subscription with the difference from the balance included (one time discount, or price increase, not even sure if that's possible)

Because Braintree doesn't really says a lot for this matter, and the fact that money will be involved, I really want to get this done right. So I am validating with you guys. Thanks!

A: Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
Your proposed solution would work. You can't update an existing subscription's billing frequency.
As a workaround, you can cancel the existing subscription in either the Control Panel or using subscription.cancel. Then, create a new one that factors in the old subscription's balance using add discounts or add-ons.


text:
Q: MySQL Query Date Great than specific date I am typing to run a query against a table with the following WHERE clause:
WHERE stock_current.Manufacturer = 5 AND
stock_current.date_despatched > 2013-10-01 AND
stock_current.StockStatus = 5

but it is returning all dates.

A: You need to quote the date
AND stock_current.date_despatched > '2013-10-01'

Only numbers don't need to be quoted.

A: The following code will work
WHERE stock_current.Manufacturer = 5 AND
DATE(stock_current.date_despatched) > '2013-10-01' AND
stock_current.StockStatus = 5


text:
Q: Need help cloning collaborative git repository - getting host is down error Trying to clone a git repo I've been asked to collaborate on and keep getting this error
ssh: connect to host heroku.com port 22: Host is down
fatal: The remote end hung up unexpectedly
Any ideas? Really need to get this working! Thanks.

A: It can be a proxy issue, or it can be because you didn't add your ssh public key to the repo (as mentioned in "ssh: connect to host heroku.com port 22").
Depending on your ssh address, use the right ssh config for heroku.
Make sure your heroku repo address is the right one (see "Rails / Heroku: fatal: The remote end hung up unexpectedly").


text:
Q: How do I add resources such as text files or exe files into my application? I tried this code
static HOST_FILE: &'static [u8] = include_bytes!("C:\\Users\\Downloads\\cbimage.png");

fn main() {
     let host_str = std::str::from_utf8(HOST_FILE). unwrap();

     println!("Hosts are:\n{}", &host_str[..42]);
}

But it shows me an error:
thread 'main' panicked at 'called Result::unwrap() on an Err value: Utf8Error { valid_up_to: 66, error_len: Some(1) }', src\main.rs:48:51
stack backtrace

A: static IMAGE: &'static [u8] = include_bytes!("C:\\Users\\Downloads\\cbimage.png");

fn main() {
    println!("Image: {:?}", IMAGE);
}

Although I recommend using a path relative to your source code, like
static IMAGE: &'static [u8] = include_bytes!("../cbimage.png");

fn main() {
    println!("Image: {:?}", IMAGE);
}

And place cbimage.png next to your Cargo.toml.


text:
Q: How to count from 0.0001 to 1 in ruby? I want to count from 0.0001 to 1 with 0.0001 steps in ruby.
I wrote this code but it enters to an infinite loop. Somewhy the interpreter does a wrong summation.
x = 0.0001
while x != 1.0
  puts x
  x = x + 0.0001
end

Here is the first 10 value it gives:
0.0001
0.0002
0.00030000000000000003
0.0004
0.0005
0.0006000000000000001
0.0007000000000000001
0.0008000000000000001
0.0009000000000000002
0.0010000000000000002

It should be 0.0001, 0.0002, 0.0003, etc...
How can I make it working?
Thanks!

A: The problem is that real numbers in ruby are not represented exactly due to binary storage and manipulation. I would do this
x = 1
while x < 10000
    puts (x/10000).round(4)
    x += 1
end

A: Try this:
0.0001.step(1, 0.0001).each { |i| puts i }

EDIT: you should use the Float#step method because it shields you from the weirdness of float arithmetic. Float#step will take care of incrementing the value and comparing to the limit in a float-proof way. For more information have a look at the official documentation of Float#step.

A: Rather than x != 1.0, put x < 1.0. That will at least be sure your loop ends.
A binary system like those that run all of our modern computers cannot (easily) represent fractions, especially ones that cannot be accurately represented in decimal. That is where the strange number comes in when you should have .0003. It is an artifact of how the numbers are represented internally.
Some languages are better at dealing with numbers and accuracy than others, so if the accuracy of the numbers matters, you either need to use a different language, use a library that handles the number things for you (significant digits and all that), or you need to handle it yourself with appropriate rounding, etc. at each step.

A: Floating point numbers are not exactly accurate Wikipedia Floating Point article.
If you must have clean x's, I'd recommend using an integer and dividing down by 1000 before you use the value.  If you don't care about the little bits of noise off, you'll be fine with changing your while x != 1.0 to while x < 1.0

A: What you are seeing is due to binary representation of floating-point numbers. This affects all computer programming languages. For more detail see What Every Computer Scientist Should Know about Floating Point Arithmetic.
What you can do is round it to the appropriate number of digits at print time, or as goiele has found, use step:
0.0001.step(1, 0.0001).each do |i|
  puts i
end

A: 1.step(10000, 1).each { |x| puts "%f" % (x / 10000.0).round(4) }


text:
Q: Unstable wireless on MacBook 2,1 with Ubuntu 11.10 I just installed Ubuntu 11.10 as the sole OS on my old white MacBook 2,1.
The wireless seems really unstable. The signal is always full, but sometimes I can browse, sometimes I can't. Sometimes I can download updates, sometimes they stop. I am using another laptop right next to it, and the network on that is flawless.
Any ideas?

A: I tried the following commands and was sceptical whether it would work. But it has been flawless and has solved my issues with my wireless on Macbook 2.1.
root@ubuntu:~# ifconfig wlan0 down
root@ubuntu:~# rmmod -f ath9k
root@ubuntu:~# sudo modprobe ath9k nohwcrypt=1

WARNING: All config files need .conf: /etc/modprobe.d/bad_list. It will be ignored in a future release.
root@ubuntu:~# ifconfig wlan0 up


text:
Q: Android: Render HTML not supported by Html.fromText If I have html with tags not supported as part of Html.fromText I understand a WebView will do the trick as it supports standard HTML as a browser but its performance is really slow to my liking. So if I don't want to use WebView, the only other way is to parse the HTML myself and put different tags in muliple TextView inside a vertical LinearLayout?

A: You'll have to use Html.fromHtml() with an Html.TagHandler to handle unknown tags like <pre/> and <code/>.
See this answer for an example of how to implement Html.TagHandler.

A: Use replaceAll() to convert the <pre> and <code> tags to <tt>, which is supported by Html.fromHtml(). Then, use Html.fromHtml() to create the SpannedString that you pass to the TextView.


text:
Q: SASL error when trying to connect to hive(hue) by python from my PC - Windows10 Need your help!
I read all the documentation that I found on the internet (StackOverflow, Github, etc.), but nothing helped.
I am trying to connect to hive(hue) by python from my PC, my script is:

When I run this code I got this error message:
 Traceback (most recent call last):
 File "C:/Users/myuser/Documents/Python/testing.py", line 6, in <module>
 cursor = hive.connect('myconnect', port=10000, username='root').cursor()
 File "C:\Users\myuser\AppData\Local\Continuum\anaconda3\lib\site-packages\pyhive\hive.py", line 94,
 in connect
 return Connection(*args, **kwargs)
 File "C:\Users\myuser\AppData\Local\Continuum\anaconda3\lib\site-packages\pyhive\hive.py", line
 192, in __init__self._transport.open()File
 "C:\Users\myuser\AppData\Local\Continuum\anaconda3\lib\site-packages\thrift_sasl\__init__.py", line
 79, in open message=("Could not start SASL: %s" % self.sasl.getError()))
 thrift.transport.TTransport.TTransportException: Could not start SASL: b'Error in sasl_client_start
 (-4) SASL(-4): no mechanism available: Unable to find a callback: 2'

My system detailes:
OS: Windows 10 Pro
Python version: Python 3.7.4
Distribution: Anaconda, Inc. on win32

A: I found a way to work around the problem.
Actions taken:

*

*Installed VirtualBox with Ubuntu OS on my PC.

*Run Ubuntu as root.

*Installed python, pip3 and the relevant libraries(pyhive, sasl, thrift_sasl, and thrift)

*Run my code - works great!

My conclusion that my problem caused due to security(I am not an admin on my station) and windows issues.


text:
Q: How to generate a dropdown input with a Django ModelForm? I have the following model:
from django.db import model

class Fruit(models.Model):
    fruit_name = models.CharField(max_length=100)

And A form like this:
from django import forms
from .models import SomeModel

class FruitForm(forms.ModelForm):
    some_input = forms.CharField(max_length=100)
    class Meta:
        model = Fruit
        fields = ['fruit_name']

This guide shows me how to create a dropdown like this:
fruit = [
    ('orange', 'Oranges'),
    ('cantaloupe', 'Cantaloupes'),
    ('mango', 'Mangoes'),
    ('honeydew', 'Honeydews'),
]
class TestForm(forms.Form):
    some_input = forms.CharField(max_length=100)
    favorite_fruit = forms.CharField(widget=forms.Select(choices=FRUIT_CHOICES))

What I want to happen is for the key/value tuple list to generate based on the fruit_id and fruit_name columns of the Fruit model, without the need to manually insert the data into the FruitForm.
What am I missing here?

A: Usually you do that with a ModelChoiceField [Django-doc]:
from django import forms

class TestForm(forms.Form):
    some_input = forms.CharField(max_length=100)
    favorite_fruit = forms.ModelChoiceField(queryset=Fruit.objects.all())
In your Fruit model, you then implement the __str__ method to decide how to render your fruit. Here that would be:
from django.db import model

class Fruit(models.Model):
    fruit_name = models.CharField(max_length=100)

    def __str__(self):
        return self.fruit_name
You can alter the queryset= parameter, for example to filter the queryset in advance. For example if you only want to show Fruit that starts with an A, you can filter like:
from django import forms

# example: only show fruit that starts with an A
class TestForm(forms.Form):
    some_input = forms.CharField(max_length=100)
    favorite_fruit = forms.ModelChoiceField(
        queryset=Fruit.objects.filter(fruit_name__startswith='A')
    )


text:
Q: Purely relational structures in 0-1 law I'm trying to understand 0-1 law for random graphs. I think I get most of it, but I don't get one thing:
We assume that structures have to be purely relational (no constants or functions). That means that there are no 0-1 law for algebra (in first order logic).
I get why constants 'breaks' this theorem for random graphs (end of 2.2 in http://web.mit.edu/joshuah/www/projects/zeroone.pdf), but I struggling with concept, why functions are problematic.
I think that we could define function $F(v) = \frac{1}{2}$ and than 0-1 law wouldn't be fulfilled, but it looks 'sketchy' for me.
What is the logic behind limiting structures to purely relational in 0-1 law?

A: We can consider asymptotic properties even when we have function symbols. However in the general case where we consider all such finite structures there are no $0-1$ laws.
To be specific: In the case where we have unary function symbols we have only a convergence law, i.e. not 0-1 but still convergence in the probabilities, while in the case of at least one binary function symbol we do not even have convergence. See this article for reference:
K.J. Compton, C.W. Henson, S. Shelah, Nonconvergence, Undecidability, and
intractability in asymptotic problems, Annals of Pure and Applied Logic 36 (1987) 207-224.
The general statements, especially about binary and larger symbols is quite involved, however we can easily see that we do not have a $0-1$ law in the case of a single unary function symbol by looking at the following nice example:
Note the formula $\varphi$ which stands for $\exists x (f(x)= x)$. What is the assymptotic probability of $\varphi$? If we assume that we have a finite structure $M$ with universe $\{1,\ldots, n\}$ then the probability that $f(i)\neq i$ is $1-\frac{1}{n}$. This probability is independent for each $i$. Thus the probability that $\varphi$ is false in $M$ is $(1-\frac{1}{n})^n$. Hence the assymptotic probability of $\varphi$ being false is
$$\lim_{n\to\infty} \left(1-\frac{1}{n}\right)^n = \frac{1}{e}$$
Thus $\varphi$ has asymptotic probability $1-\frac{1}{e}$, and thus we clearly do not have a $0-1$ law.


text:
Q: Is it valid to use a function in reducer? I want to use a function in my reducer.
I need this for sorting. I import this function from another file and all works well. But a question is: Is it valid to import and use functions from somewhere in a reducer?

A: Absolutely, as long as your functions are pure functions (so that your reducer remains pure as well). Using sub functions is a great way to keep your reducer readable and maintainable when it doesn't make sense from a state modeling perspective to break things out into a sub-reducer.
Just make sure your sub function doesn't modify the state object but rather that it returns a new sorted object to assign as the next state.

A: Something like you can use in you codebase
 import  { helperFunc } from '../helper/';

// reducer function
const reducer = () => {
   switch(action.type){
      case whatever:
        const helperfunc = helperFunc();
   }
}

A: You can, So basically reducers are pure function's. It is used to handle state mutations in redux. There is no problem of using reducer exported from any file. But the main problem arises when you're not using pure functions which will eventually lead to improper state mutations.
PS : pure functions are those which takes a parameter and returns an output without modifying the original input parameter but by using spreading or destructuring e.t.c


text:
Q: why do I get error when installing package in R? I am trying to install and run 'KoNLP' in my local R server.
but somehow I am keep getting error as below
 Error: package or namespace load failed for 'KoNLP':
    .onLoad failed in loadNamespace() for 'KoNLP', details:
    call: fun(libname, pkgname)
    error: You cann't parse resource files based on UTF-8 on rJava.
    Please reload KoNLP first than any other packages connected with
    rJava.

I installed java and assigned java home using
Sys.setenv(JAVA_HOME =
 '/Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home/jre')
dyn.load('/Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home/jre/lib/server/libjvm.dylib')

I don't know why I am keep getting this error.
Can some one please help me out?
Thanks!

A: if(dir.exists(paste(Sys.getenv("PROGRAMFILES"), "\\Java\\", sep = ""))){
  Javapath <- paste(Sys.getenv("PROGRAMFILES"), "\\Java\\", sep = "")
  Javapath <- paste(Javapath, list.files(path = Javapath, pattern = "jdk"), "\\",sep = "")
  if(grepl("jdk", Javapath)){
    options(java.home=Javapath[which.max(gsub(".*jdk[0-9]+\\.[0-9]+\\.[0-9]+_|\\\\$", "", Javapath))])
  }else{
    Javapath <- paste(Sys.getenv("PROGRAMFILES"), "\\Java\\", sep = "")
    Javapath <- paste(Javapath, list.files(path = Javapath, pattern = "jre"), "\\",sep = "")
    options(java.home=Javapath[which.max(gsub(".*jre[0-9]+\\.[0-9]+\\.[0-9]+_|\\\\$", "", Javapath))])
  }
}else if(dir.exists(paste(Sys.getenv("PROGRAMFILES(x86)"), "\\Java\\", sep = ""))){
  Javapath <- paste(Sys.getenv("PROGRAMFILES(x86)"), "\\Java\\", sep = "")
  Javapath <- paste(Javapath, list.files(path = Javapath, pattern = "jre"), "\\",sep = "")
  options(java.home=Javapath[which.max(gsub(".*jre[0-9]+\\.[0-9]+\\.[0-9]+_|\\\\$", "", Javapath))])
}

Maybe u can try to set options(java.home="path to java")


text:
Q: Getting following error on running build.xml at taskdef level On running build.xml, getting following error.
build.xml:147: taskdef class com.sun.tools.xjc.XJCTask cannot be found
Tried giving the executable permission to lib folder and all jar files but still no luck
<taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
    <classpath>
        <fileset dir="${lib.dir}" includes="*.jar" />
    </classpath>
</taskdef>

<taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport">
    <classpath>
        <fileset dir="${lib.dir}" includes="*.jar" />
    </classpath>
</taskdef>

on mouse hover on taskdef in build.xml, shows following warning
taskdef class com.sun.tools.xjc.XJCTask cannot be found using the classloader AntClassLoader


text:
Q: Crashes after waking from sleep - lost sync page write I have a laptop running Ubuntu 22.04 that is crashing every time it wakes up from sleep. After waking, it initially seems fine but as soon as I try to do anything, it crashes.
Errors appearing
EXT4-fs error (device dm-1): __ext4_find_entry:1635: inode  comm nmbd  reading directory lblock o
Buffer I?O error on dev dm-1, logical block 0 lost sync page write

Where dm-1 is mapped to my system-root.
I also get this log,
update-notifier.desktop[9564]: Cannot stat file /proc/8282/fd/4: Permission denied

Which leads me to think that my drive went into some kind of read-only mode.
I have an nvme drive installed (samsung 970 evo plus) and I tried updating the drivers. I also opened up laptop to make sure drive was seated properly.
Running smartctl -a /dev/nvme0n1 does not show any issues as well.
Error Information (NVMe Log 0x01, 16 of 64 entries)
No Errors Logged

My nvme drivers are also up to date.

So I guess my question is if my this looks like a hardware issue and if so, on the drive's side or on the actual laptop? It is a fairly new computer but did get a little turbulence while I have been traveling with it.
Also any other suggestions for what I should be looking at if it is not.
Thank you for your help!


text:
Q: What does "a man of comforts" mean? What does it mean when we say someone is "not a man of comforts" ? Does this mean he's not a rich man?

A: That's one meaning.  "Man of comforts" is a rather old-fashioned expression, meaning a person who is accustomed to having the "finer things in life" about himself, so by extension well-off to the point of being wealthy.  So, a person who is "not a man of comforts" is either a well-off person of simple tastes, or a poor person.
A little research yields examples that illustrate the different uses (first, the poor man):

One day, before the city
      Of Brussels, in Brabant,
      We saw with fear and pity
      This man of comforts scant,
– The Ladies' Garland and Family Magazine, 1846

and (the well-off man)

Tiernan, it proved, was a man of comforts, holding a well-padded county job.
–  Mounted Justice: True Stories of the Pennsylvania State Police, 1922

and (the well-off man with simple tastes)

Robert Pattinson of 'Twilight' not a Man of Comforts
Source: The Examiner

A: It mostly means the speaker/writer is seriously out of touch with contemporary English usage. There are only 7 instances of "a man of comforts" in Google Books, so it's obviously difficult to say the words have any inherent special meaning beyond the literal interpretation.
In fact, the earliest (1660) of those 7 written instances apparently does refer directly to comforts as elements of cheer in an otherwise woeful life. And it would be perfectly possible for someone of modest means to say...

"Why would I want to win the Lottery? I have all the comforts of life in my own little home already"

Of course, a richer man might have more comfortable "comforts of life" than the "poor, but content" man. But the above usage isn't uncommon, so it's not unreasonable to interpret OP's phrase as meaning a person who both has and appreciates the comforts of life - indicating an attitude to "comfortable things" rather than possession of the means with which to buy the best ones.

But most likely if you do come across the expression used today, it'll be a "pseudo-archaic" allusion to...

comfortably off - rich enough to pay for everything you need

...which is a "current expression".


text:
Q: Change state of mapped favorite buttons I am having trouble with a favorite button in my app.
I have set it up to save the data in a favorites array in my database, and can display that data in a separate component. The issue I am having is when I press the button it changes every button in the mapped data.
Here is the code for the button
export default function ShowRecords() {
  const classes = recordFormStyles();
  const url = " http://localhost:5000/record";

  //get userData state to use in useEffect

  //set state for showing records in database and opening/closing modals

  const [newRecords, newRecordData] = React.useState([]);

  const [editOpen, handleEditModal] = React.useState(false);

  const [addModalOpen, handleAddModal] = React.useState(false);

  //set state for edit records

  const [title, setTitle] = React.useState("");

  const [artist, setArtist] = React.useState("");

  const [rating, setRating] = React.useState("");

  const [genre, setGenre] = React.useState("");

  const [description, setDescription] = React.useState("");

  const [userId, setUserId] = React.useState("");

  //set state for favorite icon

  const [favorite, setFavorite] = React.useState([]);

  //functions to control state

  const handleAddModalOpen = () => {
    handleAddModal(true);
  };

  const handleCloseAddModal = () => {
    handleAddModal(false);
  };

  const handleIsEditModalClose = () => {
    handleEditModal();
  };

  //fetch record data

  const fetchData = async () => {
    const result = await axios.get(
      "http://localhost:5000/record/get",
      authToken
    );
    newRecordData(result.data);
    console.log(result.data);
  };

  //check if favorite is in local storage

  React.useEffect(() => {
    fetchData();

    console.log("data");
  }, []);

  // see if user is logged in already, if not set a token and userData

  // delete records

  const deleteRecord = async (_id) => {
    const deleteRecords = {
      _id: newRecords._id,
      title: newRecords.title,
      artist: newRecords.artist,
      rating: newRecords.rating,
      genre: newRecords.genre,
      description: newRecords.description,
    };

    await axios
      .delete("http://localhost:5000/record/" + _id, deleteRecords)
      .then((result) => {
        const refresh = newRecords.filter((result) => result._id !== _id);
        newRecordData(refresh);
      });
  };

  //functions for controlling edit record state

  const editRecord = (_id, title, artist, rating, genre, description) => {
    setUserId(_id);
    setTitle(title);
    setArtist(artist);
    setRating(rating);
    setGenre(genre);
    setDescription(description);
    handleEditModal(true);

    console.log(title);
  };

  //functions for setting favorite state and color and post request to add favorite

  const deleteFavorite = (_id) => {
    setFavorite([]);
  };

  // post request to add favorite

  const handleFavorite = (_id, title, artist, rating, genre, description) => {
    const favorites = {
      _id: _id,
      title: title,
      artist: artist,
      rating: rating,
      genre: genre,
      description: description,
    };

    const addFavorite = () => {
      axios
        .post("http://localhost:5000/favorite/add", favorites, authToken)
        .then((res) => localStorage.setItem("favorite", res.data));
    };

    addFavorite();
    setFavorite(title);

    console.log(title);
  };

  return (

      {/* set props */}

      <Favorites />
      <AddRecord
        isAddModalOpen={addModalOpen}
        handleIsAddModalClose={handleCloseAddModal}
        addNewRecords={newRecords}
        handleIsAddModalOpen={handleAddModal}
        refreshRecordData={newRecordData}
      />
      <EditRecords
        editModalOpen={editOpen}
        handleCloseEditModal={handleIsEditModalClose}
        editUserId={userId}
        editTitle={title}
        editArtist={artist}
        editRating={rating}
        editGenre={genre}
        editDescription={description}
        editTitleState={setTitle}
        editArtistState={setArtist}
        editRatingState={setRating}
        editGenreState={setGenre}
        editDescriptionState={setDescription}
        editUrl={url}
        editFetchData={fetchData}
        editNewRecordData={newRecordData}
      />
      <Button
        className={classes.addButton}
        onClick={() => handleAddModalOpen(true)}
      >
        Add Record
      </Button>

        <Grid container spacing={10} style={{ padding: "24px" }}>
          {newRecords.length > 0 &&
            newRecords.map((element) => (
              <Grid key={element._id} item xs={12} sm={6} md={4} lg={4} xl={2}>
                <Card className={classes.root}>
                  <CardContent>
                    <>
                      {favorite ? (
                        <IconButton
                          onClick={() => deleteFavorite(!favorite)}
                          className={classes.favoriteOn}
                        >
                          {" "}
                          <StarRateIcon className={classes.favoriteYellow} />
                        </IconButton>
                      ) : (
                        <IconButton
                          onClick={() =>
                            handleFavorite(
                              element._id,
                              element.title,
                              element.artist,
                              element.rating,
                              element.genre,
                              element.description
                            )
                          }
                          className={classes.favoriteOff}
                        >
                          {" "}
                          <StarOutlineIcon
                            className={classes.favoriteGrey}
                          />{" "}
                        </IconButton>
                      )}
                    </>
                    <Typography gutterBottom variant="h6">
                      {element.title}
                    </Typography>
                    <Typography variant="body2" color="inherit" component="p">
                      Artist: {element.artist}
                    </Typography>
                    <Typography variant="body2" color="inherit" component="p">
                      Rating: {element.rating}
                    </Typography>
                    <Typography variant="body2" color="inherit" component="p">
                      Genre: {element.genre}
                    </Typography>
                    <Typography variant="body2" color="inherit" component="p">
                      Description: {element.description}
                    </Typography>
                  </CardContent>

                  <CardActions>
                    <Button
                      onClick={() =>
                        editRecord(
                          element._id,
                          element.title,
                          element.artist,
                          element.rating,
                          element.genre,
                          element.description
                        )
                      }
                      size="small"
                      color="inherit"
                    >
                      Edit
                    </Button>
                    <Button
                      onClick={() => deleteRecord(element._id)}
                      size="small"
                      color="inherit"
                    >
                      Delete
                    </Button>
                  </CardActions>
                </Card>
              </Grid>
            ))}
        </Grid>

  );
}

I have tried assigning an _id, or title or whatever to the setFavorite() method. This will Toggle the individual card, but if I click on the button it will toggle the rest of the buttons in the mapped data. I have tried making the button have its on state like this
const [click, setClick] = React.useState(false)

As you can see I have tried saving it to localStorge, not sure if I am doing that right.
this does the exact same thing.
So my question is how, how do i control the state of the button in my mapped data, so it will persist through my app?? I hope this makes sense, I am very new to all of this and am stuck on this. Thank you in advance.

A: I figured this one out on my own as well, I am learning....
This is for anyone with the same question, which I could not find the answer too.
I simply moved the button to its own component, and let that component control the state. I was making things way to complicated


text:
Q: How to replace text in  using jquery
  Auto zoom
  <input type="checkbox" class="js-switch" id="autoZoom" data-switchery="true" style="display: none;">

I have this code above, I want to replace "Auto zoom" to "Test", how do I do that?
$("#div label:contains('Auto zoom')").text("Test");

I tried using the code above, which is obviously not working, it will remove the input type checkbox behind too...

A: The easiest way to do this would be to wrap the text in another element, like a span, then change the text().
Assuming you cannot change the HTML, then you can do what you require by using contents() and retrieving the first textNode, like this:

var label = $('label').contents().filter(function() {
  return this.nodeType == 3 && this.nodeValue.trim();
})[0];

label.nodeValue = label.nodeValue.replace('Auto zoom', 'Test');
.switchery-small {
  box-shadow: rgb(223, 223, 223) 0px 0px 0px 0px inset;
  border-color: rgb(223, 223, 223);
  background-color: rgb(255, 255, 255);
  transition: border 0.4s, box-shadow 0.4s;
}

.switchery-small small {
  left: 0px;
  transition: background-color 0.4s, left 0.2s;
}

  Auto zoom Foo Bar
  <input type="checkbox" class="js-switch" id="autoZoom" data-switchery="true" style="display: none;">

Also note that I moved the inline style attribute out to rules in an external stylesheet. This is much better as it de-clutters the HTML and separate the HTML from the styling.

A: I would recommend wrapping your text around span tag.

$(".labelTitle").text("Test");

Auto zoom
<input type="checkbox" class="js-switch" id="autoZoom" data-switchery="true" style="display: none;">

A: Try Code:
Just Remove # and Div

Auto zoom <input type="checkbox" class="js-switch" id="autoZoom" data-switchery="true" style="display: none;">

A: You have to select the  with:
$("label:contains('Auto zoom')").text('Test');

With your jquery:

$('#div')...

You are selecting a element with id='div'. If you can put a id or class in the label element, is too much easy, like:
 Auto zoom...
Then you can do like:
$('#label_test').text("Test");

Hope it helps!


text:
Q: WebStorm does not resolve aliases when Webpack is configured from Expo's createWebpackConfigAsync I have a React Native Web project using Expo. I have added aliases to make import statements easier to read and manage. Expo, as part of its configuration, has its own Webpack configuration, which can be modified using the documentation found here. This works, and the aliases resolve correctly when the project is built/run. However, WebStorm fails to resolve the aliases in it's intellisense after.
For example:
import userSlice from "@store/User";  // Hovering over "@store/User" will show warning: Module is not installed

webpack.config.js
let path = require("path");
const createExpoWebpackConfigAsync = require("@expo/webpack-config");

const aliases = {
    '@store': path.resolve(__dirname, '/src/store/'),
};

module.exports = async function (env, argv) {
    env.mode = "development"
    const config = await createExpoWebpackConfigAsync(env, argv);

    config.resolve.alias = {
        ...aliases,
        ...config.resolve.alias,
    };

    return config
};

There is no output in the Event Log that indicates an error.
Thinking that the env properties might somehow be different, I also tried manually setting these to the same values that are present when building from a terminal. I've also tried creating a simple Webpack config without Expo, and WebStorm does correctly resolve that.

A: Can be related to WEB-36182; you can check your idea.log file (Help > Show Log in ...) to see if any errors are thrown on webpack evaluation.
I'd suggest trying a workaround suggested for VSCode (configure the path mapping in jsconfig.json) - this should work in WebStorm


text:
Q: Como aumentar um input text e fazer quebra de linha automatica Olá, como pode ver na imagem, o input esta maior que a parte que digito o texto e caso eu continue digitando ele não faz a quebra de linha, oque devo fazer ??

A: Você não pode. O único elemento HTML feito pra ter várias linhas é a <textarea>:
<textarea cols="30" rows="5"></textarea>

A partir do HTML 5 você pode usar o atributo wrap="hard" pra forçar a quebra de linha automática.


text:
Q: Webpack compiler failing I am new to react and webpack, I have an app that I want to import, and at the time of doing the bundle with the webpack the following error appears:

*ERROR in ./src/index.js 7:16 Module parse failed: Unexpected token (7:16) You may need an appropriate loader to handle this file type,
  currently no loaders are configured to process this file.
  Seehttps://webpack.js.org/concepts#loaders | import * as serviceWorker
  from '../src/serviceWorker'; |

ReactDOM.render (, document.getElementById ('root')); | | serviceWorker.unregister ();*

My index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import '../src/index.css';
import App from '../src/App';
import * as serviceWorker from '../src/serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();

My package.json:
{
  "name": "test1",
  "version": "1.0.0",
  "description": "test",
  "main": "webpack.config.js",
  "dependencies": {
    "babel-cli": "^6.26.0",
    "cs": "^1.0.3",
    "css": "^2.2.4",
    "fsevents": "^2.0.7",
    "material-table": "^1.50.0",
    "react": "^16.9.0",
    "react-dom": "^16.9.0",
    "react-scripts": "^3.1.2",
    "typescript": "^3.6.3",
    "webpack-cli": "^3.3.9",
    "webpack": "^4.40.2"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.6",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^3.2.0",
    "style-loader": "^1.0.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

I have tried to install every module to see if it works, but facing same issue.
Can someone help me?


text:
Q: Strange BIOS int 10h ah=0eh teletype output on Sony Vaio I am having something bizarre on a Sony Vaio when playing with a boot sector. I am compiling some code with nasm, copying it to a usb stick and booting that on the Vaio.
I am running this code:
[ORG 7c00h]
cld
cli

mov bh, 0
mov ah, 0Eh
mov al, '0'
int 10h
mov bh, 0
mov ah, 0Eh
mov al, '1'
int 10h
mov bh, 0
mov ah, 0Eh
mov al, '2'
int 10h
mov bh, 0
mov ah, 0Eh
mov al, '3'
int 10h
mov bh, 0
mov ah, 0Eh
mov al, '4'
int 10h
mov bh, 0
mov ah, 0Eh
mov al, '5'
int 10h
mov bh, 0
mov ah, 0Eh
mov al, '6'
int 10h
mov bh, 0
mov ah, 0Eh
mov al, '7'
int 10h
mov bh, 0
mov ah, 0Eh
mov al, '8'
int 10h
mov bh, 0
mov ah, 0Eh
mov al, '9'
int 10h

mov cl, 192
loop:
    mov al, cl
    add al, 32
    int 10h
    dec cl
    jne loop

    hlt

times 510-($-$$) db 0
dw 0AA55h

Qemu outputs this:
SeaBIOS (version rel-1.14.0-0-g155821a1990b-prebuilt.qemu.org)

iPXE (http://ipxe.org) 00:03.0 CA00 PCI2.10 PnP PMM+07F8F390+07EEF390 CA00

Booting from Hard Disk...
0123456789α▀▐▌▄█┌┘╪╫╓╒╘╙╥╤╨╧╬═╠╦╩╔╚╟╞┼─├┬┴└┐╛╜╝╗║╣╕╖╢╡┤│▓▒░»«¡¼½¬⌐¿ºªÑñúóíáƒ₧¥£¢
ÜÖÿùûòöôÆæÉÅÄìîïèëêçåàäâéüÇȣ~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLK
JIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"!

However, the Vaio does this:

The start of the output (0122256789) is incorrect. Also, it seems to be timing dependent. For example, if I add a bunch moves after the outputting of 1:
...
mov al, '1'
int 10h

mov ax, 0
mov ax, 0
mov ax, 0
mov ax, 0
mov ax, 0

mov bh, 0
mov ah, 0Eh
mov al, '2'
...

Then the output is 01456789...
What is going on?
Edit:
Indeed, as mentioned in the comments, this was related to a missing Boot Parameter Block (BPB). Running the code from Custom bootloader booted via USB drive produces incorrect output on some computers, I got this:
7C00: EB 3C 90 AA AA AA AA AA
7C08: AA AA AA AA AA AA AA AA
7C10: AA AA AA AA AA AA AA AA
7C18: AA AA AA AA 00 00 00 00
7C20: AA AA AA AA 00 AA AA AA
7C28: AA AA AA AA AA AA AA AA
7C30: AA AA AA AA AA AA AA AA
7C38: AA AA AA AA AA AA

To confirm, I edited the boot sector, put zeros in the places where the Vaio BIOS would and disassembled the code. The result confirmed that, with the code above, the instructions that load the character values were getting nuked. So this explains everything.


text:
Q: Why this pie chart legend d3.js does not work? I made a pie chart and it's works well:
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;

var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

var percentageFormat = d3.format("%");

var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);

var pie = d3.layout.pie()
.sort(null)
.value(function(d) {
    return d.values;
});

var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

d3.json("staff.json", function(error, json_data) {

var data = d3.nest()
.key(function(d) {
  return d.sex;
})
.rollup(function(d) {
  return d.length;
}).entries(json_data);

data.forEach(function(d) {
d.percentage = d.values / json_data.length;
});

console.log("data variable", data);
console.log("pie(data)", pie(data));

var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc")
.on('mouseover', function() {
  var current = this;
  var others = svg.selectAll(".arc").filter(function(el) {
    return this != current
  });
  others.selectAll("path").style('opacity', 0.8);
})
.on('mouseout', function() {
  var current = this;
  d3.select(this)
    .style('opacity', 1);
  var others = svg.selectAll(".arc").filter(function(el) {
    return this != current
  });
  others.selectAll("path").style('opacity', 1);
});

g.append("path")
.attr("d", arc)
.style("fill", function(d, i) {
  return color(i);
});

g.append("text")
.attr("transform", function(d) {
  return "translate(" + arc.centroid(d) + ")";
})
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) {
  console.log("d is", d);
  return percentageFormat(d.data.percentage);
});
});

This is file staff.json:
    [{
    "Position" : "Programmer",
        "Name" : "Giacomo Gulizzoni",
         "Age" : 37,
         "Sex" : "Male",
     "Project" : "SmartFactory"
}, {
    "Position" : "Tester",
        "Name" : "Marko Botton",
         "Age" : 34,
         "Sex" : "Male",
     "Project" : "SmartFactory"
}, {
    "Position" : "Tester",
        "Name" : "Mariah Maclachian",
         "Age" : 37,
         "Sex" : "Female",
     "Project" : "SmartFactory"
}, {
    "Position" : "Tester",
        "Name" : "Valerie Liberty",
         "Age" : 25,
         "Sex" : "Female",
     "Project" : "SmartProject"
}, {
    "Position" : "Programmer",
       "Name " : "Guido Jack Gulizzoni",
         "Age" : 22,
         "Sex" : "Male",
I wanted to add legends and following a tutorial I added some code for that. After that it doesn't work any more.
Could you give me a hint?


text:
Q: How to do left outer joins with DbLinq and SQLite? I tried
db.Table1.GroupJoin(db.Table2,
    t1 => t1.Id,
    t2 => t2.t1Id,
    (t1,g) => new { t1, g })
  .Where(item => !item.g.Any())
  .Select(item => item.t1);

But it returned 0 results. I'm trying to write something that generated the following SQL code (or something similar)
SELECT t1.*
FROM Table1 as t1
LEFT OUTER JOIN Table2 as t2
ON t1.Id = t2.t1Id
WHERE IsNull(t2.Id);

A: It looks like your desired result is to identify the items from Table1 that had no results during the left outer join with Table2.
In fluent notation, the approach would be similar to this:
var query = db.Table1.GroupJoin(db.Table2,
                t1 => t1.Id,
                t2 => t2.t1Id,
                (t1, joined) => new { t1, joined }
            )
            .SelectMany(r => r.joined.DefaultIfEmpty(), (r, j) => new
            {
                r.t1,
                j
            })
            .Where(r => r.j == null)
            .Select(r => r.t1);

In query syntax:
var query = from t1 in db.Table1
            join t2 in db.Table2 on t1.Id equals t2.t1Id into joined
            from j in joined.DefaultIfEmpty()
            where j == null
            select t1;


text:
Q: iPhone UiWebView images with absolute path I display some html in my UIWebView and I have in my html references to images like: '/images/test1.gif' etc.
I display this in that way:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[myWebView loadHTMLString:someHtml baseURL:baseURL];

I've also added all required images to my Xcode project, into 'images' directory. The problem is, that, as far as I can see, the baseUrl ends with '/', and path to the images starts with '/' (it's absolute). All that makes my images doesn't appear.
I've noticed, that if I change, in html, path to images, to for example 'images/test.gif', the image will show up, but I want (if possible) to avoid changing all image paths in html from absolute to relative, becasue this html is imported from some database, and in case of another import I would have to change it again.

A: Have you tried clipping the slash from the end of baseURL?  I should hope the web view is smart enough to add a slash where needed, despite blindly concatenating two strings that result in a double slash.


text:
Q: Не работает клавиатура после выхода из сна (закрытие крышки ноутбука) у меня довольно частая проблема, которую я не могу решить.
На ноуте Sony Vaio стоит новая Ubuntu 18.04.3 LTS. При закрытии крышки ноута и перехода в сон (а затем открытии), встроенная клавиатура перестает работать. Только тачпад, и то, секунда через 7-10. Система как бы висит эти секунды (стоит SSD, 4 Гб память, процесор i5). Включается, только если нажать, "сменить пользователя" и опять залогиниться под ним же. Если просто нажать на кнопку "заблокировать", то такая проблему не всречается.
Советы в интернете сводяться к устновке в drup параметров
GRUB_CMDLINE_LINUX_DEFAULT=" i8042.nopnp noacpi nolapic atkbd.reset quiet splash"

что мне не помогло, от слова совсем.
Можете пожалуйста подсказать, как решить эту проблему.
Update
После перебора параметров, нашел статью о том, как при похожей проблеме "удалили" rfkill файл. Мне это "помогло". Клавиатура, да и в принципе пробуждений происходит мгновенно (wi-fi конечно требует время на подключение, но это не критично), но систем начинает жутко висеть. gnome-shell процесс забирает все ресурсы. Потребление CPU сразу поднимается на 100%. Вернув файл на место, проблема с CPU осталась, но клавиатура работает. Что за магия?  Sony дружит только с windows?


text:
Q: What's faster creating temp table or UNION ALL? I'm trying to make some query in MS SQL Server 2008 R2 faster and there are 2 ways:
1) By creating temp table:
IF OBJECT_ID('tempdb..#Rec') IS NOT NULL
BEGIN
DROP TABLE #Rec
END

CREATE TABLE #Rec
(
    ID int NULL,
    DateBeg datetime NULL,
    DateEnd datetime NULL,
    Artist varchar(200) NULL,
    DescriptionFull text NULL,
    ActionPlaceID int NULL,
    ActionTypeID smallint NULL,
    Visible tinyint NULL,
    Created datetime NULL,
    DateList varchar(4000) NULL,
    DatesAsPeriod tinyint NULL,
    ShowReservLegend tinyint NULL,
    ProviderID int NULL
)

INSERT INTO #Rec
SELECT ID,
    DateBeg,
    DateEnd,
    Artist,
    DescriptionFull,
    ActionPlaceID,
    ActionTypeID,
    Visible,
    Created,
    DateList,
    DatesAsPeriod,
    ShowReservLegend,
    ProviderID
FROM [ConcertDev].[dbo].[T_Action]
WHERE DateBeg BETWEEN '2012-01-01' AND '2012-06-01'

INSERT INTO #Rec
SELECT ID,
    DateBeg,
    DateEnd,
    Artist,
    DescriptionFull,
    ActionPlaceID,
    ActionTypeID,
    Visible,
    Created,
    DateList,
    DatesAsPeriod,
    ShowReservLegend,
    ProviderID
FROM [ConcertDev].[dbo].[T_Action]
WHERE DateBeg BETWEEN '2013-01-01' AND '2013-06-01'

SELECT * FROM #Rec

2) By using UNION ALL:
SELECT ID,
    DateBeg,
    DateEnd,
    Artist,
    DescriptionFull,
    ActionPlaceID,
    ActionTypeID,
    Visible,
    Created,
    DateList,
    DatesAsPeriod,
    ShowReservLegend,
    ProviderID
FROM [ConcertDev].[dbo].[T_Action]
WHERE DateBeg BETWEEN '2012-01-01' AND '2012-06-01'

UNION ALL

SELECT ID,
    DateBeg,
    DateEnd,
    Artist,
    DescriptionFull,
    ActionPlaceID,
    ActionTypeID,
    Visible,
    Created,
    DateList,
    DatesAsPeriod,
    ShowReservLegend,
    ProviderID
FROM [ConcertDev].[dbo].[T_Action]
WHERE DateBeg BETWEEN '2013-01-01' AND '2013-06-01'

I've expected UNION ALL could be much faster, but it wasn't. It's faster for only 1 second.
The number of records is 6147.
By using temp table method the time of execution is 18 seconds.
By using UNION ALL method the time of execution is 17 seconds.
So, is this correct approach to speed up query?

A: You can do like this also:
SELECT ID,
DateBeg,
DateEnd,
Artist,
DescriptionFull,
ActionPlaceID,
ActionTypeID,
Visible,
Created,
DateList,
DatesAsPeriod,
ShowReservLegend,
ProviderID

into #Rec

FROM [ConcertDev].[dbo].[T_Action]
WHERE DateBeg BETWEEN '2012-01-01' AND '2012-06-01'
OR
DateBeg BETWEEN '2013-01-01' AND '2013-06-01'

SELECT * FROM #Rec
DROP TABLE #Rec

A: Probably, provided that you use UNION ALL. By default UNION implies DISTINCT
which could cause a extra sorting step that could be equally expensive
as the temp table.
But there are always a lot of "it depends" when it comes to performance,
so if there are some deviations from the scenario as you described it,
the real answer may be different.
One advantage with temp tables i can think of is that you can apply indexes to them. So that should help when dealing with lots of data where you need to get results back as quick as possible.


text:
Q: ORA-04067: not executed, package body does not exist I am working on ASp.net project with backend Oracle DB.
I created a new package with stored procedures to the DB. and Called a stored procedure from package. I am getting following error.
ORA-04067: not executed, package body "WB_APP_MANAGER.WB_PCK_APP_MANAGER" does not exist
ORA-06508: PL/SQL: could not find program unit being called: "WB_APP_MANAGER.WB_PCK_APP_MANAGER"
ORA-06512: at line 1

Please let me know How to solve this issue.
Thanks

A: Your package specification may be in place but your package body seems to be missing. For any package which is executed the package body must also exist.
select object_type
from   dba_objects
where  object_name = 'WB_PCK_APP_MANAGER';

The above query must report both PACKAGE and PACKAGE BODY.
If PACKAGE BODY is not reported by the query you need to create the package body.
create or replace package body WB_PCK_APP_MANAGER as

A: *

*check if the name is correct - you didn't misspelled it;

*check if it is compiled;

*check if WB_APP_MANAGER has proper rights to WB_PCK_APP_MANAGER:

select owner, object_name, object_type
from   dba_objects
where  object_name = 'WB_PCK_APP_MANAGER';


text:
Q: CurrentDb.RecordsAffected returns 0. Why? If I use RecordsAffected with CurrentDb.Execute, it always returns 0. If I first make a instance of a Database object it works properly. Why?
Like this:
Dim Db As Database
Set Db = CurrentDb

Db.Execute "DELETE * FROM [Samples] WHERE Sample=5"
If Db.RecordsAffected = 0 Then
  MsgBox "Error"
End If

Instead of:
CurrentDb.Execute "DELETE * FROM [Samples] WHERE Sample=5"
If CurrentDb.RecordsAffected = 0 Then
  MsgBox "Error"
End If

I'm using Access 2007 and the Microsoft Office 12.0 Access database engine Objects Library.

A: Use With.  Change your code to:
Dim Db As Database
Dim recordAffect = Integer
Set Db = CurrentDb
With Db
  .Execute "DELETE * FROM [Samples] WHERE Sample=5"
  recordAffect = .RecordsAffected
  'If Db.RecordsAffected = 0 Then
  If (recordAffect = 0)  Then
     MsgBox "Error"
  End If
End With

A: Each time you use CurrentDB, it is a new instance.


text:
Q: What is the correct way to effect multiple updates on a Neo4J graph? I am cutting my teeth on Neo4J. I am trying to understand what is the correct way of effecting multiple, simultaneous changes on a Graph DB.
Before I begin, let me clarify that because of a couple of reasons, I have to use Neo4J as an embedded database, in a Java/Scala application and not as a remote server to which I can throw REST calls. Moreover, I have to use Cypher to construct the commands and execute using Neo4J's Java API: exectureQuery
So, here's a piece of code to exemplify what I am trying to do:
val db = new TestGraphDatabaseFactory().newImpermanentDatabase()
val query1 =
  """
    |Create (d: Dish {name:"Fish Curry",from:"India"}),
    |(t: Table {no: 1}),
    |(d)-[r:ORDERED_FROM]->(t)
  """.stripMargin
val query2 =
    """
    |Match (d:Dish {name: "Fish Curry"}),
    |(t: Table {no: 1}),
    |(d)-[r:ORDERED_FROM]->(t)
    |Delete r
    """.stripMargin

val query3 =
  """
   |Match (d:Dish {name: "Fish Curry"}), (t: Table {no: 1})
   |Create (d)-[r:SERVED_AT]->(t)
  """.stripMargin

Let's say I am modelling a typical evening in a restaurant. I choose a particular dish from the menu and place an order for it. At this point, query1 is fired. The nodes and relationships are created.
val v1 = db.execute(query1).resultAsString()
// ... I consume 'v1' appropriately

After some time, the dish is ready and is served. Now, for the graph to to reflect what has happened, following commands are fired:
val v2 = db.execute(query2).resultAsString
val v3 = db.execute(query3).resultAsString

To elaborate (it is perhaps obvious to all the Neo4J experts here anyway), I am severing the relationship of ORDERED_FROM between dish and table, and tying them through a relationship of SERVED_AT.
I have two questions:

*

*Because I am making 2 updates through two separate Cypher queries, I am perhaps missing on the transactional guarantee. Between removal of old Relationship and addition of the new one, the dish is vulnerable to another orthogonal update (perhaps by another thread of execution). If this understanding is correct, then what I must do to prevent it?

*In the example above, the properties of Dish node is hardcoded. But, in practice, these are going to be  variables, their values being assigned at runtime. Therefore, it is possible that either Dish or Table may not be found while query{2,3} are executed. What is the correct way to deal with that? There may not be any exception thrown, if I understand the API correctly.
I have searched through various blogs and other sites to find an answer but I haven't. So, if the answer I am seeking already exists somewhere, please point that out to me.
Any help, is appreciated.

A: You have to start a transaction outside of your query execution. Otherwise Cypher will start an implicit tx just for the one query.
try (Transaction tx= db.beginTx()) {
   db.execute(query1,params).close();
   db.execute(query1,params).close();
   tx.success();
}

note, this uses try-with-resource, otherwise you have to call tx.close() manually.


text:
Q: What Unix command can I use to enforce a limit of 100 files in a folder? I would like to delete the oldest files in a directory, after a limit of 100 files. In other words, I want to ensure that no more than 100 files exist in the directory, and if a limit is exceeded, delete the oldest files after the limit. I don't just want to delete files older than x days, since if this was run on a cronjob, eventually all files would be deleted.
I guess if I were to program this, the pseudo code would be:
list = dir.getFiles()
list.sortByDate()
deleteList = list.getSubList(100, end) // from, to
deleteAll(deleteList)

So what would the appropriate Unix command be? I guess find would be involved somehow with the -exec argument, but I'm not sure about the sorting/limiting aspect.

A: find should not be necessary. If you first go to the right dir,
rm -f `ls -rt | head -n -100`

to specify a path
rm -f `ls -rt /path/to/my/dir | head -n -100`

and for cron (on Ubuntu!)
/bin/rm -f `/bin/ls -rt /path/to/my/dir | /usr/bin/head -n -100`

A command path can be determined using which, e.g.
which ls

Finally, if file names contain spaces, they should be quoted ls -Q then sent to xargs
/bin/ls -Qrt /path/to/my/dir | /usr/bin/head -n -100 | /usr/bin/xargs /bin/rm -f

(tested on Ubuntu, for your tests, replace rm -f with echo to see what is to be deleted)

A: Are you reinventing the wheel called log rotation? If so, use logrotate (on linux systems; other systems will have their own equivalent programs).


text:
Q: android detect when view is over another view I have this layout:

What I want when I move any view of those is to detect if this view is over another view and, if so, call the swap method.
I want to do it when over on half of second view like in this example:

all code is complete, I just want to detect when view is over half view from right or left. My xml code:
<RelativeLayout
    android:id="@+id/mmmm"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="false"
    android:layout_gravity="center">

             <!-- first view -->

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_alignParentTop="true"
                android:layout_alignParentRight="true">

                <customfonts.RoundedImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/pro2"
                    android:layout_alignParentStart="false" />

                <customfonts.MyTextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@drawable/circulo"
                    android:text="1"
                    android:gravity="center_vertical|center_horizontal"
                   />
            </RelativeLayout>

            <!-- end first view -->

            <!-- second view -->

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_alignParentTop="true"
                android:layout_alignParentRight="true">

                <customfonts.RoundedImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/pro2"
                    android:layout_alignParentStart="false" />

                <customfonts.MyTextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@drawable/circulo"
                    android:text="1"
                    android:gravity="center_vertical|center_horizontal"
                   />
            </RelativeLayout>

            <!-- end secondview -->

            <!--  third view -->
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_alignParentTop="true"
                android:layout_alignParentRight="true">

                <customfonts.RoundedImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/pro2"
                    android:layout_alignParentStart="false" />

                <customfonts.MyTextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@drawable/circulo"
                    android:text="1"
                    android:gravity="center_vertical|center_horizontal"
                   />
            </RelativeLayout>

            <!-- end third view -->

        </RelativeLayout>

what i try
          float x1 = v.getX();
          float w1 = v.getWidth();

          float x2 = m.getView().getX();
          float w2 = m.getView().getWidth();

         if((x1+w1 >= x2 &&  x2 > x1)  || (x1 >= (x2 + w2/2) && (x2 + w2) > x1)){

      Log.d("overlay now","index is "+m.getIndex());

       }

this code i try it but its i don't know what the problem of it , it's like give wrong x and position