text:
Q: Increment class instance counter in Python I'm not well versed in Python as I have a Java background.
I have this simple class:
## Class declaration
class SemVersion:
    major: int
    minor: int
    patch: int

    def __init__(self, major, minor, patch):
        self.major = major
        self.minor = minor
        self.patch = patch

    def incrementMinor(self):
        print(self)
        self.minor = self.minor + 1
        return self

    def toString(self):
        return self.major + "." + self.minor + "." + self.patch

    def toSnapshotString(self):
        return self.toString() + "-SNAPSHOT"

The following statement throws an error:
newDevelopVersion = releaseSemVersion.incrementMinor()

Exception:

Traceback (most recent call last):   File
"C:\devenv\java\apps\vsb-letters-transfer-api\release_preprod.py",
line 41, in
newDevelopVersion = releaseSemVersion.incrementMinor()   File "C:\devenv\java\apps\vsb-letters-transfer-api\release_helpers.py",
line 17, in incrementMinor
self.minor = self.minor + 1 TypeError: can only concatenate str (not "int") to str

I'd like to understand how Python can manage not to recognize it as an integer as I declared it as such and just increment the way I asked it.
I'm sure there is a reasonable explanation for it.
I don't see how I asked anywhere to add a string to an int or anything of that nature.
Many thanks.

A: Python doesn't enforce types from annotations. The annotations are primarily for documentation purposes.
You are likely passing in an str to the constructor when you initialize your object which would have made the interpreter think releaseSemVersion.minor is a string instead of an int.

You can avoid this by adding a check in __init__() as follows
def __init__(self, major, minor, patch):
    if not isinstance(major, int):
        raise TypeError('major must by of type int')

    if not isinstance(minor, int):
        raise TypeError('minor must by of type int')

    if not isinstance(patch, int):
        raise TypeError('patch must by of type int')

    self.major = major
    self.minor = minor
    self.patch = patch

A: First of all, some considerations when using Python:

*

*Python do not enforce type, type hints just helps you and others to understand what is expected on some method or function

*Variables and method name must be in snake_case format, following the best practices described on pep8
Now, refactoring your example, you should be able to perform your desired operation with:
class SemVersion:
    major: int
    minor: int
    patch: int

    def __init__(self, major, minor, patch):
        self.major = major
        self.minor = minor
        self.patch = patch

    def increment_minor(self):
        self.minor = self.minor + 1
        return self

    def to_string(self):
        return self.major + "." + self.minor + "." + self.patch

    def to_snapshot_string(self):
        return self.toString() + "-SNAPSHOT"

# Your class instance
develop_vision = SemVersion(
    major=1,
    minor=2,
    patch=3
)

print(f"Initial value of minor: {develop_vision.minor}")

develop_vision.increment_minor()
develop_vision.increment_minor()

print(f"New value of minor: {develop_vision.minor}")

Now, if you want to check your constructor arguments type, pydantic can help you!
# Make sure that your virtual environment is active

$ pip3 install pydantic

Adapt your class to use pydantic validations
from pydantic import BaseModel, StrictInt

class SemVersion(BaseModel):
    major: StrictInt
    minor: StrictInt
    patch: StrictInt

    # You don't need build a constructure anymore, pydantic do it for you

    def increment_minor(self):
        self.minor = self.minor + 1
        return self

    def to_string(self):
        return self.major + "." + self.minor + "." + self.patch

    def to_snapshot_string(self):
        return self.toString() + "-SNAPSHOT"

# Your class instance
develop_vision = SemVersion(
    major=1,
    minor=2,
    patch='10'
)

print(develop_vision)

If you try to run this code, using a string like '10', you will get an exception from pydantic, like this:
Traceback (most recent call last):
  File "/home/jns/Desktop/stack.py", line 23, in <module>
    develop_vision = SemVersion(
  File "pydantic/main.py", line 341, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for SemVersion
patch
  value is not a valid integer (type=type_error.integer)


text:
Q: What does lacked substance mean here? Does it mean lacked the most important ideas?
https://www.ldoceonline.com/dictionary/substance
Gros, however, said the full text of the EU investment agreement ultimately lacked substance. He advised the Biden administration to look beyond the headlines, and see that the content of the deal, which took seven years to negotiate, changed "very little."
Source: https://edition.cnn.com/2021/02/17/economy/europe-china-united-states-trade/index.html

A: The cited example uses the definition...

substance (noun) - importance, seriousness, or relationship to real facts
Example usages:
There is no substance in/to the allegation
This new information gives substance to the stories we have heard

...where to lack means to be without, not to have (something that should be present). Gros thinks the EU investment agreement contains nothing of any significance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to access Microsoft mailboxes using OAuth2 with Chilkat2 I am trying to access some mailboxes using the Pop3 protocol through my works proxy. I can get my oauth token, and access my information using Chilkat2 HTTP Library.
Using this code gets me a response of my profile:
http = chilkat2.Http()
http.AuthToken = accesstoken
http.ProxyDomain = "Some Proxy"
http.ProxyPort = Some Port

answer = http.QuickGetStr("https://graph.microsoft.com/v1.0/me")
print(answer)

which retunrs this

{"@odata.context":"https://graph.microsoft.com/v1.0/$metadata#users/$entity"................ ect

This returns my profile details from the Windows servers so I know my oauth2 token is valid and works.
I then try and use the MailMan protocol to open up my POP3 Mailbox I run in to an authentication error, I run the code below
mailman = chilkat2.MailMan()
mailman.HttpProxyHostname = "Some Proxy"
mailman.HttpProxyPort = Some Port

mailman.MailHost = "outlook.office365.com"
mailman.MailPort = 995
mailman.PopSsl = True
mailman.PopUsername = username
mailman.PopPassword = ""
mailman.OAuth2AccessToken = accesstoken

mailman.Pop3EndSession() #close session as program keeps breaking and leaving session open

success = mailman.Pop3Connect()
if (success != True):
    print(mailman.LastErrorText)
    sys.exit()

# Authenticate..
success = mailman.Pop3Authenticate()
if (success != True):
    print(mailman.LastErrorText)
    sys.exit()

However the authenticate command always returns as false, the Chilkat error log shows as below:
ChilkatLog:
  Pop3Authenticate:
    DllDate: Feb  9 2021
    ChilkatVersion: 9.5.0.86
    UnlockPrefix: Auto unlock for 30-day trial
    Architecture: Little Endian; 64-bit
    Language: Python 3.9.4 (tags/v3.9.4:1f2e308, Apr  6 2021, 13:40:21) [MSC v.1928 64 bit (AMD64)], win32
    VerboseLogging: 0
    Pop3Authenticate:
      username: my username
      popSPA: 0
      greeting: +OK The Microsoft Exchange POP3 service is ready. [TABPADIAUAAyADYANQBDAEEAMAAzADgANgAuAEcAQgBSAFAAMgA2ADUALgBQAFIATwBEAC4ATwBVAFQATABPAE8ASwAuAEMATwBNAA==]
      pop_office365_xoauth2:
        PopCmdSent: AUTH XOAUTH2
        PopCmdResp: +
        auth_xoauth2_response_1: +

        PopCmdSent: <base64 string in XOAUTH2 format>
        PopCmdResp: -ERR Authentication failure: unknown user name or bad password.
        POP3 response indicates failure.
        AUTH_XOAUTH2_response: -ERR Authentication failure: unknown user name or bad password.

      --pop_office365_xoauth2
      POP3 authentication failed
    --Pop3Authenticate
    Failed.
  --Pop3Authenticate
--ChilkatLog

I am at a loss, I have used every combination of scope that should allow me this access with my token, but I cannot get it to work with any of the email libraries in Chilkat; seems to connect fine with the servers but always fails the authentication. Anyone got any idea on this?

A: My guess is that something wasn't setup correctly in Azure, and/or you're not asking for the correct scopes when getting the OAuth2 access token.
This example has comments that describe the App Registration in Azure Active Directory:    https://www.example-code.com/chilkat2-python/office365_oauth2_access_token.asp
At each step, there is a link to the Azure Console screen as I was doing it.
Also, your scope should look like this:
oauth2.Scope = "openid profile offline_access https://outlook.office365.com/SMTP.Send https://outlook.office365.com/POP.AccessAsUser.All https://outlook.office365.com/IMAP.AccessAsUser.All"
There are places in the Microsoft documentation where the scopes are different (or old?).
The interactive 3-legged OAuth2 flow only has to be done once.  After you have the OAuth2 access token, you can continually refresh without user interaction
as shown here:   https://www.example-code.com/chilkat2-python/office365_refresh_access_token.asp
Alternatively, you can try the resource owner grant flow as shown here:
https://www.example-code.com/chilkat2-python/office365_resource_owner_password_credentials_grant.asp
The resource-owner flow is non-interactive and is for apps accessing its own O365 account.
Please let me know if that helps.


text:
Q: Does a process switch affect std::atomic compare and exchange in arm9 processor? I am new to std::atomic in c++ and trying to understand the implementation of compare and exchange operations under ARM processors.I am using gcc on linux.
When i look into the assembly code
    mcr p15, 0, r0, c7, c10, 5
.L41:
    ldrexb  r3, [r2]
    cmp r3, r1
    bne .L42
    strexb  ip, r0, [r2]
    cmp ip, #0
    bne .L41
.L42:
    mcr p15, 0, r0, c7, c10, 5

My understanding is

*

*it takes multiple instructions to do compare and exchange.

*ldrex marks the memory location as exclusive and reads the data.

*strex stores the data and clears the exclusive flag for that
location.

My questions are

*

*does ldrex mark the Virtual addr. as exclusive or the physical address?

*If Process P1 marks the virtual address as exclusive and a process switch occurs to P2, will that virtual addr. be accessible in P2? what will happen if P2 also execute an ldrex on the same address.

*If Process P1 marks the physical address as exclusive and a process switch occurs, when P1 resumes isn't there a chance that the data now resides in a different location in physical memory due to paging.
I am trying to understand this because, i want to do a compare and exchange on a shared memory location accessed by multiple processes.
My c++ function looks like
std::atomic<bool> *flag;
flag = (std::atomic<bool> *) (shm_ptr);
bool temp = false ;
while(!std::atomic_compare_exchange_strong((flag),&temp,true))
{
std::this_thread::yield();
}
// update shared memory
std::atomic_store((flag), false);

A: Yes, it's safe to use lock-free std::atomic<T> on shared memory mapped by different processes, on all mainstream C++ implementations for ARM.
But non-lock-free atomics won't work, because different processes won't share the same table of locks.

An interrupt before the strex completes will cause it to fail.  You don't have to worry about kernel code changing the page tables between ldrex and strex.
Resuming this code in the middle after an interrupt on the same or another CPU will mean the strex simply fails, because it's not executing as part of a "transaction" started by ldrex.

Atomicity is address-free on ARM, and on every normal mainstream system that implements C++11 lock-free atomics.
Everything still works if two threads / processes on different cores have the same physical page mapped to different virtual addresses.  The C++11 standard explicitly recommends that implementations work this way for lock-free std::atomic<T>.  (It stops short of requiring it, because then it would have to define what a process is, and functions for remapping virtual memory.)
This is nearly a duplicate of Are lock-free atomics address-free in practice?.  See that for quotes from the standard and more details.

Modern computer systems ensure that their caches don't have aliasing homonym / synonym problems, because that would cause coherency problems in general, not just for atomic RMWs.  Sometimes this requires cooperation from the OS kernel (e.g. page coloring if one cache index bit comes from the page number instead of just the offset-within-a-page part of the address), but in general caches behave as physical.
(Some early CPUs, like early MIPS, did sometimes use virtually-addressed L1 data caches, but that's not done on systems that can support multiple CPUs, AFAIK.)


text:
Q: iOS Animate height constraint issue I have a problem with the animation of a view after changing it's height constraint. In the screenshot, you can see it's initial value of 120.0.

 The animation works but the constraint update from my second view (the blue one) happens directly and not during the animation. This means that second view jumps to the top directly.
With the following code, I will animate the change of the height constraint:
UIView.animate(withDuration: 3.0, animations: {
    self.heightConstraint?.constant = 0.0
    self.myLabel.alpha = 0.0
    self.layoutIfNeeded()
})

Does anybody know why?

A: self.heightConstraint?.constant = 0.0
self.myLabel.alpha = 0.0
UIView.animate(withDuration: 3.0, animations: {
    self.layoutIfNeeded()
})

It should be like this.

A: For animating constraint changes, you need to write code like below to work.
self.heightConstraint?.constant = 0.0
self.myLabel.alpha = 0.0

UIView.animate(withDuration: 5) {
    self.layoutIfNeeded()
}

A: You need to call self.layoutIfNeeded() before and after updating constraint constant. Change your code to :
self.layoutIfNeeded()

UIView.animate(withDuration: 3.0, animations: {
    self.heightConstraint?.constant = 0.0
    self.myLabel.alpha = 0.0
    self.layoutIfNeeded()
})


text:
Q: Java errors after do-release update I did a release upgrade on my box last night as I had a few other problems that were bugging me on my 14.04 version. The problem is, I'm now getting a Java error when trying to launch my Workbench, no matter if existing or new workspace, I get the same error and the log file contains a bunch of Java errors:
$ cat  /home/test/WindRiver/workbench-3.3/wrwb/platform/x86-linux2/eclipse/test:9999/.metadata/.log
!SESSION 2017-10-06 09:33:14.585 -----------------------------------------------
eclipse.buildId=M20130131-0800/WB20151117-1158
java.version=1.6.0_21
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=linux, ARCH=x86, WS=gtk, NL=en_CA
Command-line arguments:  -os linux -ws gtk -arch x86

!ENTRY org.eclipse.osgi 4 0 2017-10-06 09:33:27.450
!MESSAGE Application error
!STACK 1
java.lang.UnsatisfiedLinkError: com.windriver.core.runtime.jni.Env.setEnv(Ljava/lang/String;Ljava/lang/String;)I
        at com.windriver.core.runtime.jni.Env.setEnv(Native Method)
        at com.windriver.ide.common.core.installregistry.WREnv.setSystemEnv(WREnv.java:805)
        at com.windriver.ide.common.core.installregistry.WRInstallRegistry.initWorkbenchEnvironment(WRInstallRegistry.java:631)
        at com.windriver.ide.common.core.installregistry.WRInstallRegistry.init(WRInstallRegistry.java:484)
        at com.windriver.ide.common.core.installregistry.WRInstallRegistry.getInstance(WRInstallRegistry.java:550)
        at com.windriver.ide.application.UnifiedSWTSwingApplication.checkPreconditions(UnifiedSWTSwingApplication.java:148)
        at com.windriver.ide.application.CopyOfIDEApplication.start(CopyOfIDEApplication.java:136)
        at com.windriver.ide.application.UnifiedSWTSwingApplication.access$2(UnifiedSWTSwingApplication.java:1)
        at com.windriver.ide.application.UnifiedSWTSwingApplication.start(UnifiedSWTSwingApplication.java:70)
        at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
        at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
        at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
        at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
        at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
        at org.eclipse.equinox.launcher.Main.main(Main.java:1414)
        at org.eclipse.equinox.launcher.WRWBMain.main(WRWBMain.java:37)

Why is this and how can I get it fixed?


text:
Q: maximum value from three different tables I have three tables which are as:

*

*table1(ID,JName, XVal, YVal)

*table2(ID, RName, XVAl, YVal)

*table3(ID, TName, XValue, YValue)

XValue, YValue , XVal, YVal are of number type. I want maximum and minimum value of XVal and YVal among all these tables. Previously I wrote following queries:
Select max(XVal) FROM table1
Select max(XVal) FROM table2
Select max(XValue) FROM table3

And for minimum value:
Select min(XVal) FROM table1
Select min(XVal) FROM table2
Select min(XValue) FROM table3

By running these queries, I can get 3 different results for minimum and maximum and then, I can just use logical codes to compare between them and get the maximum and minimum value but what i want here is single query which will do this for me.
I have used following queries:
Select max(XVal) from table1 UNION select max(XVal) from table2 UNION select max(XValue) as XVal from table3 ORDER BY 'MAX(XVal)'DESC LIMIT 1

And another one:
select max(XVal) as maxval from(select XVal from table1 UNION ALL SELECT XVal from table2 UNION ALL Select XValue from table3) as subquery

But both of them failed. Can somebody help me with this? And also point out the cause for the above queries to not function?

A: The correct syntax for the first of the two versions is:
Select max(XVal) as max_XVal from table1 UNION ALL
select max(XVal) from table2 UNION ALL
select max(XValue) as XVal from table3
ORDER BY max_XVal DESC
LIMIT 1;

You can use either UNION or UNION ALL here.
If you want the minimum and maximum values from the three tables:
SELECT MIN(XVal), MAX(XVal)
FROM
(
    SELECT XVal FROM table1
    UNION ALL
    SELECT XVal FROM table2
    UNION ALL
    SELECT XVal FROM table3
) t123;

A: The UNION solution above is better but it's worth noting you could also just use your original query like this:
SELECT
    GREATEST
    (
        (SELECT MAX(XVal) FROM table1),
        (SELECT MAX(XVal) FROM table2),
        (SELECT MAX(XValue) FROM table3)
    )
    LEAST
    (
        (SELECT MIN(XVal) FROM table1),
        (SELECT MIN(XVal) FROM table2),
        (SELECT MIN(XValue) FROM table3)
    )

A: Use a max over a subquery:
select max(val) from (
  select max(XVal) val from table1
  UNION ALL
  select max(XVal) from table2
  UNION ALL
  select max(XValue) from table3
) x

AFAIK this syntax will work all rbdms.


text:
Q: C++ аллокация памяти #include <iostream>

void main() {
  void* ptr = malloc(3);
  int *b = static_cast<int*>(ptr);
  *b = 2147483647;
  std::cout << *b; // 2147483647
}

У меня есть 3 байта пам'яти от malloc и sizeof(int*) показывает 4, каким образом я поместил int в 3 байта без ошибок? Компилятор MS Visual C++

A: Этот код вызывает неопределенное поведение.
Ошибка не гарантируется, и эффект может быть любым (в том числе программа может работать как будто ничего не произошло, а может неожиданно сломаться).

A: Ваш код содержит неопределённое поведение (UB) - запись за границы выделенной памяти. От компилятора не требуется уведомлять о подобного рода ошибках. Подробнее об UB можете почитать в соответствующем вопросе: Разница между неопределённым, неспецифицированным и зависимым от реализации поведением


text:
Q: Exercise about $\sum_{n=1}^{\infty}\frac{e^{-nx}}{n+1}$
(1) Let $r$ be a positive real number. Show $\sum_{n=1}^{\infty}\frac{e^{-nx}}{n+1}$ is uniformly convergent on $x\in [r,\infty)$.
(2) Find the value of $\lim_{r\to+0} \int_{r}^{1/r}\sum_{n=1}^{\infty}\frac{e^{-nx}}{n+1}dx$

My approach
(1) Let $f_n(x) = \frac{e^{-nx}}{n+1}$. $f_{n}^{'}(x) < 0$ on the interval, then $\sum_{n=1}^{\infty}f_n(x) < \sum_{n=1}^{\infty}f_n(r) $. For sufficiently large $n$, $e^{-nx} < 1/(n+1)$. So there exists $N$ and $\sum_{n=1}^{\infty}f_n(r) <\sum_{n=1}^{N-1}f_n(r) + \sum_{n=N}^{\infty}\frac{1}{(n+1)^2} < \infty$. From Riemann zeta function and Weierstrass M test, we get the result.
(2) We can assume $r<1$.
$\lim_{r\to+0} \int_{r}^{1/r}\sum_{n=1}^{\infty}\frac{e^{-nx}}{n+1}dx = \lim_{r\to+0} \sum_{n=1}^{\infty}\int_{r}^{1/r}\frac{e^{-nx}}{n+1}dx = \lim_{r\to+0} \sum_{n=1}^{\infty} [(\frac{1}{n+1}-\frac{1}{n})e^{-nx}]_{r}^{1/r}.$
No idea from here.

A: Note that $e^{-nx}\leq e^{-nr}=(e^{-r})^n.$ as $x\geq r$. Thus, any partial sum $S_n(x)$ will, uniformly in all $x\in [r,+\infty),$ satisfy
$$S_n(x)\leq \sum_{k=1}^n \frac{(e^{-r})^k}{k+1}<\sum_{k=1}^n (e^{-r})^k.$$ The RHS is the partial sum of a Geometric series of common ratio $0<e^{-r}<1$--hence converges. Thus, your series converges uniformly.

*because of uniform convergence, you can interchange the integral   with the infinite sum. So we do this and after integration the result follows.


text:
Q: Renaming feature classes in ArcGIS 10 I often have a problem when it comes to renaming featureclasses or SHPs in ArcGIS. I also have a problem when for example I have to transform 20 Feature classes or a whole dataset into a new coordinate system and want to append "_ETRS89" to the end of all the transformed feature classes.
I know there are python scripts which do this, as well variable substitution methods in model builder. But isn´t there also the option of putting this in the Tool´s dialog in ArcMap?

A: When you create a tool in model builder and want to run it from the tools menu (rather than open model builder all the time), you need to define parameters.  These will then show up in a dialog box when you click on the tool n the tools menu (as opposed to edit it in model builder).  See the documentation for how to do this.  You can then use the tool from the tools menu like any other tool.
So, you can take your python script and add it to a tool using model builder.  Give it some inputs which you should mark as parameters and perhaps likewise have a parameter for the string you want to append as a file name.  You will also want to parameterize your folder destination.


text:
Q: getchar() only calling every other time While using Ch Standard Interpreter, getchar() only runs every other line.
C:/> char a = getchar();
C:/> char b = getchar();
b
C:/> char c = getchar();
C:/> char d = getchar();
d

I have the same issue when using scanf("%c", &a) instead; in Vim the statement is skipped.
printf("\nType of Something\nA for SomethingA\nB for SomethingB "
        "\nC for SomethingC\n\nSelect (A,B,C) > ");
char letter = getchar(); // This statement gets skipped
return 0;

A: When you type "A" on the keyboard, you first press "A", and then you press "ENTER", right? So getchar() or scanf("%c", ....) gets two characters to read: "A", and the newline character from the "ENTER" key.
If you use your code in a loop, or just repeatedly, the first getchar() will read the newline character from the previous input.


text:
Q: Using @Mock and @InjectMocks I'm currently studying the Mockito framework and I've created several test cases using Mockito.
But then I read that instead of invoking mock(SomeClass.class) I can use the @Mock and the @InjectMocks - The only thing I need to do is to annotate my test class with @RunWith(MockitoJUnitRunner.class) or use the MockitoAnnotations.initMocks(this); in the @Before method.
But it doesn't work - It seems that the @Mock won't work!
Here is my 2 codes revisions - one using the annotations and one without.
What am I doing wrong?
public class ReportServiceImplTestMockito {

    private TaskService       mockTaskService; // This is the Mock object
    private ReportServiceImpl service;

    @Before
    public void init(){
        service         = new ReportServiceImpl();
        mockTaskService = mock(TaskServiceImpl.class);
        service.setTaskServiceImpl(mockTaskService);
    }
/// ...

 Some tests
}

As I said - this work great.
But the following wont:
@RunWith(MockitoJUnitRunner.class)
public class ReportServiceImplTestMockito {

     @Mock
     private TaskService      mockTaskService;

     @InjectMocks
     private ReportServiceImpl service;

         // Some tests
}

And here is the ReportServiceImpl class:
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private TaskService taskServiceImpl;

    public ReportServiceImpl(){}

    public ReportServiceImpl(TaskService taskService){
        this.taskServiceImpl = taskService;
    }

    public void setTaskServiceImpl(TaskService taskServiceImpl) {
        this.taskServiceImpl = taskServiceImpl;
    }
}

What am I missing?

A: O.K, I got my mistake!!!
I've used the @InjectMocks but initialized the same variable in the init() method...
So what happened was that mockito injected the mock objects to my variable - but seconds later I ran it over - initializing that very same variable!!!

A: I'm not sure, but try to create new instance of ReportServiceImpl manually (as you did in working example):
 @InjectMocks
 private ReportServiceImpl service = new ReportServiceImpl();

A: Your code works fine for me using Mockito 1.9.
Using an 1.8+ version of Mockito I get a very specific error message telling me exactly how to fix the problem. As php-coder suggests: For Mockito 1.8+ you need to initialize the field.
Did you see this or any other error message?
Edit:
The following code works for me. Small changes:

*

*Removed Spring annotations

*Removed Interface

*Added Getter

*Added empty TaskService

*Added test with System.out.println
Does it produce an error for you? :
Service:
public class ReportServiceImpl {

    private TaskService taskServiceImpl;

    public ReportServiceImpl() {

    }

    public ReportServiceImpl(TaskService taskService) {
        this.taskServiceImpl = taskService;
    }

    public void setTaskServiceImpl(TaskService taskServiceImpl) {
        this.taskServiceImpl = taskServiceImpl;
    }

    public TaskService getTaskServiceImpl() {
        return taskServiceImpl;
    }
}

Dependency:
public class TaskService {

}

Test, prints mockTaskService:
@RunWith(MockitoJUnitRunner.class)
public class ReportServiceImplTestMockito {

    @Mock
    private TaskService       mockTaskService;

    @InjectMocks
    private ReportServiceImpl service;

    @Test
    public void testMockInjected() {
        System.out.println(service.getTaskServiceImpl());
    }
}


text:
Q: Looping through cURL json array result I have been trying to do this for awhile. I have a request to an api using cURL. For the moment I can execute the cURL function and encode it with json. I can print_r() an element of the array which gives me back one result. However I have a return from the api of 25 elements of which I need to return back just the id of the 25 elements. I have included a var_dump() of the array to give you a screen shot of the array. The list iterates to 24 elements. I need the 25 Id's
Below is my code
<?php

$url = 'https://api.getbase.com/v2/lead_sources?sort_by=name:desc';

//Initiate cURL.
$chbase_user = curl_init($url);

curl_setopt($chbase_user, CURLOPT_RETURNTRANSFER, true);

curl_setopt($chbase_user, CURLOPT_HTTPHEADER, array('User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4','Accept: application/json','Authorization: Bearer inserted here'));

$result_base_user = curl_exec($chbase_user);

$data_result_base_user = json_decode($result_base_user,true);

echo '<pre>';
print_r($data_result_base_user['items'][0]['data']['id']);
var_dump($data_result_base_user );// Below is the result of this

?>

array(2) {
["items"]=>
array(25) {
  [0]=>
  array(2) {
    ["data"]=>
    array(6) {
      ["id"]=>
      int(154808)
      ["created_at"]=>
      string(20) "2015-11-09T09:25:55Z"
      ["updated_at"]=>
      string(20) "2018-03-08T16:43:31Z"
      ["name"]=>
      string(17) "X - Zopim IM Chat"
      ["creator_id"]=>
      int(675478)
      ["resource_type"]=>
      string(4) "lead"
    }
    ["meta"]=>
    array(1) {
      ["type"]=>
      string(6) "source"
    }
  }

A: Loop through the $data_result_base_user['items'], save ids in array and return that array
$ids = array();

foreach ($data_result_base_user['items'] as $key => $value) {
    $ids[]=$value['data']['id']; // assuming all element have same structure
}

return $ids;


text:
Q: password protect multiple directories via htaccess I am able to password protect directories via the htaccess file at the root of my site (I have to use one htaccess file in my site root because of my CMS). The issue I'm having is assigning users to each directory I want to protect. I can create multiple users and password protect multiple directories, but any user will work for any protected directory. For example:
example.com/section-one should be private and accessed by user "one".
example.com/section-two should be private and accessed by user "two".
However any user will work on either section and once users log into one they have access to the others without being asked for a password. I know it is an issue with my htaccess file. I tried using  but can't seem to figure out the formatting. All the information online shows how to do this for files, but directories just isn't as easy to find help on.
I am using this:
<IfModule mod_authn_file.c>
SetEnvIf Request_URI "^/section-one.*$" private
AuthName "Password Needed"
AuthGroupFile /dev/null
AuthType Basic
AuthUserFile /www/server/.htpasswd
Require user one
Order Deny,Allow
Deny from env=private
Satisfy any
</IfModule>

<IfModule mod_authn_file.c>
SetEnvIf Request_URI "^/section-two.*$" private
AuthName "Password Needed"
AuthGroupFile /dev/null
AuthType Basic
AuthUserFile /www/server/.htpasswd
Require User two
Order Deny,Allow
Deny from env=private
Satisfy any
</IfModule>

A: .htaccess files are used for applying specific configuration directives to the directories in which they are located. It is not possible to use one .htaccess file to specify different configurations for different directories. You either need to put your access controls in the server/vhost configuration file or use one .htaccess per directory.


text:
Q: Display an image to be a certain size in PHP I have a number of different image URLs in my database, of varying dimensions. When I display my web page in PHP, how can I display the image and have it be fixed dimensions?

A: using both fixed height and width will stretch the image. Use only one height or width in img tag or use css height or width to zoom image to fixed dimension.
1.) use either height or width in img tag in html
2.) use css either height or with
3.) resize image proportionately using image resize in php. for image resize you can use any 3rd party class. eg. suggested above.

A: You could use this easily: Smart Image Resizer
Hope it helps

A: I suggest resizing all images as they are uploaded and store the resized image along with the original.

A: You may use a script like this (just an example code).
I recommend you to implement an image cache for resized files.
<?php

$image = "images/worldsmap_bg.png";

if(!file_exists($image))
    throw new Exception("file doesn't exists");

$imageinfo = getimagesize($image);

$maxwidth = 120;
$maxheight = 150;
$origratio = $imageinfo[0]/$imageinfo[1];

$width = $imageinfo[0];
$height = $imageinfo[1];

if($height>$maxheight)
{
    $faktor = $maxheight/$imageinfo[1];
    if($faktor < 1)
    {
        $width = round($width*$faktor);
        $height = round($height*$faktor);
    }
}

if($width>$maxwidth)
{
    $faktor = $maxwidth/$width;
    if($faktor < 1)
    {
        $width = round($width*$faktor);
        $height = round($height*$faktor);
    }
}

$image_p = imagecreatetruecolor($width, $height);

switch($imageinfo[2]):
    case IMAGETYPE_GIF:
            $image = imagecreatefromgif($image);
        break;
    case IMAGETYPE_JPEG:
    case IMAGETYPE_JPEG2000:
            $image = imagecreatefromjpeg($image);
        break;
    case IMAGETYPE_PNG:
            $image = imagecreatefrompng($image);
        break;
    default:
        throw new Exception ("invalid image");
        break;
endswitch;

imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $imageinfo[0], $imageinfo[1]);

header("Content-type: " . image_type_to_mime_type($imageinfo[2]));

switch($imageinfo[2]):
    case IMAGETYPE_GIF:
            imagegif($image_p);
        break;
    case IMAGETYPE_JPEG:
    case IMAGETYPE_JPEG2000:
            imagejpeg($image_p);
        break;
    case IMAGETYPE_PNG:
            imagepng($image_p);
        break;
    default:
        throw new Exception ("invalid image");
        break;
endswitch;

?>


text:
Q: What would you recommend using for audio file transcribing into a .txt? I am working on a small school project where I have to take a lot of audio files and transcribe them into .txt files. I am a beginner at programming.
So far I've tried alexkras method using Google's Cloud Speech API. But I can't use this for mass transcribing as it is done by converting the audio to .wav using an external software(This can be done through ffmpeg too so not a big deal) and splitting up the new .wav file into <60s parts as Cloud Speech can only transcribe <60s at a time which is a big loss in trans unless you upload them to GCS but this is also a problem for mass transcribing as some .wav files are large enough(A 1 hour podcast I used turned into 800mb file) the process is slowed down.
The next one I tried is using gcloud SDK and directly transcribing audio files on the GCS using a small code in my terminal, now the problem I observed here is the transcription is not complete and it shows the transcription this way,
Example from Google:
   {
          "@type": "type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeResponse",
      "results": [
        {
          "alternatives": [
            {
              "confidence": 0.9840146,
              "transcript": "how old is the Brooklyn Bridge"
            }
          ]
        }
      ]
    }

Which is not ideal, maybe there is a way to transfer it into a text file but the transcriptions I've done so far are not complete, I got like a total of <30 lines of text from a 11-minute video.
The most effective method I've tried is the alexkras method but as I've said above there are problems with that too(In my case). I've been looking into Machine Learning methods for speech-to-text so it can recognise or transcribe audios with accent too.
Do you guys know any method to help me transcribe mass audios into text effectively? It would have been so happy with alexkras method if it wasn't for the splitting of files or uploading it to GSC. I would greatly appreciate any help or suggestions or guidance with this. Thank you.

A: you can try the Watson STT API, the file/stream size limitation is 100MBs, which means that if using the proper encoding you can decode files up to several hours long. You can use sox or ffmpeg for the audio conversion if needed, the lighter weight codec is audio/ogg
https://www.ibm.com/watson/developercloud/speech-to-text/api/v1/#recognize_sessionless12
see the curl example to get you started

A: I've just been exploring the AWS Transcribe product.   It requires an AWS account, which can be obtained free, with a credit card for payment if you go over the free limits.
It provides up to 60 minutes per month of audio transcription.  If you go beyond 60 minutes of audio, you'll need to pay a bit less than $1.50 per hour of audio transcribed.
The transcription results in a .JSON file that is not easy to read.  But, there is a php script on GitHub that turns the .JSON file into a very easy-to-read transcript.
I've found it to be pretty accurate, and relatively easy to use.  I'd look into it if I were you.


text:
Q: How can I override jquery UI styling? I am having problems with this site.  It is a learning site for me and hopefully will become a site for my hobby, but it is in crude form right now.  I am using Bootstrap for responsiveness and have a bit of JQuery in there for an accordion in the middle for a log of sorts.  I am using JQuery to do some text highlighting on hover and maybe some other things that come up.
My problem is that something in the JQueryUI seems to break my nice styling that I had going on where I had the headers in the accordion area with a nice dark grey background which you can see on page load for a split second until the jqueryUI loads which then changes my styling to a white background header.
Check out http://joshsbees-com.stackstaging.com and you will see what I mean.
How do I use bootstrap with JQueryUI and my own CSS?  I'm sure I have too many scripts here and have some things crossed up somewhere.
Here is the code in my index page:
<!doctype html>

    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
    <title>Josh's Bees</title>

Welcome to Josh's Bees

Bee farm in southern Jones County Georgia

I got interested in beekeeping in 2018 when helping my dad. He got 2 hives and I helped him occasionally
                by holding tools, smoking them, lifting boxes, and such. I just could not get enough of watching God's
                miraculous work at hand in those little creatures. Everything from watching them build comb to laying
                eggs and storing nectar which they then turned into honey. I was hooked and still they never cease to
                amaze me.

I set up the hive and bought a nuc in mid May 2019. I spent the summer learning a lot and watching my
            bees.

2020 Inspection Report

Feb 9 2020

First quick inspection of this year. I wanted to get in and see how they were doing over the winder.
                    Last check was early December 2019 and there was not much brood capped. This time, however, since
                    the days are getting longer, the queen has several frames in the middle of the top box with fully
                    capped brood. There is a healthy amount of bees in the hive as well. Today was a sunny day, light
                    wind and mild temperatures. The bees were calm, but with healthy activity and still good on honey
                    stores. Dry sugar on top has not been eaten at all.

March 1 2020

Today was mostly cloudy and cool. High in the low 60's, so I knew the girls would be cranky and I
                    suited up for the occasion, gloves and all. Objective for today was to swap brood chambers, check
                    food stores, and add beetle barns to each layer: bottom board, top of bottom box, and top of top
                    box. I did a quick frame inspection of the top box. Saw good capped brood pattern on several frames.
                    Hive had healthy supply of bees which stands to reason after the amount of capped brood I saw in
                    February. I did not see any swarm cells, but I only did a quick glance over as I was swapping boxes.
                    They were getting angry and were all up in my face. If I had not had on gloves and full suit, I
                    would definitely have gotten popped multiple times. They were also eating the dry sugar pretty good,
                    but still have a little capped honey in the hive.

March 2 2020

I added a Boardman entrance feeder today with some 1:1 syrup to begin feeding. Plan to add honey
                    super end of March.

Links of my Favorite Sites

Barnyard Bees

Dadant

Dixie Bee Supply

        Design by Josh Scoville, January 2020

A: Use JQuery UI's ThemeRoller page.

A: Let us imagine you have imported your third-party library and your CSS like below:
<link href="yourStyle.css" rel="stylesheet" />
<link href="bootstrap.css" rel="stylesheet" />
<link href="jqueryUI.css" rel="stylesheet" />

If you done this order to importing your CSS & libraries, the bootstrap and jqueryUI overwrite your Custom Style !
Finally, you have two options to solve your problem.

*

*Re-order your importing libraries.

*Make your specific CSS classes !important.

So do this:
<link href="bootstrap.css" rel="stylesheet" />
<link href="jqueryUI.css" rel="stylesheet" />
<link href="yourStyle.css" rel="stylesheet" />

And make sure they are loaded in a correct order in your DOM.
And if the order of imported libraries were correct, put your Custom-Style bottom of your page, before  tag.
By the way, for your knowledge and enhance your code quality, learn about this plugin (Gulp).


text:
Q: Hadoop MapReduce Adding Values with Same Keys - Java I'm trying to add the numbers for each recurring name. However, I go the names and numbers separate but I can't figure out how to add the numbers. Please let me know if you need any more information to help.
Thank you in advance.

This is my code so far:
package hadoop.names;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class names_app {

    public static class GroupMapper extends Mapper<LongWritable, Text, Text, IntWritable> {

        /** The name. */
        Text nameText = new Text();

        /** The count text. */
        IntWritable count = new IntWritable();

        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

            String line = value.toString();
            String[] keyvalue = line.split(",");
            nameText.set(new Text(keyvalue[3]));
            count.set(Integer.parseInt(keyvalue[4]));
            context.write(nameText, count);

        }
    }

    public static class GroupReducer extends Reducer<Text, IntWritable, Text, IntWritable> {

        public void reduce(Text key, Iterator<IntWritable> values, Context context) throws IOException,
                InterruptedException {

            int n = 0;
            while (values.hasNext()) {
                n = n + values.next().get();
            }
            context.write(key, new IntWritable(n));

        }

    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        FileUtils.deleteDirectory(new File("/output/names"));
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "GroupMR");
        job.setJarByClass(names_app.class);
        job.setMapperClass(GroupMapper.class);
        job.setReducerClass(GroupReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        FileInputFormat.setMaxInputSplitSize(job, 10);
        FileInputFormat.setMinInputSplitSize(job, 100);
        FileInputFormat.addInputPath(job, new Path("/input_data/Sample_of_names.csv"));
        FileOutputFormat.setOutputPath(job, new Path("/output/names"));
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}

Input Sample:
NJ,F,1910,Mary,593
NJ,F,1910,Helen,438
NJ,F,1910,Anna,355
NJ,F,1910,Margaret,311
NJ,F,1910,Elizabeth,260
NJ,F,1910,Dorothy,255
NJ,F,1910,Rose,201
NJ,F,1910,Ruth,188
NJ,F,1910,Mildred,174
NJ,F,1910,Florence,169
NJ,F,1910,Catherine,158
NJ,F,1910,Marie,152
NJ,F,1910,Lillian,130
NJ,F,1910,Alice,125
NJ,F,1910,Frances,124

Link to the orginal data set: https://www.kaggle.com/datagov/usa-names
I got the following output as a csv:
Aaliyah,5
Aaron,14
Aaron,22
Aaron,11
Aaron,17
Aaron,24
Aaron,12
Aaron,241
Aaron,9
Aaron,11
Aaron,199
Aaron,16
Abbey,5
Abbie,5
Abbie,5
Abbie,5

I would like to have:
Aaliyah,5
Aaron,576
Abbey,5
Abbie,15

A: For some reason you are using the default reducer in Hadoop which is the identityReducer. I think that it is happening because there is a typo in your reduce function so that its parent's class reduce function is called instead of the one that your created. To avoid this problem is always wise to use @Override in Java. Try to write @Override in your reduce function and re-compile.
According to Hadoop's source code, the default reducer looks like this:
/** Writes all keys and values directly to output. */
public void reduce(K key, Iterator<V> values,
                   OutputCollector<K, V> output, Reporter reporter)
  throws IOException {
  while (values.hasNext()) {
    output.collect(key, values.next());
  }
}

Basically it spills out the output of the mapper.
Better solution
Just use the Hadoop given LongSumReducer which basically does the reduce operation that you want to do, so in your main function write:
job.setReducerClass(LongSumReducer<Text>.class);

The package's location is at org.apache.hadoop.mapred.lib.LongSumReducer


text:
Q: $\mathcal A\equiv\mathcal B\implies \mathcal A\cong\mathcal B$ for finite $\mathcal L$-structures where $\mathcal L$ is an infinite signature Let $\mathcal L$ be an infinite signature and $\mathcal A$, $\mathcal B$ two finite $\mathcal L$-structures such that
for each first-order $\mathcal L$-sentence $\varphi$, $$\mathcal A\models\varphi\iff\mathcal B\models\varphi.$$

Does it follow that $\mathcal A$ and $\mathcal B$ are isomorphic?

Clearly, for finite signatures $\mathcal L$ the answer would be "yes".

A: Yes. If they are not isomorphic, then for each bijection of $A$ with $B$, there is an atomic formula  that the bijection does not respect, that is, a reason that it is not an isomorphism. Since there are only finitely many bijections, we therefore reduce to the case of a finite sublanguage, in which the structures are not isomorphic, contrary to your observation that the conclusion is valid in finite signatures.


text:
Q: Icinga database cleanup I am working in Icinga for performance data collection,
I have to clear all plugin data more than 30 days, how can I do this. I had some google searches does not help.
some references:
External Commands List
Database model
I am using:
RHEL os
icinga2 from source build
postgresql
Using NRPE for collecting remote server data
Is there any tool available to cleanup or any queries to delete all database entries older than 30 days?

A: http://docs.icinga.org/latest/en/configido.html#configido-ido2db
From the manual, it looks like your ido2db.cfg needs to be configured with the proper data:
max_systemcommands_age=43200
max_servicechecks_age=43200
max_hostchecks_age=43200
max_eventhandlers_age=43200
max_externalcommands_age=43200
max_logentries_age=43200
max_acknowledgements_age=43200
max_notifications_age=43200
max_contactnotifications_age=43200
max_contactnotificationmethods_age=43200

Also, make sure that trim_db_interval is set somewhat sane. The default of 3600 should be sufficient.
trim_db_interval=3600


text:
Q: Get data whenever email is sent to an email id and update db with email information I am trying to write a webservice and configure my webserver such that whenever I send an email to xyz@domain.com, it should make an API call store email details in DB. I was using Cloudmailin to implement similar functionality before but now I want to convert it to native PHP webservice. Any help would be appreciated.

A: See http://harrybailey.com/2009/02/send-or-pipe-an-email-to-a-php-script/ for information on how to configure a mail server to accept incoming messages for your domain, and pipe each incoming message to a PHP script.  Then, your PHP script can parse the headers and body of each incoming message as they arrive.


text:
Q: SSH hangs forever? I'm trying to SSH into a remote VM, and the command hangs forever.
Before, when I was trying to get some stuff set up on it, I edited /etc/hosts and /etc/init.d, and I'm worried I might have messed something up. If it isn't obvious, I'm a bit new to networking/server admin stuff.
Running with -v gives me this:
ssh USERNAME@IP -vvv
OpenSSH_5.9p1, OpenSSL 0.9.8x 10 May 2012
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to 10.150.42.39 [10.150.42.39] port 22.
debug1: Connection established.
debug1: identity file /Users/LOCALUSERNAME/.ssh/id_rsa type -1
debug1: identity file /Users/LOCALUSERNAME/.ssh/id_rsa-cert type -1
debug3: Incorrect RSA1 identifier
debug3: Could not load "/Users/LOCALUSERNAME/.ssh/id_dsa" as a RSA1 public key
debug1: identity file /Users/LOCALUSERNAME/.ssh/id_dsa type 2
debug1: identity file /Users/LOCALUSERNAME/.ssh/id_dsa-cert type -1

EDIT: I tried moving the id_dsa and id_dsa.pub files away and got these messages instead:
ssh USERNAME@IP -vvv
OpenSSH_5.9p1, OpenSSL 0.9.8x 10 May 2012
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to 10.150.42.39 [10.150.42.39] port 22.
debug1: Connection established.
debug1: identity file /Users/LOCALUSERNAME/.ssh/id_rsa type -1
debug1: identity file /Users/LOCALUSERNAME/.ssh/id_rsa-cert type -1
debug1: identity file /Users/LOCALUSERNAME/.ssh/id_dsa type 1
debug1: identity file /Users/LOCALUSERNAME/.ssh/id_dsa-cert type -1

EDIT2: If anyone else runs into this problem: Apparently my VM ran out of memory and hung. My sysadmin restarted it and that fixed it.

A: Turns out the machine was constantly running out of memory due to unrelated (and still slightly mysterious) reasons. Restarting it fixed it temporarily but it would soon run out again. I ended up trashing the VM and getting a new one.


text:
Q: Using NGINX server to deploy a Meteor App from Amazon Linux AMI 2013.09.2 instance receive Module Error I am attempting to deploy my first web application (a version of Telescope from the MeteorJS framework) via Heroku to a custom subdomain from a Amazon Linux AMI 2013.09.2 instance. I am following along with this tutorial - http://satishgandham.com/2013/12/a-complete-guide-to-install-production-ready-telescope-on-your-own-server/ - but once I attempt to run Telescope using PORT=3000 MONGO_URL=mongodb://localhost:3000/Telescope ROOT_URL=http://ec2-54-193-42-229.us-west-1.compute.amazonaws.com node client/main.js, I receive this error message: Error: Cannot find module '/home/ec2-user/bundle/programs/server/node_modules/fibers/client/main.js'
What I have attempted to do to solve this problem is performed cp || mv on the file main.js which is originally located in the ~/Telescope/client directory over to /home/ec2-user/bundle/programs/server directory and even '/home/ec2-user/bundle/programs/server/node_modules/fibers but I cannot seem to separate main.js from the /client directory. I am not sure if that is the issue or if there is some other underlying problem but I want to find a work around to using a proxy server at this point. I thought that moving the main.js file out of the /client directory was sufficient but apparently not.  I am not sure it is imperative for my purposes to continue attempting to use a proxy but if there is a fix, I would not mind learning about it.
Or if any one could direct me on how this - https://github.com/aldeed/deploymeteor/ - could be a potential work-around to using an NGINX server proxy your help would be much appreciated.

A: You are getting the error because you are not running the command from your home folder.
You were at bundle/programs/server/node_modules/fibers.
Either use absolute path for client/main.js, or cd to ~
MONGO_URL=mongodb://localhost:3000/Telescope ROOT_URL=http://ec2-54-193-42-229.us-west-1.compute.amazonaws.com node client/main.js

PS: It will be helpful for others if you asked the question on the post itself, instead of here


text:
Q: Convergence and sum of $S(R,\omega) = \sum_{n=1}^{\infty}\frac{R^n}{(4\pi n)^{0.5+i\omega}}$ I am looking for a convergence test and a potential analytical expression for this serie:
$$S(R,\omega) = \sum_{n=1}^{\infty}\frac{R^n}{(4\pi n)^{0.5+i\omega}}$$ Where $R$, $\omega$ are real numbers such that  $0<R < 1$ and $0 \leq \omega \leq \infty$
For the convergence test, I am using the fact that the serie seems to converge by absolute convergence ? since:
$$S(R,\omega) = \sum_{n=1}^{\infty}\frac{R^n}{(4\pi n)^{0.5}}e^{-i\omega log(4\pi n)}$$
and $$\sum_{n=1}^{\infty}|\frac{R^n}{(4\pi n)^{0.5}}e^{-i\omega log(4\pi n)}| = \sum_{n=1}^{\infty}|\frac{R^n}{(4\pi n)^{0.5}}| = \sum_{n=1}^{\infty}\frac{R^n}{(4\pi n)^{0.5}}$$ which converge since $\lim_{n \to \infty} |\frac{a_{n+1}}{a_{n}}| = R$ with $a_{n} = \frac{R^n}{(4\pi n)^{0.5}}$ and $R<1$
Is that correct? I also plotted the complex term up to n = 100 for many values of $R,\omega$ and the sequence always converge.
Now I am clueless on how to calculate the sum. Can the residue theorem be used ?
Any advice are welcome!


text:
Q: 4.0.4 Facebook SSO - Android Key Hash changed? App with Facebook SDK SSO was working fine in 2.2, now upgraded Samsung Galaxy (both a II and III for testing) to 4.0.4 and now getting this from FB SSO SDK:
E/fbLogin(8286): invalid_key:Android key mismatch. Your key "<<omitted>>" does not match the allowed keys specified in your application settings. Check your application settings at http://www.facebook.com/developers

So I went and updated the key hash on fb/developers, and yep, it's working fine again.
It's odd- it worked with the original value in a 2.2 AVD, and the 4.0.3 AVD, but on both 4.0.4 physical devices, I'm getting the above error.
Is there something different going on with 4.0.4 that's causing this?

A: Well, no answer seems coming.  For those who come across this, just copy the key hash in the error message to the fb developers site, and you should be good to go.


text:
Q: Write a query to print all prime numbers less than or equal to
Write a query to print all prime numbers less than or equal to. Print your result on a single line, and use the ampersand (&) character as your separator (instead of a space).

For example, the output for all prime numbers (<= 10) would be:

Output : 2&3&5&7

A: Different RDBMS have their own syntax / functions for RCTE and string aggregation.
Below is an example for PostgreSQL:
WITH RECURSIVE T (I) AS (SELECT 1 UNION ALL SELECT I+1 FROM T WHERE I < 10)
SELECT STRING_AGG (I::TEXT, '&') AS LST
FROM
(
  SELECT A.I
  FROM T A
  LEFT JOIN T B ON B.I BETWEEN 2 AND A.I - 1
  -- Actually, 1 is prime as well...
  WHERE A.I > 1
  GROUP BY A.I
  HAVING COUNT (CASE MOD (A.I, B.I) WHEN 0 THEN 1 END) = 0
  ORDER BY A.I
) A

LST

2&3&5&7

A: The solution provided below might be of assistance.
MSSQL
DECLARE @n INT = 1000;
DECLARE @x INT = 2;
DECLARE @z INT;
DECLARE @temp TABLE (A INT)

WHILE (@x <= @n)
BEGIN
    INSERT INTO @temp
    SELECT @x

    SET @z = 2

    WHILE (@z < @x)
    BEGIN
        IF (@x % @z <> 0)
        BEGIN
            SET @z = @z + 1
        END
        ELSE
        BEGIN
            DELETE
            FROM @temp
            WHERE A = @x

            BREAK
        END
    END

    SET @x = @x + 1
END;

SELECT STRING_AGG(A, '&')
FROM @temp


text:
Q: register a font with Raphael using CSS3 @font-face In my pages I often use custom fonts with the Raphaël .print with
the .getFont. for SVG text, and the CSS3 @font-face (with Font
Squirrel kits) for normal text.
Is maybe possible to automatically register a font from the @font-face
property, without create a JSON with Cufon?
I saw that in Font Squirrel kit there's the format('svg') used for old
iPhone/iPad ("This is an XML format required by iOS devices before
version 4.2.") maybe it could be useful also for desktop...
Thank you

A: If you define a font using @font-face in your css, you can then apply it to a Raphaël paper.text object in this way :
var someText = paper.text(0, 0, 'this is some text');
someText.attr({'font-family':'myCustomFont'});


text:
Q: Tweepy rate_limit_status- how to get remaining tweet posts Using tweepy rate_limit_status call, I get the following json output. However, I am not able to discern the number of tweet posts/writes remaining. I have monitored all the values below without being able to find the number of tweet posts/writes remaining.
How does one get this value with tweepy? If not possible with tweepy, the twitter api?
{
  u'rate_limit_context': {
    u'access_token': u'XXXXXXXXXXXXXXXXXX'
  },
  u'resources': {
    u'account': {
      u'/account/verify_credentials': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/account/update_profile': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/account/settings': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/account/login_verification_enrollment': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      }
    },
    u'blocks': {
      u'/blocks/list': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/blocks/ids': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      }
    },
    u'users': {
      u'/users/derived_info': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/users/lookup': {
        u'reset': 1413769788,
        u'limit': 180,
        u'remaining': 180
      },
      u'/users/search': {
        u'reset': 1413769788,
        u'limit': 180,
        u'remaining': 180
      },
      u'/users/suggestions/:slug/members': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/users/suggestions/:slug': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/users/show/:id': {
        u'reset': 1413769788,
        u'limit': 180,
        u'remaining': 180
      },
      u'/users/suggestions': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/users/report_spam': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/users/profile_banner': {
        u'reset': 1413769788,
        u'limit': 180,
        u'remaining': 180
      }
    },
    u'search': {
      u'/search/tweets': {
        u'reset': 1413769788,
        u'limit': 180,
        u'remaining': 180
      }
    },
    u'saved_searches': {
      u'/saved_searches/show/:id': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/saved_searches/list': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/saved_searches/destroy/:id': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      }
    },
    u'lists': {
      u'/lists/subscribers/show': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/lists/subscriptions': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/lists/members/show': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/lists/statuses': {
        u'reset': 1413769788,
        u'limit': 180,
        u'remaining': 180
      },
      u'/lists/subscribers': {
        u'reset': 1413769788,
        u'limit': 180,
        u'remaining': 180
      },
      u'/lists/list': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/lists/show': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/lists/memberships': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/lists/members': {
        u'reset': 1413769788,
        u'limit': 180,
        u'remaining': 180
      },
      u'/lists/ownerships': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      }
    },
    u'geo': {
      u'/geo/similar_places': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/geo/id/:place_id': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/geo/reverse_geocode': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/geo/search': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      }
    },
    u'application': {
      u'/application/rate_limit_status': {
        u'reset': 1413769491,
        u'limit': 180,
        u'remaining': 177
      }
    },
    u'trends': {
      u'/trends/available': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/trends/closest': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/trends/place': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      }
    },
    u'followers': {
      u'/followers/list': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/followers/ids': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      }
    },
    u'favorites': {
      u'/favorites/list': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      }
    },
    u'device': {
      u'/device/token': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      }
    },
    u'friendships': {
      u'/friendships/outgoing': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/friendships/show': {
        u'reset': 1413769788,
        u'limit': 180,
        u'remaining': 180
      },
      u'/friendships/incoming': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/friendships/no_retweets/ids': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/friendships/lookup': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      }
    },
    u'mutes': {
      u'/mutes/users/list': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/mutes/users/ids': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      }
    },
    u'friends': {
      u'/friends/list': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/friends/following/ids': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/friends/ids': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/friends/following/list': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      }
    },
    u'direct_messages': {
      u'/direct_messages/show': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/direct_messages': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/direct_messages/sent': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/direct_messages/sent_and_received': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      }
    },
    u'statuses': {
      u'/statuses/retweets_of_me': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/statuses/retweeters/ids': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/statuses/mentions_timeline': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/statuses/user_timeline': {
        u'reset': 1413769788,
        u'limit': 180,
        u'remaining': 180
      },
      u'/statuses/oembed': {
        u'reset': 1413769788,
        u'limit': 180,
        u'remaining': 180
      },
      u'/statuses/lookup': {
        u'reset': 1413769788,
        u'limit': 180,
        u'remaining': 180
      },
      u'/statuses/show/:id': {
        u'reset': 1413769788,
        u'limit': 180,
        u'remaining': 180
      },
      u'/statuses/friends': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/statuses/home_timeline': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/statuses/retweets/:id': {
        u'reset': 1413769788,
        u'limit': 60,
        u'remaining': 60
      }
    },
    u'help': {
      u'/help/tos': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/help/settings': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/help/configuration': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/help/privacy': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      },
      u'/help/languages': {
        u'reset': 1413769788,
        u'limit': 15,
        u'remaining': 15
      }
    }
  }
}

A: All calls to the twitter API that create or modify data are not rate limited on an application by application basis, and thus are not returned by that endpoint. They are, however, limited on a user basis across all applications in total, including official Twitter applications. There is, as far as I know, no way to see a user's progress towards those limits besides looking at their activity and counting yourself.
https://support.twitter.com/forums/10711/entries/15364#


text:
Q: How can we install Debian Jessie packages offline from the installation USB If the media used for installation is a USB stick (which has been created using dd, Unetbootin or some other method), how can one add packages from the USB without an Internet connection?
The following Repository is not usable by default after initial installation:
cdrom:[Debian GNU/Linux testing Jessie - Official Snapshot amd64 DVD Binary-1
For some reason, this USB connection doesn't work.
If the .iso image used to create the installation USB is copied into the new Debian Jessie installation, perhaps there is a means of mounting that ISO, using the packages that are already present by default in the Jessie installation?

A: Try this:

*

*Remove the existing entry for your CDROM disc from /etc/apt/sources.list

*Mount your flash drive somewhere.

*Do
apt-cdrom add -d=/mount/point/of/the/flash/drive

If this doesn't work for the flash drive, try dd-ing the .iso file back from the flash drive, loop-mount it (mount -o loop,ro /path/to/the/file.iso /mount/point) and try using apt-cdrom again.
Yet another possible option, if you're about to use this on multiple computers on a LAN, is to use a toop like reprepro to create a Debian repository on a dedicated server, feed it all the packages from your installation media and serve the resulting repository using a web server.

A: First, you need to mount your USB in your file manager (probably, Nautilus). Usually it auto-mounts with the default settings though.
As someone suggested on another website, i edited the /etc/apt/sources.list and added the following line after some fiddling around:
deb file:/media/your_username/DEBIAN\ 8_1_/dists/jessie jessie main contirb

It worked like a charm. Hope this helps someone although this post is a bit old.


text:
Q: Snap.svg load svg files and manipulate it I would like to stock an loaded svg files in variable to manipulate it later with snap.svg.
I can load a file, manipulate it in the loading function, but after ?
var _perso = Snap.load("svg/perso1.svg", function(f) {
    var g = f.select("g");
    g.transform("r45,650,200");
    s.append(g);
});
console.log(_perso); // undefined !!!

I would like, for exemple, transform my loaded object later with a buttom, or hide it... But I don't know how stock it?

A: Snap.load() doesn't return anything, you'll have to define a global var inside the callback.

var _perso=Snap.load("http://upload.wikimedia.org/wikipedia/commons/b/b0/NewTux.svg", function(f) {
    var g = f.select("g");
    g.transform("r45,650,200");
//    s.append(g);
    _perso=g;
});
setTimeout(function(){console.log(_perso)}, 1000); // defined !!!
<script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.3.0/snap.svg-min.js"></script>
<script type="text/javascript" src="https://getfirebug.com/firebug-lite.js">{startOpened: true,}</script>


text:
Q: Как найти частичное совпадение строки? Пробовал использовать алгоритм Левенштейна, но он зависит от длинны строки.
Пример:
let c = "1"
let b = "1"
let bb = "12"
let bbb = "123"

console.log(aza(c, b)); //100
console.log(aza(c, bb)); //50
console.log(aza(c, bbb)); //33

function aza(firstString, secondString, round = true) {
    import leven

    //Calculate leven distance.
    const levenDistance = leven(firstString, secondString);
    //Find longest string.
    const longestString = Math.max(firstString.length, secondString.length);
    //Calculate in percentage.
    const result = (longestString - levenDistance) / longestString * 100;
    return round ? Math.round(result) : result;
}

Как сделать, чтобы во всех вариантах было 100, так-как там есть искомая строка.
P.S Там, в примере "1", что выглядит глупо. Его я взял лишь для наглядного отображения процентов.
В реальной задаче там будет что-то на подобии:
const string1 = "4185614171";
const veryVeryLongText = "И тут длинный текст со значением, 41856AA4171";

Соответственно, нужно четко понять, что содержимое string1 есть в veryVeryLongText, в процентах, к string1.


text:
Q: Header of the first pages, which are different from the rest of the document This is my document:
\documentclass[12pt,a4paper,twoside]{report}

%Layout
\usepackage[top=2.5cm, bottom=3cm, left=2.5cm, right=2.5cm,paper=a4paper]{geometry}

%Header
\usepackage{fancyhdr}

%Chapter adjustments
\usepackage{titlesec}
\titleformat{\chapter}{\normalfont\fontsize{16pt}{0}\bfseries}{\thechapter.}{9pt}{}
\titlespacing*{\chapter}{0pt}{0pt}{16pt}
\usepackage{blindtext}

%Arial - ATTENTION: Compile with XeLaTeX (not PDFLaTeX)!
\usepackage{fontspec}
\defaultfontfeatures{Scale = MatchLowercase}
\setmainfont{Arial}[Scale = 1.0]

%Formatting the header
\pagestyle{fancy}
\fancyhf{}
\fancyhead[EL,OR]{\fontsize{8}{5} \selectfont \thepage}
\fancyhead[ER,OL]{\fontsize{8}{5} \selectfont \leftmark}
\renewcommand{\chaptermark}[1]{\markboth{#1}{}}

\fancypagestyle{plain}{
\fancyhf{}
\fancyhead[EL,OR]{\fontsize{8}{5} \selectfont \thepage}
\fancyhead[ER,OL]{\fontsize{8}{5} \selectfont \leftmark}
}

%Abstracttexts
\newcommand{\FirstAbstract}{This is Abstract 1.}
\newcommand{\SecondAbstract}{This is Abstract 2.}

\begin{document}

\pagenumbering{Roman}

{\fontsize{16pt}{0} \selectfont {\bf Abstract 1}}
\newline \vspace{-2mm} \\
\FirstAbstract

\newpage
{\fontsize{16pt}{0} \selectfont {\bf Abstract 2}}
\newline \vspace{-2mm} \\
\SecondAbstract

\newpage
\pagenumbering{arabic}

\chapter{Chapter 1}
\blindtext \blindtext \blindtext \blindtext \blindtext
\newpage

\chapter{Chapter 2}
\blindtext
\newpage

\section{First Section}
\blindtext
\newpage

\end{document}

I would like to adjust the header of my document - the two first pages should also contain the title of the pages. For the rest of the document it already works, but I have no idea how to just adjust the first two ones without interfering with the other following pages. I already tried the following code:
\usepackage{ifthen}
\lhead{\ifthenelse{\value{page}=1}{\fontsize{8}{5} \selectfont Kurzfassung}}

but with this the header of the following pages are disordered.
Thanks A LOT in advance :)!

A: [...]
\begin{document}
\markboth{Kurzfassung}{Kurzfassung}
\pagenumbering{Roman}
[...]


text:
Q: Multi-User program - list is the same in all users Problem: If I'm entering items to one user it'll save in every existing user, and even if i will create later a new user
i tried to save the list into a dictonary of users
which includes the usernames which are the keys and the values will be the list,
the list saved in the end after it changed because i have functions which can
append it and delete items and after the user have his list delete the list, logout and return to login menu. but i want that if the user will login you still can cahnge the same list and save again and open a new list. if you have better suggestions, tell me.
Thanks a lot
Sorry for my English, the comments are not accurate
code:
WATCH_LIST = 1
WATCH_HOW_MANY_ITEMS_IN_LIST = 2
CHECK_IF_ITEM_IS_IN_LIST = 3
SHOW_THE_NUMBER_OF_TIMES_ITEM_IS_IN_THE_LIST = 4
DELETE_ITEM = 5
ADD_NEW_ITEM = 6
WATCH_INVALID_ITEMS = 7
TOTAL_SUM = 8
LOGOUT = 9
EXIT = 10
LOGIN = 1
REGISTER = 2
ENTER = '\n'
STOP = "0"
MINIMUM_LENGTH = 3
DELETE_ALL_ITEMS = 1
DELETE_ONE_ITEM = 2
def get_input(list):
    '''
    Function gets input from user to the dictionary.
    input: dictionary - grocery list
    output: none'''

    item = raw_input("""Please enter items, enter 0 to stop: """)
    list[item] = 1
    while(item != STOP):
        print list, " 1"
        item = raw_input("")
        if(item in list):
            value = list[item]
            list[item] = value + 1
        else:
            list[item] = 1
    del list[item]
    return None
def print_menu():
    '''
    Function prints the main menu
    input: none
    output: none'''
    print """
    Main Menu:
    1. Watch grocery list.
    2. Watch how many items are in the list.
    3. Check if item is in the list.
    4. Watch how many times item is appeared in the list.
    5. Delete items from the list.
    6. Add item to the list.
    7. Watch all of the invalid items.
    8. Watch the total sum of your items
    9. logout
    10. Exit
    """
    return None
def print_delete_menu():
    '''
    Function prints all of the delete options you can do.
    input: none
    output: none'''
    print """
    Delete Menu:
    1. Delete item by name (all of the them).
    2. Delete item by name (only one of them).
    """
def print_num_of_times_item_is_listed(list, requested_item):
    '''
    Function gets item's name from the user and
    returns the number of times it shows in the list.
    input:
    *list - grocery list
    *requested item - string - item's name.
    output: counter - int - the number of times the item is listed.
    '''
    item_in_list = False
    for item in list.keys():
        if(item == requested_item):
            print "The item appears", list[item], "times in the list"
            item_in_list = True
    if(not item_in_list):
        print "item isn't listed"
    return None
def add_item_to_the_list(list):
    '''
    Function gets input from user to the dictionary.
    input: dictionary - grocery list
    output: none'''
    item = raw_input("""Please enter item """)
    if(item in list):
        value = list[item]
        list[item] = value + 1
    else:
        list[item] = 1
    return None
def print_invalid_items(list):
    '''
    Function prints invalid items, which are items with non alphabetic chars or items with less than 3 chars.
    input: list - grocery list
    output: none'''
    for item in list:
        if(

        len(item)<MINIMUM_LENGTH):
            print item
    return None
def delete_item(list):
    '''
    Function deletes items in 3 different ways.
    input: list - grocery list
    output: none'''
    print_delete_menu()
    choice = input()
    if(choice is DELETE_ALL_ITEMS):
        requested_item = raw_input("Please enter item (Warning! If it'll be deleted, it will not be saved elsewhere): ")
        requested_item = requested_item.lower()
        if(requested_item in list):
            del list[requested_item]
        else:
            print "item is not in list..."
    elif(choice is DELETE_ONE_ITEM):
        requested_item = raw_input("Please enter item (Warning! If you have only one of this item, this item will be deleted totally and won't be aved elsewhere): ")
        requested_item = requested_item.lower()
        if(requested_item in list):
            value = list[requested_item]
            value -= 1
            list[requested_item] = value
            if(value is 0):
                del list[requested_item]
        else:
            print "item is not in list..."
    else:
        print "invalid input..."
    return None
def total_sum (list):
    sum = 0
    for item in list:
        sum += list[item]
    return sum
def register (users):
    username = 0
    while(username != "stop"):
        username = raw_input("""Enter username, enter "stop" to return to the login menu: """)
        if(username in users):
            print "username already exist"
        else:
            users[username] = {}
            return username
def login (users):
    username = raw_input("Enter your username ")
    if(username in users):
        return True, username
    else:
        print "username not exist"
def users_menu (users, list):
    access = False
    while(not access):
        print_login_menu()
        choice = input()
        if(choice is LOGIN):
            access, username = login(users)
        elif(choice is REGISTER):
            username = register(users)
            if(username != "stop"):
                get_input(list)
            else:
                users_menu(users, list)
        else:
            print "invalid input"
    return username
def print_login_menu ():
    print "1. login"
    print "2. register"
def catalog_list_by_username(users, username, list):
    users[username] = list
    for item in list:
        print item
        del list[item]
def main():
    grocery_list = {}
    users = {}
    choice = 0
    print users
    while(choice is not EXIT):
        username = users_menu(users, grocery_list)
        choice = 0
        print users, "2"
        while(choice is not EXIT and choice is not LOGOUT):
            print users, "3"
            print_menu()
            choice = input()
            if(choice is WATCH_LIST):
                print grocery_list
            elif(choice is WATCH_HOW_MANY_ITEMS_IN_LIST):
                print len(grocery_list)
            elif(choice is CHECK_IF_ITEM_IS_IN_LIST):
                item = raw_input("Please enter item ")
                print item in grocery_list
            elif(choice is SHOW_THE_NUMBER_OF_TIMES_ITEM_IS_IN_THE_LIST):
                item = raw_input("Please enter item ")
                print_num_of_times_item_is_listed(grocery_list, item)
            elif(choice is DELETE_ITEM):
                delete_item(grocery_list)
            elif(choice is ADD_NEW_ITEM):
                add_item_to_the_list(grocery_list)
            elif(choice is WATCH_INVALID_ITEMS):
                print_invalid_items(grocery_list)
            elif(choice is TOTAL_SUM):
                total_items_sum = total_sum(grocery_list)
                print "the total sum of your list is", total_items_sum
            elif(choice is LOGOUT):
                print "Goodbye,", username + "..."
                catalog_list_by_username(users, username, grocery_list)
            elif(choice is not EXIT):
                #The choice is neither 10 (exit) nor any of the above choices
                print "invalid input..."
    print "GoodBye :)"
    return None
main()

A: You are only creating one grocery_list in main(), and then reusing it for all users. As a result, all items get appended to the same list. You could make the following changes in main() to create separate lists for each user:
def main():
    # change the next line from grocery_list to grocery_lists
    # (this dictionary will hold one grocery list for each user)
    grocery_lists = {}
    users = {}
    choice = 0
    print users
    while(choice is not EXIT):
        username = users_menu(users, grocery_list)
        # add the next few lines to select the right list for the current user
        if username not in grocery_lists:
            # make a grocery list for this user
            grocery_lists[username] = {}
        # retrieve the grocery list for this user
        grocery_list = grocery_lists[username]
        # code below here is unchanged...


text:
Q: Multiple where statement returning undesired result I'm trying to retrieve employees within depts 10 and 30 with a salary greater than 1500. This is the statement I'm running.
select ename, sal
from emp
where deptno = 10
or deptno = 30
and sal > 1500;

It returns:
Name               Salary
---------- --------------
NAME1                1600
NAME2                2850
NAME3                2450
NAME4                5000
NAME5                1300

When I run the query without the OR for only one dept, it returns NAME1 and NAME2, when I run it for the other dept it returns NAME3 and NAME4.
My question is, is it the OR statement that's giving me the incorrect NAME5? To me that query should work, I tried using AND instead of OR and it gives me no results. Any help would be appreciated.

A: AND has precedence over OR in a SQL WHERE clause, so what you have is equivalent to
where deptno = 10 or (deptno = 30 and sal > 1500)

Try putting parentheses around the OR to see if it gives you the results you expect.
where (deptno = 10 or deptno = 30) and sal > 1500

(Also, it would clarify things a little bit if you included the department number in your SELECT so you can see which department each row is coming from.)

A: Your problem is the lack of parentheses.  But really the best way to write the query uses in:
select ename, sal
from emp
where deptno in (10, 30) and
      sal > 1500;


text:
Q: Post form to MailChimp, but display dynamic success page I am working on a MailChimp subscription form that will need to send the form $_POST data to MailChimp, but not actually load the success page. I.e. I want it to load custom JS on submission. This is what I have so far. Obviously the preventDefault is breaking the submission. Any thoughts are greatly appreciated:

<link href="http://cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">

<form action="http://yourmove.us5.list-manage.com/subscribe/?u=00000444444333331&id=aaa111444iiii" method="POST" id='mc_embed_form'>

Subscribe to Our Newsletter/em> for your free download:

    <input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button" novalidate>

</form>

A: You are missing a parameter in your function, try this one:
$(document).ready(function(){
    $("#mc_embed_form").submit(function (event){
            event.preventDefault();
            showConfirmation();
    });
});


text:
Q: Install osmosis without wget and still create its folder? I am trying to install osmosis onto my Ubuntu 16.04 PC.
I tried to do it using this explanation, but I can't download osmosis-latest.tgz because the link throws a 404 error.
Now I installed it by simply using apt-get install osmosis which worked well, but I don't know what to do about the osmosis folder which the above explanation creates. I just created an empty folder now, but that's surely not what I would like to have I guess.
PS: As you can tell, I'm new to this.

A: You don't need this step when using the package manager. This directory is only created for storing the files from the previously downloaded osmosis archive. Since you already installed osmosis via package manager there is no need to store manually downloaded osmosis files inside this directory.
However, it might be a good idea to use the latest osmosis release. The latest release is available via https://github.com/openstreetmap/osmosis/releases (which is also mentioned on the wiki page). In this case follow the installation guide, including the creation of this directory.
By the way, I updated the wiki page and removed the dead link.
Also keep in mind that osmosis isn't maintained very well. As of today there are better alternatives such as osmium, as already mentioned by user @mmd.


text:
Q: Is it possible to run SharePoint 2013 on SQL Server using Compatibility Level 120 I need to migrate a SQL Server 2014 instance supporting SSAS/SSRS and SharePoint 2013 to SQL Server 2016. Unfortunately, I won't be able to have separate instances.
I've read that SharePoint 2013 isn't compatible with SQL Server 2016 but can't find if running it in Compatibility Level (120) is possible.
I would really appreciated some feedback if you have tested this setup.
Thank you very much for your support.
Best Regards


text:
Q: Trouble pairing Raycon earbuds with 18.04 Bluetooth system I bought a pair of Raycon Earbuds and for some reason I am having trouble pairing them with my Ubuntu 18.04 system. My Bluetooth headphones work fine and I managed to pair them (earbuds) with my phone just fine but for some reason although the machine does recognize them (shows them in the Bluetooth device tree) as "Not Set Up" when I click them the "Not Set Up" string turns into a loading symbol for a second then just goes back to "Not Set Up". I tried:
sudo add-apt-repository ppa:bluetooth/bluez
sudo apt update
sudo apt install bluez

but that did not help. Any ideas why I can't pair this device? I am using a simple Bluetooth dongle: Panda BT 4.0.

A: I had the same exact issue and thought about it for a few minutes then decided to turn off the Bluetooth on my phone and try pairing with my computer. After doing this, they worked perfectly fine.
I think what happened is the earbuds themselves are only able to have one device approaching them and whichever device latches on first trumps the other(s)
Hope this helps

A: Edit /etc/init.d/bluetooth and make sure ControllerMode is
ControllerMode = dual

If you needed to change it, make sure to restart your bluetooth service with
sudo /etc/init.d/bluetooth restart


text:
Q: flash music player not playing after second time i am new to flash. i was created flash player for my online radio. it's working fine first two time when i use the stop and play button. the third time it will not playing. i don't know why is not playing , i am using action script 3.0 , my action script is here
import flash.events.MouseEvent;
import flash.media.Sound;
import flash.net.URLRequest;
import flash.media.SoundChannel;
import fl.events.SliderEvent;

// objects

var soundfile:URLRequest = new URLRequest('http://www.xxx.com:80/;stream1.mp3');
var channel:SoundChannel = new SoundChannel();
var sTransform:SoundTransform = new SoundTransform();

// controls
btnplay.addEventListener(MouseEvent.CLICK,playmusic);
btnstop.addEventListener(MouseEvent.CLICK,stopmusic);
sldVolume.addEventListener(SliderEvent.CHANGE,changevolume);

function playmusic(evt:MouseEvent):void
{
    var myMusic:Sound = new Sound();
    myMusic.load(soundfile);
    myMusic.play();

}
function changevolume(evt:SliderEvent):void
{
    sTransform.volume = sldVolume.value;
    channel.soundTransform = sTransform;
}

function stopmusic(evt:MouseEvent):void
{
    sldVolume.removeEventListener(Event.COMPLETE, changevolume);
    SoundMixer.stopAll();
}


text:
Q: Using tables to categorise resources with I'm trying to design a database that allows for filtering according to if a specific resource fills certain categories. I've gotten to the point where I can input data that seems to be how it should be filled out but I'm not sure how I should pull it out again.
The main resource table looks like this:
Table1 - resources
| resourceID   | AutoNum    |
| title        | short text |
| author       | short text |
| publish date | date       |
| type         | short text |

Table2 - Department Categories
| ID | AutoNum |
| 1  | Yes/No  |
| 2  | Yes/No  |
| fID| Number  |

Table3 - Categories
| ID   | AutoNum |
| cat  | Yes/No  |
| dog  | Yes/No  |
| bird | Yes/No  |
| fID  | Number  |

I have built a form where you can fill in items to the resource ID, and at the same time check off the Yes/No boxes in tables 2 & 3.
I'm trying to use the primary key ID from table 1 and copy it into the table 2 & 3 with referential integrity to cascade deletes, updates. Which I think is the right way to do this.
Currently, I've learnt that I can implement a search function for the columns in table 1, this seems to work fine. However I am stuck with applying the relevant columns in table 2 and 3 as filters.
apply search>
[X] - Cats
Should only return records from table 1 where in table 3 the relevant column has a tick in the Yes/No box.
I hope I have explained this properly, very new to Access and databases so if you need clarity, don't mind offering.


text:
Q: WebSocketProxyException 403 when trying to submit image with praw on pythonanywhere I'm trying to use praw on pythonanywhere to natively upload an image to reddit.
praw.models.Subreddit.submit_image(title, image_path)
This works fine on my computer, but on pythonanywhere it throws a 403 error. (The image still gets uploaded though.)
I see on pythonanywhere's website that 403 errors are due to their proxy whitelist, but reddit is one of the whitelisted websites and praw uses requests which pythonanywhere says is a compatible library. Also the regular submit works fine.
File "/home/ibid/.local/lib/python3.7/site-packages/praw/models/reddit/subreddit.py", line 780, in submit_image
    return self._submit_media(data, timeout)
File "/home/ibid/.local/lib/python3.7/site-packages/praw/models/reddit/subreddit.py", line 494, in _submit_media
    response["json"]["data"]["websocket_url"], timeout=timeout
File "/home/ibid/.local/lib/python3.7/site-packages/websocket/_core.py", line 514, in create_connection
    websock.connect(url, **options)
File "/home/ibid/.local/lib/python3.7/site-packages/websocket/_core.py", line 223, in connect
    options.pop('socket', None))
File "/home/ibid/.local/lib/python3.7/site-packages/websocket/_http.py", line 122, in connect
    sock = _tunnel(sock, hostname, port, auth)
File "/home/ibid/.local/lib/python3.7/site-packages/websocket/_http.py", line 293, in _tunnel
    "failed CONNECT via proxy status: %r" % status)
websocket._exceptions.WebSocketProxyException: failed CONNECT via proxy status: 403

A: I wrote the image-submit feature in PRAW. As is noted in the documentation, the Reddit API uses websockets when submitting images or videos through the API. This is different from how the API works for text or link submissions, which directly return the URL of the created post. When it comes to images and videos, the response is something like
{'json': {'data': {'user_submitted_page': 'https://www.reddit.com/user/username/submitted/',
                   'websocket_url': 'wss://ws-05ba9e4989f78959d.wss.redditmedia.com/rte_images/z4a98g21vsb31?m=AQAAHFs1XR-NRjAq9D4PPYA6SuDvFIMUGGv2Vpv5ePM2bLV6wf5o'},
          'errors': []}}

We then have to listen on the websocket URL to eventually get the url of the created post. If you're interested, the relevant code is here.

As you found, the websocket URLs (at least at the time of this answer) tend to be a subdomain of *.wss.redditmedia.com. redditmedia.com isn't on the PythonAnywhere whitelist (though reddit.com itself is), so the connection fails.
I see a few solutions for you, given here with what I think is most ideal first:

*

*Get Giles Thomas (who left a comment) or someone else from PythonAnywhere to whitelist subdomains of wss.redditmedia.com.

*In PRAW >=6.5.0, pass the parameter without_websockets=True to disable the use of websockets. As noted in the documentation of submit_image, setting this to True means that you won't get a return value at all.

*In PRAW <6.5.0, use a try-except block around every use of submit_image. As you discovered, the posts will still be created. However, you will not receive a Submission object as a return value because the websocket will fail.

*Pay to upgrade to the non-whitelisted version of PythonAnywhere.


text:
Q: Не работает функция unique для vector почему не удаляются дубликаты из вектора?
#include <vector>
#include <iostream>
#include <algorithm>
#include <time.h>

using namespace std;

 void printVector(vector<int> & v);

int main() {
    vector<int> v;

    srand(time(0));

    for (int i = 0; i < 10; i++){
        v.push_back(rand() % 9);
    }

    printVector(v);
    sort(v.begin(), v.end());
    cout << endl;
    printVector(v);
    unique(v.begin(), v.end()); // не работает
    cout << endl;
    printVector(v);

    return 0;
}

void printVector(vector<int> & v){
    for (vector<int>::iterator it = v.begin(); it != v.end(); it++){
         cout << *it << endl;
    }
}

A: Делайте так:
v.erase(
    unique(v.begin(), v.end()),
    v.end());

Дело в том, что std::unique лишь сдвигает дублирующиеся элементы в конец вектора, но не удаляет их оттуда. (Он также возвращает итератор, указывающий на первый из "ненужных" элементов.)


text:
Q: Get cloned rows and columns to move inside surrounding div I've almost got a frozen header and left column working. Can anyone tell me how to get the cloned tables that contain the header row and left column to appear inside the div that encloses the main table - and how to get the cloned header and cloned column to scroll when appropriate.
Someone has posted the code below for me ... but it does not display or run properly on here when you click 'Run Code Snippet'. This fiddle shows the display issues I am having.

var $target = $("#targetT");

$("#sourceT tr").each(function() {
  var $clone = $(this).clone();
  $clone.children(':gt(0)').remove();
  $clone.height($(this).height());
  $target.append($clone);
});

var $targethead = $("#targetThead");
$("#sourceT tr:first").clone().appendTo($targethead);
$("#sourceT").find('tr').first().children().each(function(i, e) {
  $($("#targetThead").find('tr').children()[i]).width($(e).width());
});
.gv {
  border-collapse: collapse;
  border-spacing: 0;
  z-index: 100;
  background-color: White;
}
.gv td {
  white-space: nowrap;
  border: 1px solid #CCCCCC;
  padding: 0.2em;
}
.gvOver {
  background-color: White;
  border-collapse: collapse;
  border-spacing: 0;
  z-index: 150;
  position: fixed;
  top: 21px;
}
.gvOver td {
  white-space: nowrap;
  border: 1px solid #CCCCCC;
  padding: 0.2em;
}

      Name
      Heading
      Heading
      Heading
      Heading

      Fred
      Some random text
      Some random text
      Some random text
      Some random text

      Martha
      Some random text
      Some random text

Bigger row
      Some random text
      Some random text

      William
      Some random text
      Some random text
      Some random text
      Some random text

      Samantha
      Some random text
      Some random text
      Some random text
      Some random text

      Brian
      Some random text
      Some random text
      Some random text
      Some random text


text:
Q: Aes encryption and decryption Work Fine With .Net Core 3.1 but not work with .Net 6 I have update the my project fretwork from .Net Core 3.1 to .Net 6. bellow code working fine with 3.1 but not working with .Net 6. In .net 6 I have missing some data, Like if I encrypt "Ravi Chandra" and than decrypt, I got "Ravi Chand". please suggest any solution.
public class AESEncryption
{
    private const string _IV = "Encryption";
    private const string _Key = "TestEncryption";
    private const int _BlockSize = 128;
    public static string Encrypt(string plainText)
    {
        if (string.IsNullOrEmpty(plainText))
            return ""; byte[] bytes = Encoding.Unicode.GetBytes(plainText);
        using (Aes crypt = Aes.Create())
        {
            using (HashAlgorithm hash = MD5.Create())
            {
                crypt.BlockSize = _BlockSize;
                crypt.Key = hash.ComputeHash(Encoding.Unicode.GetBytes(_Key));
                crypt.IV = hash.ComputeHash(Encoding.Unicode.GetBytes(_IV)); using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream =
                    new CryptoStream(memoryStream, crypt.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(bytes, 0, bytes.Length);
                    }
                    return Convert.ToBase64String(memoryStream.ToArray());
                }
            }
        }
    }
    public static string Decrypt(string ciphertext)
    {
        if (string.IsNullOrEmpty(ciphertext))
            return ""; byte[] bytes = Convert.FromBase64String(ciphertext);
        using (Aes crypt = Aes.Create())
        {
            using (HashAlgorithm hash = MD5.Create())
            {
                crypt.Key = hash.ComputeHash(Encoding.Unicode.GetBytes(_Key));
                crypt.IV = hash.ComputeHash(Encoding.Unicode.GetBytes(_IV));
                using (MemoryStream memoryStream = new MemoryStream(bytes))
                {
                    using (CryptoStream cryptoStream =
                    new CryptoStream(memoryStream, crypt.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        byte[] decryptedBytes = new byte[bytes.Length];
                        cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length);
                        return Encoding.Unicode.GetString(decryptedBytes).Replace("\0", "");
                    }
                }
            }
        }
    }
}