text:
Q: ORA-01847 day of month must be between 1 and last day of month i made some research about it but i couldn't figure it out. My problem is i can't add new record oracle database because of ORA-01847 error.
I try to add this date value to database: 23.07.2017 18:10:00
$MYDATE= $data[$i]->MYDATE;
//I ALSO ADD THIS LINE
$str = oci_parse($conn, "ALTER SESSION SET NLS_DATE_FORMAT = 'DD.MM.YYYY HH24:MI:SS'");
oci_execute($str);
//
$sql = 'INSERT INTO MYTABLE(ID,MYDATE)'.'VALUES(:ID,:MYDATE)';
$compiled = oci_parse($conn, $sql);
oci_bind_by_name($compiled, ':ID', $ID);
oci_bind_by_name($compiled, ':MYDATE', $MYDATE);
oci_execute($compiled);

however it gave me error:

ORA-01847 day of month must be between 1 and last day of month error.

A: You can additionally try to execute this line after you change NLS_DATE_FORMAT in your php code.
ALTER SESSION SET NLS_DATE_LANGUAGE = 'AMERICAN';

It is possible sometimes  that setting NLS_DATE_FORMAT has no effect if NLS_DATE_LANGUAGE is unset.

A: add this trigger your database
CREATE OR REPLACE TRIGGER USER_NAME.MY_SET_DATE after logon on database
begin
if (user = 'USER_NAME') then
execute immediate
'alter session set nls_date_format = ''YYYY-MM-DD'' ';
-- execute immediate
--'ALTER SYSTEM SET SEC_CASE_SENSITIVE_LOGON = FALSE' ;

end if;
end my_set_date;


text:
Q: Android instrumentation How do I make a test project using instrumentation that tests an application from an Android device not from command line. I think I should add a dependency in the manifest.xml file but not sure how to do this.
Is there any good tutorial of doing this?
Thank in advance..

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the object id of the document in a mongodb collection during mongotemplate.save operation is executed? Using MongoTemplate, I have saved a json in a collection. The objectid is generated automatically by MongoDB, I suppose.
How to get the objectid at the instant while saving?
mongotemplate.save(data,"collection");

A: If I understand you right you can do this, if Object "data" has field "id"
mongotemplate.save(data,"collection").getId();


text:
Q: Destructuring object in a event handler parameter const handleChange = ({ target }) => {
    const name = target.name;
    const value = target.value;
    setProfile({
      [name]: value
    });
  };

<input  value={phone}  onChange={handleChange} id='phone-input'/>

How its possible that JS knows that target is in the object of the SyntheticEvent?
Why i dont need to do this: handleChange(event)?
What if there is a other object with a target property?
I have learned this:
let truck = {
  model: '1977 Mustang convertible',
  maker: 'Ford',
  city: 'Detroit',
  year: '1977',
  convertible: true
};

const printCarInfo = ({model, maker, city}) => {
  console.log(`The ${model}, or ${maker}, is in the city ${city}.`);
};

printCarInfo(truck);


text:
Q: Ring homomorphism from Wiki From the page of Wiki:
$f: \mathbb Z_6\rightarrow Z_6$ defined by $f([a_6])=[4a_6]$ is a ring homomorphism.
$f(a)=\{a_n\}=a \pmod n$.
The kernel is $3\cdot \mathbb Z_6$ and image is $2\cdot\mathbb Z_6$.
I don't know if I understood well:
is $3\cdot \mathbb Z_6=\{0,3,6,9,12,15\}$?
Is $\mathbb Z_6=\{0,1,2,3,4,5\}$?
Can somebody explain why kernel and image are $3\cdot \mathbb Z_6$ and $2\cdot\mathbb Z_6$?
reduced mod 6 is $3\cdot \mathbb Z_6=\{0,3\}$?

A: The kernel of the map are all the elements $a \in \mathbb Z_6$ such that $f(a) = 6 k$ for some $k \in \mathbb Z$ (because these elements are zero mod $6$). We get $4a = 6k$ for some $k \in \mathbb Z$ for $a=0, a=3$, so the kernel is
$$3 \cdot \mathbb Z_6 = \{0,3\}$$
because $3 \cdot \mathbb Z_6 = \{0,3,6,9,12,15\} = \{0,3\}$ reduced mod $6$.
In a similar fashion we get
$$\text{Im}(f) = \{0,4,8,12,16,20\} = \{0,2,4\} = 2 \cdot \mathbb Z_6$$


text:
Q: How can I push element to array in http.put in angularjs? I have the following schema:
var UserSchema = new Schema({
  name: String,
  email: { type: String, lowercase: true },
  projects: [{type: Schema.ObjectId, ref:'Project'}],
  //....
}

How can I add projectId by using http.put?
This is among the things that I have tried:
$http.put('/api/users/'+User._id, {'projects': project._id});

A: Solved it using:
$http.put('/api/users/'+User._id, {'projects': User.projects});
and in my update method:
_.extend(user, req.body);
instead of
_.merge(user, req.body);


text:
Q: Cannot create a react native library I've been creating a react native component library since a month now, and I think it's ready to be posted as a package on npm. So I pushed it on github, I npm publish, everything's fine.
To publish it, I replaced my index.ts:
// index.ts
import createRComps from 'Base.tsx';

export default createRComps; // That's the only object I need to export because it calls the others from itself

I also tried to use create-react-native-library on another copy of this repo, which didn't get any more success.
Now, I create another react native project to test my new library : I install my library with npm i react-native-ready-comps, add some of my lib's code in it :
export default function App() {
  const RComps = createRComps();  // my lib's main function

  return (
    <RComps.Title bold>Hello world !</RComps.Title>    // one of my lib's components
  );
}

But when I launch it with metro (npx react-native run-android && npx react-native start), I get this error :
 ERROR  TypeError: Cannot read property 'createNode' of null, js engine: hermes
 ERROR  Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication(). Module has not been registered as callable. Registered callable JavaScript modules (n = 10): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter, GlobalPerformanceLogger, JSDevSupportModule, HMRClient.
        A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes
 ERROR  Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication(). Module has not been registered as callable. Registered callable JavaScript modules (n = 10): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter, GlobalPerformanceLogger, JSDevSupportModule, HMRClient.
        A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes

I know it comes from my lib, but I didn't encoutered this problem when I was working on it. Maybe did I miss something when publishing it ?
Can you please explain me what I did wrong ? And if you have resources on how to export a react native component library, I'dd be glad if you shared them ! Everything I found on Google/Stack couldn't help me.
Thanks a lot !
PS : here is the repository of my library, if you want to see the code. As soon as it's a project problem, I cannot create a minimal reproducible example...


text:
Q: Is it possible to run individual test cases/test classes on the command line with xcode 5? I can run all unit tests using the following command:
xcodebuild test -workspace Project.xcworkspace -scheme Scheme -sdk iphonesimulator7.0 -destination platform='iOS Simulator',OS=7.0,name='iPhone Retina (4-inch)'

Is there anything I can pass to this to run individual unit tests/classes in the same way that you can using the Xcode UI?
Cheers.

A: Not that I know of, and it's not on the man page either. But you have such option in the excellent xctool (-only SomeTestTarget:SomeTestClass/testSomeMethod).

A: For those who are using later versions of Xcode (8.0+) and may run across this post in the future (like myself), this is now possible using the -only-testing flag, which is documented in the man page for xcodebuild. The format for using the flag is as follows:
xcodebuild \
    -destination "$DEST" \
    -workspace "$WRKSP" \
    -scheme "$SCHEME" \
    -only-testing:Target/Class/Method test

You can also omit elements from the path after the -only-testing flag, e.g. -only-testing:Scheme/Class will run all these tests within that class.
Here is a related Stackoverflow question, touching on the new functionality:
How to use xcodebuild with -only-testing and -skip-testing flag?

A: Another way is to edit the schemer of your test file and disable/enable the tests as you please. Then you can rerun the same command through the CLI and it will only run the tests you specified above.

A: If you're using Kiwi, you should supposedly be able to do it using the KW_SPEC environment variable. I haven't been able to, though: Running a single KIWI spec with xctool.


text:
Q: Excel Power Query. Run multiple queries by list of templates to join tables in different files I have a question:
I have 60+ tables in dbf with columns: year, product, value. Tables have different years data.
EXAMPLE.
Table 1
Year  product value
1993     Apple  98.45
1994   Mushrooms 67.54

Table 2
Year  product value
1992  Apple  95.45
2021  Melon 112.0

I need a pivot table(to consolidate) all tables in one table.
My way:
Let
DatesList={1992, 1993,1994,1995,2021},
Tbl=Odbc.Query("dsn=my_custom_dsn", "select * from c:\data\1993.dbf"),
Result=List.Accumulate (DatesList, Tbl, (state, current) =>Table.Join(Tbl, "product", Query.odbc("dsn=my_custom_dsn", "select * from c:\data\" +Text.From(current) +".dbf", "product")

in
 Result

Its ok, but results only for the last date. How to save Table between dates
Please, help

A: I think you are overcomplicating.
Try this:
let
      DatesList = Table.FromList({1992,1993,1994,1995,2021}, Splitter.SplitByNothing(), {"Year"}, null, ExtraValues.Error)
    , #"Added Custom" = Table.AddColumn(DatesList, "Data", each Odbc.Query("dsn=my_custom_dsn", "select * from c:\data\" & Number.ToText([Year]) & ".dbf"))
    , #"Expanded Data" = Table.ExpandTableColumn(#"Added Custom", "Data", {"product", "table"}, {"product", "table"})
in
    #"Expanded Data"

Remember in your question you misspelled Odbc.Query


text:
Q: Why does YouTube's JavaScript API cause errors when unloading in IE8? At this point I'm stumped.  The below embed code causes "Object Required" errors every time I refresh the page in Internet Explorer 8 (probably other versions of IE as well but I don't have them readily available for testing).
It works just fine in other browsers.
The oh so simple code:
<object width='425' height='344'>
    <embed src='http://www.youtube.com/v/3kU1x9StavM?enablejsapi=1' type='application/x-shockwave-flash' width='425' height='344' allowscriptaccess='always' allowfullscreen='true'></embed>
</object>

It errors even when that is literally the only content on the page.
Does anyone have any ideas?  I don't have the option of using swfobject because I'm going to be rewriting embed tags to enable jsapi (I'm writing an interactive transcript plugin that needs to essentially load itself and require no extra action on the part of the publisher to use).

A: Embedding with SWFObject is definitely a right way to do it. We have encountered exactly the same problem in IE6+ and it went away once swf object was used to embed the video.

A: There is a problem with the js api on IE... others have talked about it here http://support.soundcloud.com/soundcloud/topics/sets_breaking_in_ie8
If you remove the jsapi parameter or set the value of allowscriptaccess to sameDomain or never the errors disappear but you can't use the API anymore :(

A: Unfortunately I was never able to get to the bottom of this.  Which is frustrating.
Ultimately IE has some issues with binding events to flash objects when the object is created out of order.
I ended up just using swfobject.js after all.  They work some magic somewhere that I couldn't reproduce.

A: This is occurring because of javascript calls on page unload to an object that no longer exists (the video embed). The code below removes the embed before the page unloads, hence no more errors in IE8:
Event.observe(window, 'beforeunload', function(){
    var player = $("video-embed-element");
    player.remove();
}, false);

I'd also highly recommend surrounding the code with an IF statement that checks to make sure the browser is IE8, as described here


text:
Q: sql alphanumeric with range start & end I have a problem, how to search alphanumeric with range (start & end) such as below :

if i use BETWEEN, the result will problem with the number that have letter at the end, in pic/table = Input 2.
So, how can i to get the Id 6 result when keyin HSF3145858B
pls advise
Thank You

A: That is because between uses alphabetical ordering. You should probably add another check to confirm that the searched code is the same length as the start and/or end. This could be done by putting parenthesis around the first clause and adding AND (len('$serialno') = len (Start))
This would lead to the following which should work
$tsql = "SELECT Product FROM tbl_serial_range WHERE ('$serialno' BETWEEN Start AND End) AND (len('$serialno') = len (Start)) ";


text:
Q: Is there an option to toggle between two units of currency? With most currencies there two units of currency, for example, pounds/pence, dollars/cents. Is there a way to toggle between these two units when displaying currency data (preferable using react-intl)?

A: It's not possible to format numbers as sub-divisions of a currency in the default Intl API (10 cents, 25 paise, etc). Hence, it's also not possible via the react-intl library.


text:
Q: Hexadecimal NCR characters doesn't work in IE For a web page  need some special characters (like ones bellow) that I found here.

Converted Decimal NCR values works fine in FF, Safari and Chrome. But not on IE where I get strange square character. Page is UTF8 encoded.
For example this is the code for one character:

This is what I get on Safari, FF and Chrome:

And this is on IE8:

Could please someone explains why this does not work in IE?


text:
Q: What is difference between ckanext-ngsiview and right_time_context plugin CKAN? I had a query that what is difference in ckanext-ngsiview and ckanext-right_time_context plugin in ckan?
I was using ckanext-ngsiview of conwetlab,They have made another release and renamed it to right_time_context.
While,I was working with the latter plugin,I did'nt recieved the expected result which I used to receive with ngsiview.(Screenshot attached)
Also,do I need to enable any other  plugin for right_time_context?

After adding the id as ngsi_view in my (development.ini file) I get the following error as follows

I am not being rendered the NGSI-VIEW after adding right_time_context as id in my (.ini file)

A: The plugin has evolved and is not only a view for NGSI anymore, so we think that the name was not representing the functionality. On the other hand, Telefónica has the previous name registered on pypi, so we cannot make releases using that name. Apart from that, the new version is an evolution of the previous releases we did.
That message means that there is no view configured for that resource. I guessing you are complaining because the raw NGSI view was not configured automatically (in fact this can be perfectly ok since you may want to manually add views).
To enable automatic configuration of the raw view, make sure you include the ngsi_view view into the ckan.views.default_views setting. The important detail here is that the id of the view has changed from ngsiview to ngsi_view in this new version. Take into account that this is not the id of the plugin that is right_time_context and this id is the one you have to use to enable the plugin using ckan.plugins.

Also, do I need to enable any other plugin for right_time_context?

The resource_proxy plugin (comes directly with CKAN, but has to be enabled), is required for using the raw view, although it is optional if you don't need that view.
The ckanext-oauth2 plugin is required to make request to secured Context Broker instances.


text:
Q: get additional info from facebook-sdk using python I am using python to get info data from facebook api.
I use the following code:
import facebook
import requests
token = 'mytoken'
graph = facebook.GraphAPI(token)

profile=graph.get_object("me")

but only the name and the id are returned. Thus i cannot use the command
profile["gender"]

in order to get the user's gender.
How can i fix that?
thank you!!


text:
Q: How we can diff log files by ignoring first two lines of the files? I need to diff two log files but ignore first two line (As it contains Date) and print the output which is not common

A: To skip first two lines you can use tail like this
tail -n +3 file

You can then write a diff command like this:
diff < (tail -n +3 file1) < (tail -n +3 file2)

The diff command prints the difference between the two files.


text:
Q: The average distance from the centre of a square or rectangle to a point within this shape I know that for a circle, the average distance from the center to a point is $(2/3)\sqrt{A/pi}$ in which A is the surface of the circle. This is understandable for me. However, I am wondering about a formula to calculate the average distance from the center of a square and rectangle to a random point.
I have found similar questions on this forum, but I have not yet found an answer that I could grasp my mind around. I can imagine that for the rectangle, it would incorporate like a length vs. width ratio or something.
Can somebody point me in the right direction?

A: Answer depends on random points distribution.
Let this distribution is uniform by area.
Let center of rectangle is $O(0;0)$, sides are parallel to axes and one of vertices is $A(a;b)$ with $a>0$, $b>0$. Then all rectangle points are given by inequalities $$-a<x<a \land -b<y<b$$ Let $(x;y)$ is random point, then distance from this point to center is $\sqrt{x^2+y^2}$. Then average distance is $$\frac{1}{4ab}\int_{-a}^a \int_{-b}^b \sqrt{x^2+y^2}\,dy\,dx=\\
\frac{1}{6ab} \left(a^3 \ln \left(\frac{b+\sqrt{a^2+b^2}}{a}\right) +2 ab
   \sqrt{a^2+b^2} +b^3 \ln
   \left(\frac{a+\sqrt{a^2+b^2}}{b}\right)\right)$$


text:
Q: как сделать передвижение в сторону мыши unity 2D top-down Я не понимаю как мне сделать передвижение в сторону мыши. Я до этого использовал передвижение через "Horizontal" и "Vertical", но понадобилось передвижение в другом стиле. Что у меня есть? Вот....
public Vector3 mousePosition;
public float Speed;

void Start()
{

}

void FixedUpdate()
{
    if(Input.GetKeyDown(KeyCode.W))
    {

    }

    faceMouse();
}

void faceMouse()
{
    mousePosition = Input.mousePosition;
    mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
    Vector2 directione = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);
    transform.up = directione;
}


text:
Q: Facebook album title export Hi I am making a facebook photo album GUI for my website.
Now I already got it woriking in the way that I have my list of albums and can select one and show the photos of it.
But now I have the problem that I cant import the title of the album.
The script I use:
    <?php
//Get Albumdata
$naamDataRuw = file_get_contents('https://graph.facebook.com/'.$_GET['album_id']);
//Decode data
$naamData = json_decode($naamDataRuw);
//Useable data
foreach ($naamData->data as $data)
{
    //Show description or album name as title DOES NOT WORK
    echo '<h2>'.$data->description.'</h2>';
}
?>

Any ideas on how to handle this?
Thanks in advance!


text:
Q: Using RDKit to calcutate Tanimoto similarity between sdf file and a structure SMILE? I'm using RDKIt with Python 3.7 to calculate the similarity of a database in sdf (smile of every structure) with a molecule, of which i have the smile. I found a way to calculate Tanimoto index only between two SMILES using this code:
import numpy as np
import scipy
import matplotlib
import matplotlib.pyplot as plt
import rdkit as  rd
from rdkit import Chem

ref = Chem.MolFromSmiles('Nc1nc2nc(N)nc(N)c2nc1-c1cccc(Cl)c1')
mol1 = Chem.MolFromSmiles('structure smiles')
fp1 = Chem.RDKFingerprint(ref)
fp2 = Chem.RDKFingerprint(mol1)

Tan  =DataStructs.TanimotoSimilarity(fp1,fp2)

print (Tan)

Is there a way to substitute mol1 with a sdf file?

A: You can iterate over a SDF with SDMolSupplier.
from rdkit import Chem, DataStructs

ref = Chem.MolFromSmiles('Nc1nc2nc(N)nc(N)c2nc1-c1cccc(Cl)c1')
fp1 = Chem.RDKFingerprint(ref)

suppl = Chem.SDMolSupplier('yourSDF.sdf')
for mol in suppl:
    fp2 = Chem.RDKFingerprint(mol)
    Tan = DataStructs.TanimotoSimilarity(fp1,fp2)
    print(Tan)


text:
Q: When should pdf files be tracked in a Git repository and when not I am developing a LateX package (http://www.openlilylib.org/lilyglyphs) which contains a number of small PDF files. Currently there are only a few dozens of them but as the package and its user base grows there will probably hundreds of them (but unlikely more than 1000).
The PDFs are typically only a few KB in size, but I don't know whether to track them in the Git repository. The files are subject to change at any time, but probably not too often.
Usually one is told not to track binary files which can't be diffed, but I also have read that this doesn't really matter with smaller files and a smaller overall volume. I think in the end the PDFs will sum up to not more than a few MB in total.
The package will be available as a download or through the Git repository which I prefer because using the package quite naturally leads to contributing ...
Currently when cloning the Git repository one has to rebuild the pdfs using Python and the LilyPond notation software so the stakes are rather high - which is why I would like to have the pdfs directly in the repo.
Any thoughts?

EDIT in response to answers/comments:
The pdf files are generated from the sources in the repository, which is why I'm reluctant to track them in Git.
But:

*

*The pdfs are necessary to use the package so the user needs to have them

*To generate the pdfs one needs Python as well as LilyPond, and both of them are not necessary to use the package. So I feel it is a too big burden to require someone to install two programs just to install my package.
I don't see a problem requiring someone who decides to clone a Git repo to run an install script, but the software dependencies are maybe too high?

*Currently generating the pdfs finishes in reasonable time because there are only a few dozens. But with a growing number of files this time could become inacceptable.

The pdf files change when they are updated/corrected. This won't happen often, and I think this is covered by tracking the source code. But the pdfs will also change whenever there is  a new version of LilyPond available, which may be every two to four weeks. So while the source remains the same the pdfs will change regularely - which is a clear indicator against tracking them with Git.
On the other hand we are talking about (possibly) a few hundred files of a few KB each, so I don't know if it's worth bothering about the issue at all.

A: If the documents don't change, there is no reason to track their changes in git. No revisions, no need for revision control.
But if they do change over time, and someone may need to consult the old document versions for any reason, consider these questions:

*

*Is it impossible or impractical to recreate the old versions of the documents?

*Is there any underlying data outside of version control that has changed, or is it still in the same state?

*Is the data in the documents tied to source code releases?

If the answers to these questions are yes, then they may be good candidates for version control under git.

A: The question is: do you want to use git for source code management/tracking/syncing exclusively or do you want to use it for distribution as well? For smallish projects it simplifies things to do it that way, for big projects it bloats the repo.

A: I know this is an old post but I found it whilst searching so other people might as well.  Here are some options I found
As it has been pointed out, a lot will depend on whether these source files will change over time.
One option you have if they don't change (or change infrequently) would be to keep a copy of them on a server you control or on a Cloud storage option and make your install script download them rather than produce them.
This would probably depend on the user having wget or curl installed but most people do and if they don't, you could always prompt the user to download them manually.
If the PDFs do change with the source frequently, you could look at GIT LFS.  I have never used it myself but have seen it used.


text:
Q: How to exit from a background thread loop? I have a background thread for uploading files.  It runs in a loop; it does some work, then sleeps until a timeout elapses or until it is explicitly notified via a condition variable that there is more work to do. The problem is that sometimes I'm unable to get the thread to exit quickly.
Here is a simplified version:
    std::thread g_thread;
    std::mutex g_mutex;
    std::condition_variable g_cond;
    bool g_stop = false;

    void threadLoop()
    {
        while (!g_stop)
        {
            printf("doing some stuff\n");
            std::unique_lock<std::mutex> lock(g_mutex);
            g_cond.wait_for(lock, std::chrono::seconds(15));
        }
    }

    int main(int argc, char* argv[])
    {
        g_stop = false;
        g_thread = std::thread(threadLoop);

        printf("hello\n");

        g_stop = true;
        g_cond.notify_one();
        g_thread.join();
    }

When I run this test program, I would expect it to exit quickly, but sometimes it gets stuck in the wait_for().  I think maybe the notify_one() is happening before the thread is sleeping in the wait_for(), but after the check of g_stop.
Is there a simple solution to this, or another design pattern that would work better?

A: You are reading and writing the g_stop variable without any synchronisation (such as using atomic operations, or using a mutex to serialize accesses to it). That is a data race, which is undefined behaviour.
Because you don't access it safely the compiler is allowed to assume that no other thread ever modifies g_stop, so in the threadLoop function it can load it into a register once and then never read the variable again, but just keep looping.
To ensure the write to the variable is seen by the looping thread you should use std::atomic<bool> or lock the mutex before all reads/writes to that variable. If you use an atomic<bool> that will fix the undefined behaviour, but doesn't ensure the thread will not wait on the condition variable, because as you suggest there is a window between checking the value of g_stop and going to sleep, in which the main thread can set g_stop = true and signal the condvar, so the looping thread doesn't wait until after the notify_one() call, and so misses it.
This slightly changed version will ensure that the thread will not wait on the condition variable if the main thread has told it to stop:
std::thread g_thread;
std::mutex g_mutex;
std::condition_variable g_cond;
bool g_stop = false;

void threadLoop()
{
    std::unique_lock<std::mutex> lock(g_mutex);
    while (!g_stop)
    {
        printf("doing some stuff\n");
        g_cond.wait_for(lock, std::chrono::seconds(15));
    }
}

int main(int argc, char* argv[])
{
    g_stop = false;
    g_thread = std::thread(threadLoop);

    printf("hello\n");

    {
      std::lock_guard<std::mutex> lock(g_mutex);
      g_stop = true;
    }
    g_cond.notify_one();
    g_thread.join();
}

This works because the looping thread holds a lock on the mutex while it checks g_stop, and it keeps holding that lock until it starts to wait on the condvar. The main thread takes the lock to set g_stop = true, which it can only do while the other thread is waiting.
This means there are only two possible executions now. g_stop = true happens while the thread is waiting on the condvar, and either it wakes up just before the notify_one() call or it wakes up because of the notify_one() call, but in both cases it will see g_stop == true immediately and stop looping.


text:
Q: Passing Boolean as Arg to a command
\usepackage{ifthen}

%booleandeclaration
\newboolean{istest}
\setboolean{istest}{false}

%Set boolean in if
% \newcommand{\activate}[1]{%
% \ifnum#1>0{\setboolean{istest}{true}}\fi }

\newcommand{\activate}[1]{%
  \ifnum#1>0 \setboolean{istest}{true}\fi}

%test boolean of true or false
\newcommand{\test}{\ifthenelse{\boolean{istest}}{TRUE}{FALSE}}%

\activate{10}
\begin{document}
\test
\end{document}

How can I use true or false as args.
\activate{true}

This has to set istest to true.

A: You can do even better: the \returnTorF command accepts an argument in the forms

*

*t, T, true, True, TRUE

*y, Y, yes, Yes, YES

*f, F, false, False, FALSE

*n, N, no, No, NO

*any integer

In cases 1 and 2, it returns true; in cases 3 and 4 it returns false (any capitalization, even TrUe is actually accepted); in case 5, true is returned if the integer is positive, false otherwise.
As an argument you can also use \value{<counter>}, which is a legal integer.
\documentclass{article}
\usepackage{ifthen}% but there are better methods

% we want to accept
%
% t, T, true, True, TRUE, y, yes, YES
%
% or
%
% f, F, false, False, FALSE, n, no, NO
%
% but also integers, with positive ones yielding true
% and nonpositive yielding false

\ExplSyntaxOn

\NewExpandableDocumentCommand{\returnTorF}{m}
 {
  \darkshadow_tf:n { #1 }
 }

\cs_new:Nn \darkshadow_tf:n
 {
  \str_case_e:nnF { \str_casefold:n { #1 } }
   {
    {t}{true}
    {y}{true}
    {true}{true}
    {yes}{true}
    {f}{false}
    {n}{false}
    {false}{false}
    {no}{false}
   }
   { \int_compare:nTF { #1 > 0 } { true } { false } }
 }

\ExplSyntaxOff

\newboolean{istest}
\setboolean{istest}{false}

\newcommand{\activate}[1]{\setboolean{istest}{\returnTorF{#1}}}

\newcommand{\test}{\ifthenelse{\boolean{istest}}{TRUE}{FALSE}}

\begin{document}

\test\ (false)\par
\activate{y}
\test\ (true)\par
\activate{NO}
\test\ (false)\par
\activate{true}
\test\ (true)\par
\activate{0}
\test\ (false)\par
\activate{2}
\test\ (true)\par

\end{document}

A: Adaptations

*

*Use \setboolean{istest}{<true|false>} directly

*or put it into a command (\activate)

Note: You could also use other ways (bool or toggle, see package manual of etoolbox).
Code
\documentclass{article}

\usepackage{ifthen}

%booleandeclaration
\newboolean{istest}
\setboolean{istest}{false}

\newcommand{\activate}[1]{%
    \setboolean{istest}{#1}
}

%test boolean of true or false
\newcommand{\test}{\ifthenelse{\boolean{istest}}{TRUE}{FALSE}}%

\begin{document}
\activate{true}
\test
\activate{false}
\test
\end{document}


text:
Q: How to select specific interesting groups for the boxplot in R Shiny app? I have some information in a file called data.csv. Here is the link to the file https://www.mediafire.com/file/fil4r6noockgl9q/data.csv/file
I'm trying to create a shiny app with that data with the following code.
library(shiny)
library(EnvStats)
data <- read.csv("data.csv")
choi <- unique(data$GENE)

positions <- c("Type1", "Type2",
               "Type4",'Type5', "Type8",
               "Type9", "Type10", "Type6", "Type3", "Type7")
my_comparisons <- list(c("Type1", "Type2"),
                       c("Type1", "Type3"),
                       c("Type1", "Type7"),
                       c("Type1", "Type10"),
                       c("Type2", "Type3"),
                       c("Type2", "Type7"),
                       c("Type2", "Type10"),
                       c("Type3", "Type7"),
                       c("Type3", "Type10"),
                       c("Type7", "Type10"))

ui <- fluidPage(
  titlePanel("values"),
  sidebarLayout(
    sidebarPanel(
      selectInput(inputId = "thegene", label = "Gene", choices = choi, selected = "geneC"),
      selectInput(inputId = "group", label = "Group", choices = my_comparisons, selected=c("Type1")),
      radioButtons(inputId = "colour", label = "Colour", choices=c("white"),selected="white"),
      radioButtons(inputId = "FileType", label = "file type", choices = list("png", "pdf"), selected = "pdf"),
      width = 3),
    mainPanel(
      plotOutput("boxplot"),
      downloadButton(outputId = "downloadPlot", label = "Download"),
      width = 9
    )
  )
)
options(shiny.maxRequestSize = 100*1024^2)

server <- function(input, output, session) {
  vals <- reactiveValues()
  alldat <- reactive({
    choices <- unique(data$GENE)
    selected <- isolate(input$thegene)
    if (!selected %in% choices) selected <- choices[1]
    updateSelectInput(session, "thegene", choices = choices, selected = selected)
    data
  })

  dat <- reactive({
    x <- alldat()
    x[ x$GENE == input$thegene,,drop=FALSE]
  })

  output$boxplot <- renderPlot({
    gg <- ggboxplot(data = dat(), x = "Group", y = "value", color = "Group",
                    add = "jitter")+
      xlab("") + ylab("values") +
      stat_compare_means(comparisons = my_comparisons, label = "p.signif", method = "wilcox.test")
    gg2 <- gg + scale_x_discrete(limits = positions)+
      theme_bw(base_size = 14) + stat_n_text() +
      theme(axis.text=element_text(size=13, face = "bold", color = "black"),
            axis.title=element_text(size=13, face = "bold", color = "black"),
            strip.text = element_text(size=13, face = "bold", color = "black"),
            legend.text = element_text(size=13, face = "bold", color = "black"),
            legend.title = element_text(size=13, face = "bold", color = "black"),
            legend.position = "none",
            axis.text.x = element_text(angle = 90))

    vals$gg2 <- gg2

    print(gg2)
  })

  output$downloadPlot <- downloadHandler(
    filename =  function() {
      paste(input$thegene, input$FileType,sep=".")
    },
    # content is a function with argument file. content writes the plot to the device
    content = function(file){
      if(input$FileType=="png")
        png(file, units="in", width=6, height=7, res=300)
      else
        pdf(file, width = 6, height = 7)
      print(vals$gg2)
      dev.off()
    }
  )
}

# Run the application
shinyApp(ui = ui, server = server)

With the above code, I have it like in the below picture:

To this, I would like to add some more radio buttons/select input where I would like to select the Group (Type1 to Type10), based on my interest.
Along with the above picture, I want to add some options for Group so that I can select only the interesting Group comparisons and download them.
For eg: I want to see the boxplot comparison between Type1 vs Type7 and it should show boxplot only for this comparison and download it.
Another eg: Type1 vs Type5 vs Type4 and it should show boxplot only for this comparison and download it
How do I do this? Can anyone please help me? Thank you.

A: You can use a selectizeInput with multiple = TRUE to select the groups you want to compare. This input can then be used to filter the dataset, the axis limit, and the comparisons you want to test.
I've just pasted the parts below, where I made changes to your code (selectizeInputin the ui, and your renderPlot expression)
ui <- fluidPage(
  titlePanel("values"),
  sidebarLayout(
    sidebarPanel(
      selectInput(inputId = "thegene", label = "Gene", choices = choi, selected = "geneC"),
      selectizeInput(inputId = "group", label = "Group", choices = positions,
                     multiple = TRUE, selected=positions),
      radioButtons(inputId = "colour", label = "Colour", choices=c("white"),selected="white"),
      radioButtons(inputId = "FileType", label = "file type", choices = list("png", "pdf"), selected = "pdf"),
      width = 3),
    mainPanel(
      plotOutput("boxplot"),
      downloadButton(outputId = "downloadPlot", label = "Download"),
      width = 9
    )
  )
)

output$boxplot <- renderPlot({

    # make sure we remove comparisons that are not possible
    comparisons_reduced <- purrr::map(my_comparisons, function(m) {
        if(sum(m %in% input$group) == 2) {
          m
        } else {
          NULL
        }
      }
    )
    comparisons_reduced <- comparisons_reduced[lengths(comparisons_reduced)!=0]

    gg <- ggboxplot(data = dat() %>%
                      dplyr::filter(Group %in% input$group),
                    x = "Group", y = "value", color = "Group",
                    add = "jitter") +
      xlab("") + ylab("values") +
      stat_compare_means(comparisons = comparisons_reduced, label = "p.signif", method = "wilcox.test")

    gg2 <- gg + scale_x_discrete(limits = positions[positions %in% input$group])+
      theme_bw(base_size = 14) + stat_n_text() +
      theme(axis.text=element_text(size=13, face = "bold", color = "black"),
            axis.title=element_text(size=13, face = "bold", color = "black"),
            strip.text = element_text(size=13, face = "bold", color = "black"),
            legend.text = element_text(size=13, face = "bold", color = "black"),
            legend.title = element_text(size=13, face = "bold", color = "black"),
            legend.position = "none",
            axis.text.x = element_text(angle = 90))

    vals$gg2 <- gg2

    print(gg2)
  })


text:
Q: Create 3D Room based on Line Drawing I'm provide LineRenderer to draw the shape of Room in 2D and store the LineRenderer position values in DrawLine.storeLineRenderers list.(List2>)
My plan to create 3D room using 2D Shape , i.e LineRenderer's.

Following code gives convert to 3d, but not accurate
for(int i=1;i<=noOfLines;i++)
    {
        LineRenderer line =GameObject.Find("line" + i).GetComponent<LineRenderer>();
        if(line!=null)
        {
          Vector3[] ss=  DrawLine.storeLineRenderers[i - 1];
          print(ss[0]);  //Position Element 0 value (Vector3)
          print(ss[1]);  //Position Element 1 value (Vector3)

            //generate 3d box (wall) here
          GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
          cube.name = "wall" + i;
          cube.transform.localPosition =new Vector3(ss[0].x,ss[0].y,ss[0].z);

          cube.transform.localScale = new Vector3(ss[1].x - ss[0].x, ss[1].y - ss[0].y,ss[1].z - ss[0].z);

        }
    }

Output

How to solve this?? Is there any formula to create properly??
thanks in advance...

A: try this out.
What you have to be aware of is that the cube's pivot is in its center, meaning you have to add half its size to its position to make it "start" at ss[0] and span all the way to ss[1].
Also, the wall need to be rotated to look at ss[1].
const float thickness = .1f; // how thick will the wall be
const float height = 1f; // how high will the wall be

Vector3 dist = ss[1] - ss[0];
float length = dist.magnitude; // make wall long enough to span ss[0] to ss[1]

Vector3 cubeSize = new Vector3(thickness, height, length);
Vector3 cubePos = ss[0] + (cubeSize * 0.5f); // cube pivot is in its center
Quaternion cubeOrientation = Quaternion.LookRotation(dist, Vector3.up); // rotate to look at ss[1]

GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.localPosition = cubePos;
cube.transform.localScale = cubeSize;
cube.transform.localRotation = cubeOrientation;


text:
Q: CONSULTA SQL ("SUM") Ok, se que haciendo SELECT SUM(column_name) FROM table_name puedo obtener el total de una columna de mi tabla. Ejemplo:
Personas
NOMBRE---- SAUL,Eliz
APELLIDO--- ROMER,Guzman
EDAD------- 21,20
SELECT SUM(Edad) FROM Personas (El resultado sera 41)

¿pero como hago que me muestre los mismos datos (nombre,apellido y edad)y una columna extra con el total de las edades "41"?
hago la pregunta porque ya intente usando group by y el resultado no es el que deseo (La columna extra con el total)
lo que intente fue
SELECT NOMBRE,APELLIDO,SUM(Edad)
FROM Personas
GROUP BY NOMBRE,APELLIDO

A: Puedes usar la cláusula OVER con funciones de agregado y prescindir del GROUP BY
SELECT NOMBRE,APELLIDO,EDAD, SUM(EDAD) OVER() AS SUMAEDAD
FROM Personas

O puedes usar una subconsulta de esta forma:
SELECT A.NOMBRE, A.APELLIDO, A.EDAD, B.SUMAEDAD
FROM Personas A, (SELECT SUM(EDAD) AS SUMAEDAD FROM PERSONAS) B


text:
Q: Why I can't determine locatoin on some devices? Good day. I learnt all about LocationListener and looked through different examples - but every time some tests on different devices make me upset.
So, I ask you for help.
Trouble-devices: Samsung Galaxy S1, Galaxy fit, htc one v, HTC Incredible S,  Pipo Smart S1 and some else.
NoProblem-device: Samsung Galaxy S3. Help :)
Current implementation:
public class LocationListener implements android.location.LocationListener
{
    // Current myLocation
    private LocationManager mLocationManager = null;
    private boolean mLocationEnabled = false;
    private volatile Location mLocation;
    private LocationListener locationListener;
    private volatile boolean locationChanged = false;
    //interface implementation Runnable which called UI methods
    private LocationRunnable runnable = null;

    public LocationListener(Context context, LocationRunnable runnable)
    {
        this.runnable = runnable;
        mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        mLocation = null;
    }

    public boolean enableMyLocation()
    {
        mLocationEnabled = true;
        List<String> mProviders = mLocationManager.getProviders(true);

        if (mProviders.size() > 0)
        {
            locationListener = this;
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, locationListener);

        }

        //start background process to count 30 secs
        new TimeOut().execute();
        return false;
    }

    public void disabledMyLocation()
    {
        if (mLocationManager != null)
            mLocationManager.removeUpdates(this);
    }

    private class TimeOut extends AsyncTask<Void, Void, Void>
    {

        @Override
        protected Void doInBackground(Void... params)
        {
                long sec = System.currentTimeMillis();
               //here we count 30 secs and if method onLocationChanged wasn't run before, start runnable here
                while (!locationChanged && System.currentTimeMillis() - sec < 30 * 1000)
                {}
            return null;
        }

        @Override
        protected void onPostExecute(Void p)
        {
            if (!locationChanged)
            {
                runnable.setLocation(mLocation);
                runnable.run();
            }

        //cancel update
            mLocationManager.removeUpdates(locationListener);
        }
    }

    public void onLocationChanged(Location location)
    {
     //if location is OK so call UI changing
        mLocation = location;
        locationChanged = true;
        runnable.setLocation(location);
        runnable.run();
        //cancel update
        mLocationManager.removeUpdates(locationListener);
    }

}


text:
Q: Show a custom Error page in jQuery on wrong URL I have an application in web which is made by jQuery and HTML. Now if a user put any wrong url say www.abcd.com/menupa instead of www.abcd.com/menu I want to redirect it in my Custom Error page. I searched in web but did not find the solution.

A: You can use .htaccess to do this :
ErrorDocument 404 "
Page not found
"
or
ErrorDocument 404 /404.html

I think its easy to do.

A: ErrorDocument 404 /404.html

Create a file by copying above code but file name should be .htaccess and paste it in your website directory e.g   http://google.com/.htaccess

A: From jQuery API ajax docs:
error option

http://api.jquery.com/jQuery.ajax/


text:
Q: Conditional visibility of a custom property in visual WebPart SharePoint I am editing some feature of a SharePoint visual webPart and I need to add on custom text box property which needs to be appeared if user choose one specific value from another drop down property. I am not sure which attribute I can add to the new text property to make it conditional visible.
If (Action.toString()=="Custom")
 {
    visibility = true
 }

I am not sure I need to work around webBrowsable (true) ?
 Thanks in advance.


text:
Q: THD calculation using microcontroller I want to calculate power supply THD (Total Harmonics Distrotion) using microcontroller.
My current sampling rate is 5000 samples per second to measure other parameters.
I have followed some formulas like using FFT but it is not showing results near by to industrial meters.
If anyone have some methodology or way to find please suggest.
Thanks in advance
-Abhishek

A: Power supplies are not usefully characterized by THD. THD stands for Total Harmonic Distortion, and DC (the desired power supply output) has no harmonics.
The closest thing to THD is pk-pk ripple, or perhaps noise (over a specified bandwidth). In neither case is an FFT a useful tool. In the case of ripple, a scope is the preferred tool, and for noise performance an RMS voltmeter works just fine.


text:
Q: attach onClick handler to populated list item reactjs i have a function that i want to fire when a button is being clicked, this button is included in a list item that gets populated based on values from an array passed from the parent component, but its not working and returning an error saying that the function is undefined, how can i make this work?
import React from 'react';

export default class Card extends React.Component {

constructor(){
  super()
  this.state = {
    index: null
  };
}

handleClick(x){
   this.setState({
    index: x
   })

}

 render(){
  /**
   * Populates list items according to data passed
   * on to resultsArray.
   */
    var items = this.props.resultsArray;
    var itemslist = items.map(function(item, index){
          return(

                    { item.hourPrice } € /hour

                    Book

{ item.name }

                    { item.score } ★

{ item.location }

{ item.price } € / Day

          );})
    return(

          { itemslist }

      );

  }
}

A: You should change your render to the below codes. Use that instead of this.
var items = this.props.resultsArray;
var that = this;
var itemslist = items.map(function(item, index){
      return(

                { item.hourPrice } € /hour

                Book

           ......


text:
Q: Password hashing and special characters? Does any hashing algorithm exclude special characters?
Just tried to register at HP and here is what i got, do they store passwords as plaintext?

A: Of course no, as hashing algorithms work with streams of bytes, not with characters. So making some of those bytes special is a nonsense.
It's hard to tell why do they have such a weird restriction but it definitely has nothing to do with hashing.


text:
Q: Create a List of Dates in Access Query I have a MakeTable query in Access that I am working on. I want to make it so that one of the fields in the table being created will be a list of dates in chronological order from 1/2/2015 to 11/30/2015. How is this done in Access query design view?

A: You can create a query:
SELECT DISTINCT
    Abs([id] Mod 10) AS N
FROM
    MsysObjects;

Save this as qdxNumber10
Now create a query with a Cartesian Join (multiplying) to generate your dates:
SELECT
    DateAdd("d",[qdxNumber10_0].[N]+[qdxNumber10_1].[N]*10+[qdxNumber10_2].[N]*100,#2/1/2015#) AS [Date]
FROM
    qdxNumber10 AS qdxNumber10_0,
    qdxNumber10 AS qdxNumber10_1,
    qdxNumber10 AS qdxNumber10_2
WHERE
    DateAdd("d",[qdxNumber10_0].[N]+[qdxNumber10_1].[N]*10+[qdxNumber10_2].[N]*100,#2/1/2015#) <= #11/30/2015#;

Use this as source when you create your table.
To generate all dates for the current year, use:
SELECT
    DateAdd("d",[qdxNumber10_0].[N]+[qdxNumber10_1].[N]*10+[qdxNumber10_2].[N]*100,DateSerial(Year(Date()),1,1)) AS [Date]
FROM
    qdxNumber10 AS qdxNumber10_0,
    qdxNumber10 AS qdxNumber10_1,
    qdxNumber10 AS qdxNumber10_2
WHERE
    DateAdd("d",[qdxNumber10_0].[N]+[qdxNumber10_1].[N]*10+[qdxNumber10_2].[N]*100,DateSerial(Year(Date()),1,1)) <= DateSerial(Year(Date()),12,31);

or use DateSerial directly:
SELECT
    DateSerial(Year(Date()),1,1+[qdxNumber10_0].[N]+[qdxNumber10_1].[N]*10+[qdxNumber10_2].[N]*100) AS [Date]
FROM
    qdxNumber10 AS qdxNumber10_0,
    qdxNumber10 AS qdxNumber10_1,
    qdxNumber10 AS qdxNumber10_2
WHERE
    DateSerial(Year(Date()),1,1+[qdxNumber10_0].[N]+[qdxNumber10_1].[N]*10+[qdxNumber10_2].[N]*100) <= DateSerial(Year(Date()),12,31);

A: I'd create a table with three fields:
[Snapshot Date]   date
[CountA]          number
[CountB]          number

Fill the Snapshot Date column in with a wide range of dates (yours inclusive) -- you can do this through code or just cut/paste from a spreadsheet.
Then save a crosstab query similar to this:
TRANSFORM Avg([All Dates].[CountB]) AS DeleteMe
SELECT [All Dates].[CountA]
FROM [All Dates]
WHERE [All Dates].[Snapshot Date] Between #1/2/2015# and #11/30/2015#
GROUP BY [All Dates].[CountA]
PIVOT [All Dates].[Snapshot Date];

(once you save this query, you should be able to switch to design view and see what the designer looks like)
Assuming the crosstab query above was named All Dates Crosstab, you could:
select *
into [My New Table]
from [All Dates Crosstab]


text:
Q: How to parse JWT token in unit tests SpringBoot I have a microservice setup with Spring boot and OAuth 2 with JWT.
I have additional fields in my JWT token.
Most of my services call a static method that has a thread local of the additional fields in the token.
How can I write unit tests for such services?
Even if I tried to inject a mock user it doesn't work and I couldn't find a way of sending the JWT because I am no testing the controllers.
Code:
SecurityUtils static Calss (also check the package for other relevant JWT handler) .
Example on a method that will call the static class (Line 79).
Method:
public CommonResponse saveUpdateProfile(ProfileRequest request) {

    String authUsername = SecurityUtils.getUsername();

    Optional<ProfileEntity> optionalProfile = findProfileByUsername(authUsername);

    ProfileEntity profile;
    if (optionalProfile.isPresent()) {
        profile = optionalProfile.get();
    } else {
        profile = ProfileEntity.builder()
                .username(authUsername)
                .build();
    }

    profile.setFirstName(request.getFirstName());
    profile.setLastName(request.getLastName());

    ProfileEntity savedProfile = profileRepository.save(profile);

    if (savedProfile == null) {
        throw new RuntimeException("Failed to save user in database");
    }

    return CommonResponse.ok(savedProfile);
}

I appreciate all the help.

A: Ok, so that's a common problem when using static methods. You can't easily override them, e.g. in tests. I think what I would do is to turn your SecurityUtils class into a service and make it implement an interface. Then inject this interface into any other service that needs to use it, instead of calling static methods. Then you can easily provide another implementation to your tests.
So you would have something like that:
interface SecurityUtils {
    String getUsername();
    ...
}

@Service
class MySecurityUtils immplements SecurityUtils {
    private JwtToken getJwtToken() {
        return MySecurityContextHolder.getContext().getJwtToken();
    }

    public String getUsername() {
        return getJwtToken().getUsername();
    }
    ...
}

Then in the unit test you can just inject a mock implementation of SecurityUtils to any class you're testing.


text:
Q: Broken pipe no longer ends programs? When you pipe two process and kill the one at the "output" of the pipe, the first process used to receive the "Broken Pipe" signal, which usually terminated it aswell. E.g. running
$> do_something_intensive | less

and then exiting less used to return you immediately to a responsive shell, on a SuSE8 or former releases.
when i'm trying that today, do_something_intensive is obviously still running until i kill it manually. It seems that something has changed (glib ? shell ?) that makes program ignore "broken pipes" ...
Anyone of you has hints on this ? how to restore the former behaviour ? why it has been changed (or why it always existed multiple semantics) ?
edit : further tests (using strace) reveal that "SIGPIPE" is generated, but that the program is not interrupted. A simple
#include <stdio.h>
int main()
{
   while(1) printf("dumb test\n");
   exit(0);
}

will go on with an endless
--- SIGPIPE (Broken pipe) @ 0 (0) ---
write(1, "dumb test\ndumb test\ndumb test\ndu"..., 1024) = -1 EPIPE (Broken pipe)

when less is killed. I could for sure program a signal handler in my program and ensure it terminates, but i'm more looking for some environment variable or a shell option that would force programs to terminate on SIGPIPE
edit again: it seems to be a tcsh-specific issue (bash handles it properly) and terminal-dependent (Eterm 0.9.4)

A: Well, if there is an attempt to write to a pipe after the reader has gone away, a SIGPIPE signal gets generated.  The application has the ability to catch this signal, but if it doesn't, the process is killed.
The SIGPIPE won't be generated until the calling process attempts to write, so if there's no more output, it won't be generated.

A: Has "do something intensive" changed at all?
As Daniel has mentioned SIGPIPE is not a magic "your pipe went away" signal but rather a "nice try, you can no longer read/write that pipe" signal.
If you have control of "do something intensive" you could change it to write out some "progress indicator" output as it spins.  This would raise the SIGPIPE in a timely fashion.

A: Thanks for your advices, the solution is getting closer...
According to the manpage of tcsh, "non-login shells inherit the terminate behavior  from their parents.  Other signals have the values which the shell       inherited from its parent."
Which suggest my terminal is actually the root of the problem ... if it ignored SIGPIPE, the shell itself will ignore SIGPIPE as well ...
edit: i have the definitive confirmation that the problem only arise with Eterm+tcsh and found a suspiciously missing signal(SIGPIPE,SIG_DFL) in Eterm source code. I think that close the case.


text:
Q: How to make startup Azure Function I have a Azure Function like that
[FunctionName("Function1")]
public static void Run([ServiceBusTrigger("myqueue", AccessRights.Manage,      Connection = "AzureWebJobsServiceBus")]string myQueueItem, TraceWriter log)
    {
        log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
    }

I want to dynamic bind myqueue and AzureWebJobServiceBus connection string in a startup or OnInit of app without as method's parameter above. I mean, I want to a method run first of all like Program.cs in WebJob to binding or start up global variables. Can I do that in Azure Function and how to do it?
Many thanks

A: The attributes here are compiled into a function.jsonfile before deployment that has the info on what the binding talks to. Often things like the connection string reference app settings. Neither of these can be modified within the code itself (so a Program.cs couldn't modify the function.json binding).
Can you share any more on your scenario? If you have multiple queues you want to listen to could you deploy a function per queue? Given the serverless nature of Functions there isn't a downside to having extra functions deployed. Let me know - happy to see if we can help with what you need.

A: Edit
The suggestion below doesn't work for a Trigger, only for a Binding.
We have to wait for the team to support Key Vault endpoints in Azure Functions, see this GitHub issue.

I think what you are looking for is something called Imperative Bindings.
I've discovered them myself just yesterday and had a question about them also. With these type of bindings you can just dynamically set up the bindings you want, so you can retrieve data from somewhere else (like a global variable, or some initialization code) and use it in the binding.
The thing I have used it for is retrieving some values from Azure Key Vault, but you can also retrieve data from somewhere else of course. Some sample code.
// Retrieving the secret from Azure Key Vault via a helper class
var connectionString = await secret.Get("CosmosConnectionStringSecret");
// Setting the AppSetting run-time with the secret value, because the Binder needs it
ConfigurationManager.AppSettings["CosmosConnectionString"] = connectionString;

// Creating an output binding
var output = await binder.BindAsync<IAsyncCollector<MinifiedUrl>>(new DocumentDBAttribute("TablesDB", "minified-urls")
{
    CreateIfNotExists = true,
    // Specify the AppSetting key which contains the actual connection string information
    ConnectionStringSetting = "CosmosConnectionString",
});

// Create the MinifiedUrl object
var create = new CreateUrlHandler();
var minifiedUrl = create.Execute(data);

// Adding the newly created object to Cosmos DB
await output.AddAsync(minifiedUrl);

There are also some other attributes you can use with imperative binding, I'm sure you'll see this in the docs (first link).
Instead of using Imperative Bindings, you can also use your application settings.

As a best practice, secrets and connection strings should be managed using app settings, rather than configuration files. This limits access to these secrets and makes it safe to store function.json in a public source control repository.
  App settings are also useful whenever you want to change configuration based on the environment. For example, in a test environment, you may want to monitor a different queue or blob storage container.
  App settings are resolved whenever a value is enclosed in percent signs, such as %MyAppSetting%. Note that the connection property of triggers and bindings is a special case and automatically resolves values as app settings.
  The following example is an Azure Queue Storage trigger that uses an app setting %input-queue-name% to define the queue to trigger on.
{
  "bindings": [
    {
      "name": "order",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "%input-queue-name%",
      "connection": "MY_STORAGE_ACCT_APP_SETTING"
    }
  ]
}


text:
Q: EXPLODE FUNCTION PHPEXCEL FILE Im creating  a packing list on a PHPEXCEL FILE, I had create the same packing list on a pdf and works well.
On pdf file this is my code:
while($linha_itens = mysql_fetch_object($select_list_itens)){

                    $linha_sizer_run = explode(",", $linha_itens->ppk_size_run);

                    print '

                        '.$linha_itens->po.'
                         '.$linha_itens->customer_name.'
                         '.$linha_itens->style_name.'
                         '.$linha_itens->style_id.'
                         '.$linha_itens->material.'
                         '.$linha_itens->colors.'
                        '.$linha_itens->case_ini.'
                        '.$linha_itens->case_fin.'
                        '.$linha_itens->ppk_style_name.'
                        '.$linha_sizer_run[0].'
                        '.$linha_sizer_run[1].'
                        '.$linha_sizer_run[2].'
                        '.$linha_sizer_run[3].'
                        '.$linha_sizer_run[4].'
                        '.$linha_sizer_run[5].'
                        '.$linha_sizer_run[6].'
                        '.$linha_sizer_run[7].'
                        '.$linha_sizer_run[8].'
                        '.$linha_sizer_run[9].'
                        '.$linha_sizer_run[10].'
                        '.$linha_sizer_run[11].'
                        '.$linha_sizer_run[12].'
                        '.$linha_sizer_run[13].'
                        '.$linha_sizer_run[14].'
                        '.$linha_sizer_run[15].'
                        '.$linha_sizer_run[16].'
                        '.$linha_sizer_run[17].'

My phpexcel code:
while ( $item = mysql_fetch_array ($itens)) {

            $linha_sizer_run = explode(",", $item->ppk_size_run);

             $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $item['po']);
             $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $item['style_name']);
             $objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $item['colors']);
             $objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowCount, $item['material']);
             $objPHPExcel->getActiveSheet()->SetCellValue('F'.$rowCount, $item['case_ini']);
             $objPHPExcel->getActiveSheet()->SetCellValue ('G'.$rowCount, '-');
             $objPHPExcel->getActiveSheet()->SetCellValue('H'.$rowCount, $item['case_fin']);

             $objPHPExcel->getActiveSheet()->SetCellValue('I'.$rowCount, $linha_sizer_run[0]);
             $objPHPExcel->getActiveSheet()->SetCellValue('J'.$rowCount, $linha_sizer_run[1]);
             $objPHPExcel->getActiveSheet()->SetCellValue('K'.$rowCount, $linha_sizer_run[2]);
             $objPHPExcel->getActiveSheet()->SetCellValue('L'.$rowCount, $linha_sizer_run[3]);
             $objPHPExcel->getActiveSheet()->SetCellValue('M'.$rowCount, $linha_sizer_run[4]);
             $objPHPExcel->getActiveSheet()->SetCellValue('N'.$rowCount, $linha_sizer_run[5]);
             $objPHPExcel->getActiveSheet()->SetCellValue('O'.$rowCount, $linha_sizer_run[6]);
             $objPHPExcel->getActiveSheet()->SetCellValue('P'.$rowCount, $linha_sizer_run[7]);
             $objPHPExcel->getActiveSheet()->SetCellValue('Q'.$rowCount, $linha_sizer_run[8]);
             $objPHPExcel->getActiveSheet()->SetCellValue('R'.$rowCount, $linha_sizer_run[9]);
             $objPHPExcel->getActiveSheet()->SetCellValue('S'.$rowCount, $linha_sizer_run[10]);
             $objPHPExcel->getActiveSheet()->SetCellValue('T'.$rowCount, $linha_sizer_run[11]);
             $objPHPExcel->getActiveSheet()->SetCellValue('U'.$rowCount, $linha_sizer_run[12]);
             $objPHPExcel->getActiveSheet()->SetCellValue('V'.$rowCount, $linha_sizer_run[13]);
             $objPHPExcel->getActiveSheet()->SetCellValue('W'.$rowCount, $linha_sizer_run[14]);
             $objPHPExcel->getActiveSheet()->SetCellValue('X'.$rowCount, $linha_sizer_run[15]);
             $objPHPExcel->getActiveSheet()->SetCellValue('Y'.$rowCount, $linha_sizer_run[16]);
             $objPHPExcel->getActiveSheet()->SetCellValue('Z'.$rowCount, $linha_sizer_run[17]);
             $objPHPExcel->getActiveSheet()->SetCellValue('AA'.$rowCount, $linha_sizer_run[18]);

THis is how is my data on DB: database
This is how looks like on PDF: pdf_size_run
This is the error i get when I tried to open the excel using the same explode from pdf: excel_error
How could I fix this? How could I open the size_run and explode on excel file?
Thanks

A: First, you are pulling an array from the database and trying to access it as an object ($item->ppk_size_run). You have to use [] syntax to access an array value... for example $item['ppk_size_run']
Second, there is way too much repeated code, which is why you probably couldn't see the issues at hand. Try using a helper function like the addRowToExcel() function in the code below.
Third, not sure if this is an issue or not because I can't see the previous code, but inside the mysql_fetch_array method you have a variable spelled "$itens"... should that be "$items"?
Also I would consider switching to PDO or mysqli as they are much more secure and will make your code more future proof as mysql is being deprecated.
require_once("phpexcel/Classes/PHPExcel.php");

$phpexcel = new PHPExcel();

$phpexcel->getProperties()
    ->SetLastModifiedBy("")
    ->setTitle("")
    ->setSubject("")
    ->setDescription("");

function addRowToExcel($column, $count, $value) {
    $phpexcel->getActiveSheet()->setCellValue($column.$count, $value);
}

$phpexcel->setActiveSheetIndex(0);

$rowcount = 0;

while($item = mysql_fetch_array($items)) {

    $runs = explode(",", $item['ppk_size_run']);

    $columns = [
        'A' => $item['po'],
        'B' => $item['style_name'],
        'C' => $item['colors'],
        'D' => $item['material'],
        'E' => $item['case_ini'],
        'F' => '-',
        'G' => $item['case_fin'],
        'H' => $runs[0],
        'I' => $runs[1],
        'J' => $runs[2],
        'L' => $runs[3],
        'M' => $runs[4],
        'N' => $runs[5],
        'O' => $runs[6],
        'P' => $runs[7],
        'Q' => $runs[8],
        'R' => $runs[9],
        'S' => $runs[10],
        'T' => $runs[11],
        'U' => $runs[12],
        'V' => $runs[13],
        'W' => $runs[14],
        'X' => $runs[15],
        'Y' => $runs[16],
        'Z' => $runs[17],
        'AA' => $runs[18]
    ];

    foreach($columns as $k => $v) {
        addRowToExcel($k, $rowcount, $v);
    }

    $rowcount++;

}


text:
Q: Which of my Visual Studio extensions are slowing? My Visual Studio 2012 has become slow to open. In 'safe mode' it's fast again. Presumably some extensions are slowing Visual Studio. Which?
Is there an analogue of Internet Explorer's feature which shows load time for each extensions? http://blogs.msdn.com/b/ie/archive/2009/07/18/how-to-make-ie-open-new-tabs-faster.aspx

A: You can start Visual Studio from the command line and specify the /log option to have Visual Studio write all details to the ActivityLog.xml. It's not a pretty pop-up dialig, but you can get the information you want from there.
See: http://msdn.microsoft.com/en-us/library/vstudio/ms241272.aspx

A: Thanks Jesse, ActivityLog.xml has the information I want. Unfortunately, it's unreadable. I wrote a Python script to extract the relevant details
import sys
from bs4 import BeautifulSoup
try:
    f = open(sys.argv[1])
except IndexError:
    f = sys.stdin

soup = BeautifulSoup(f)

loads = dict()

for entry in soup.find_all('entry'):
    description = entry.find('description')
    if not (description and "package load" in description.get_text() ):
        continue

    print(entry)
    print()

A: I solved my similar problem with "The Activity Log Profiler". It's just an xsl-Stylesheet for the Activity Log and shows the HotSpots and Errors in current ActivityLog.xml
https://github.com/lcorneliussen/ActivityLogProfiler
There is also a Blog-Entry about it:
http://startbigthinksmall.wordpress.com/2011/11/08/activity-log-profiler-find-out-which-extension-is-slowing-down-your-visual-studio/


text:
Q: C - getting pressed KeyCode (NOT stdio) I'm trying to write a little program (in C), which writes every pressed Key I'm pressing into a .txt-file (and yes, it's a keylogger).
But I don't want to use the stdio, because I'm using FreeConsole();.
#include <stdio.h>
#include <windows.h>

int main()
{
    char c;
    int i = 0;
    FILE *datei;
    datei = fopen("test.txt","w+");
    if (datei == NULL) exit(1);
    FreeConsole();
    while(1)
    {
        c =    ???      ;              //get KeyCode of pressed key
        fprintf(datei, "%c",c);
        if (c == 27)
        {
              break;
        }
        printf("%c",c);
    }
    fclose(datei);
    return(0);
}

Hope I made it clear (hope)
Thanks! :)

A: You can't do that with only the standard library. The I/O functions that don't specify an explicit FILE* found in the standard library get their data from the standard input (stdin).
Thus, the standard input does not necessarily have to be attached to a terminal, from which you could retrieve actual keystrokes. You have to look into your operating system's documentation and APIs for that.


text:
Q: RegEx in cfml to match whole word in uppercase followed by line feed I've been struggling with this all day, as regular expressions aren't my most favourite topic.
I'm trying to find when the following happens:
Complete word that is in uppercase
Followed by a space
Followed by a line feed
Followed by another space
Followed by another word that starts with an uppercase letter
While testing I found that if I defined what the capital letter should be (in this case S):
[A-Z][A-Z]+ \n S
It would match, however if I change it to something like
[A-Z][A-Z]+ \n [A-Z]
It now picks up any text that contains a line feed regardless if it is preceded by an uppercase word.
Am I missing something obvious?
Below is some sample text I'm using (hopefully it pastes ok without losing it's line feeds).  I'm trying to find the headings (in uppercase) so that I can make some changes to them.
 People who have a disability that would prevent them from performing required
 basic life support skills are advised that they will not be able to achieve the
 unit of competency.
 ENROLLING IN FIRST AID UNITS OF COMPETENCY
 If you are seeking to enrol in a First Aid unit of competency e.g. HLTFA301B
 Apply first aid, you are advised that to complete the unit you must be able to
 perform basic life support skills, for example control bleeding and perform
 cardiopulmonary resuscitation (CPR). If you have a disability that would prevent
 you from performing required basic life support skills you are advised that you
 will not be able to achieve the unit of competency.
 REQUIREMENTS AND ADVICE FOR STUDENTS PARTICIPATING IN WORK PLACEMENT
 Some or all of the following advice will apply to you, depending on your course
 and the type of organisation where you will be undertaking work placement.

Cheers
Mark

A: When you are matching a line break, make sure you consider that line breaks may (or may not) have carriage-returns preceding them.  Especially on text files from Windows.
So you might want something like:
"[ ][A-Z]+\r?\n[A-Z]"
Make sure you don't leave random spaces in your regex, because these will very likely be treated as literal spaces.  I've enclosed the (only) space in the expression above in [ ] to make it clearer that it's part of the regex, and I've enclose the whole regex in " characters because you probably want that.  The [ ] around that space should not be needed, though.
The ? following a match means "0 or more of the preceding", so in this case we want a \n optionally preceded by a \r.

A: There are two primary problems. The lines have spaces and possibly other characters. You will need to at least use more than [A-Z] to search for these. You will at least need to include a space in the set [A-Z ]. If there are other characters such as numbers or some punctuation you will need to add them here as well. And as karora mentioned you will need to check for variations on the breaks.
Here is an example that also includes a positive look ahead to prevent it from coming back in the result, so you can then probably just use the match results array directly in the next step of your code.
<cfset matches = reMatch(" [A-Z ]+(?= \r?\n [A-Z])", teststring) />
<cfdump var="#matches#" />


text:
Q: OpenCV DNN Face detector def detect_video(image):
gray=image

blob = cv2.dnn.blobFromImage(gray, 1.0, (300, 300), [104, 117, 123], False, False)
net.setInput(blob)
detections = net.forward()
bboxes = []
gray=cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
frameWidth=image.shape[1]
frameHeight=image.shape[0]
for i in range(detections.shape[2]):
    confidence = detections[0, 0, i, 2]
    if confidence > 0.7:
        x1 = int(detections[0, 0, i, 3] * frameWidth)
        y1 = int(detections[0, 0, i, 4] * frameHeight)
        x2 = int(detections[0, 0, i, 5] * frameWidth)
        y2 = int(detections[0, 0, i, 6] * frameHeight)
        cv2.rectangle(image,(x1,y1),(x2,y2),(255,255,0),3)
        try:
            image1 = gray[y1:(y2), x1:(x2)]

            img = cv2.resize(image1, (48,48), interpolation = cv2.INTER_CUBIC) / 255.

            prediction=model1.predict_proba(img.reshape(1,48,48,1))

            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.putText(image,str(emotions[prediction[0].argmax()]),(x1,y1+10), font, 1,(255,255,255),2,cv2.LINE_AA)

            result=prediction
            if result is not None:
                if result[0][6] < 0.6:
                    result[0][6] = result[0][6] - 0.12
                    result[0][:3] += 0.01
                    result[0][4:5] += 0.04
    # write the different emotions and have a bar to indicate probabilities for each class
                for index, emot in enumerate(emotion):
                    cv2.putText(image, emot, (10, index * 20 + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
                    cv2.rectangle(image, (130, index * 20 + 10), (130 + int(result[0][index] * 100), (index + 1) * 20 + 4), (255, 0, 0), -1)
                emt=[prediction[0][0],prediction[0][1],prediction[0][2],prediction[0][3],prediction[0][4],prediction[0][5],prediction[0][6]]
                indx=np.arange(len(emotion))
                plt.bar(indx,emt,color='blue')

                plt.xticks(indx,emotion)
                plt.savefig("ab.png")
                cv2.imshow("graph",cv2.imread("ab.png"))
                plt.clf()
                #cv2.waitKey(5)
                #plt.show()
                #return indx,emt

        except:
            #print("----->Problem during resize .Probably Cant detect any face")
            continue
return image

I have made my own model and trained on KDEF dataset.Now when I am giving the video as an input , it detects the face in the video but it makes two bounding boxes.Can anyone help me whats the mistake in the code.Its running successfully but just creating two bounding boxes.The input which the neural networks accepts is 48*48.

A: first select the detection which has the most significant confidence then draw it on image.
detection_index = 0
max_confidence = 0

for i in range(detections.shape[2]):
    confidence = detections[0, 0, i, 2]
    if max_confidence < confidence:
        max_confidence = confidence
        detection_index = i

i = detection_index

x1 = int(detections[0, 0, i, 3] * frameWidth)
y1 = int(detections[0, 0, i, 4] * frameHeight)
x2 = int(detections[0, 0, i, 5] * frameWidth)
y2 = int(detections[0, 0, i, 6] * frameHeight)
cv2.rectangle(image, (x1, y1), (x2, y2), (255, 255, 0), 3)
try:
    image1 = gray[y1:(y2), x1:(x2)]

img = cv2.resize(image1, (48, 48), interpolation=cv2.INTER_CUBIC) / 255.

prediction = model1.predict_proba(img.reshape(1, 48, 48, 1))

font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(image, str(emotions[prediction[0].argmax()]), (x1, y1 + 10), font, 1, (255, 255, 255), 2, cv2.LINE_AA)

result = prediction
if result is not None:
    if result[0][6] < 0.6:
        result[0][6] = result[0][6] - 0.12
        result[0][:3] += 0.01
        result[0][4:5] += 0.04
        # write the different emotions and have a bar to indicate probabilities for each class
    for index, emot in enumerate(emotion):
        cv2.putText(image, emot, (10, index * 20 + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
        cv2.rectangle(image, (130, index * 20 + 10), (130 + int(result[0][index] * 100), (index + 1) * 20 + 4),
                      (255, 0, 0), -1)
    emt = [prediction[0][0], prediction[0][1], prediction[0][2], prediction[0][3], prediction[0][4],
           prediction[0][5], prediction[0][6]]
    indx = np.arange(len(emotion))
    plt.bar(indx, emt, color='blue')

    plt.xticks(indx, emotion)
    plt.savefig("ab.png")
    cv2.imshow("graph", cv2.imread("ab.png"))
    plt.clf()
    # cv2.waitKey(5)
    # plt.show()
    # return indx,emt

except:
    # print("----->Problem during resize .Probably Cant detect any face")
    continue
return image


text:
Q: Problem with static files using phpmyadmin:fpm-alpine behind Apache2 I try to migrate most of my server apps to docker. I basically have a Apache2 running on my host and some PHP based WebApps as docker containers using FPM.
As my knowledge goes, only the *.php files are served through the docker container, those this configuration must be added to Apache2:
ProxyPassMatch "^/phpMyAdmin/(.*\.php)$" "fcgi://localhost:9000/var/www/html/$1"

So you can't pass any static files (CSS, JavaScript) to the fpm container. Therefore I usually mount a host directory to the container like so:
docker run -v /var/www/phpMyAdmin:/var/www/html -p 9000:9000 -d phpmyadmin:fpm-alpine

But as soon as I add the mount (-v), the containers "/var/www/html" directory is empty. I checked with:
docker exec -it phpmyadmin /bin/sh

It seems like the whole phpMyAdmin installation wasn't extracted or got deleted/overwritten. This approach did work for other containers (postfixadmin, roundcube), so I have no idea what is going on or what I'm doing wrong.
How am I supposed to serve the static files from the fpm docker container through my Apache2 host? I didn't find any example, only nginx as server or docker compose.
Best regards,
Billie


text:
Q: add discussion comment to TFS via web-access How can you add notes/comments to the discussion box on the TFS web interface? There doesn't seem to be any "add input" field anywhere...

A: It's just misleading ui, you have to type your comment in the "History" box and save the TFS item to add a comment to the discussion box:


text:
Q: AttributeError: module 'tensorflow' has no attribute 'gfile' even with tensorflow v1 I am having a problem as i upload my model in drive and mount it in Colab module imports are working fine in previous cell as i gave the root path and sys.append() it , I am using (tf.compat.v1) you can see it in ouptut, but still getting this error also tried (tensorflow v2) and used tf.io.gfile but still same error. Kindly help me
<module 'tensorflow_core.compat.v1.version' from '/usr/local/lib/python3.6/dist-packages/tensorflow_core/_api/v2/compat/v1/version/__init__.py'>
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-e851eb463895> in <module>()
      1 print(tf.version)
----> 2 category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)

2 frames
/content/drive/My Drive/models/research/object_detection/utils/label_map_util.py in load_labelmap(path)
    136     a StringIntLabelMapProto
    137   """
--> 138   with tf.gfile.GFile(path, 'r') as fid:
    139     label_map_string = fid.read()
    140     label_map = string_int_label_map_pb2.StringIntLabelMap()

AttributeError: module 'tensorflow' has no attribute 'gfile'

A: Try to downgrade TF 1.15 from TF 2.x, your issue will be resolved.
Please refer code as shown below
!pip uninstall tensorflow
!pip install tensorflow==1.15

 import tensorflow as tf

If you are looking for simple solution for Colab, please use %tensorflow_version 1.x magic command, which does for you without un-installation.
%tensorflow_version 1.x
 import tensorflow as tf


text:
Q: Python multiprocessing - How can I split workload to get speed improvement? I am writing a simple code of cropping images and saving it.
But the problem is that the number of images is about 150,000+ and I want to improve the speed.
So, at first I wrote a code with simple for loops, like the following:
import cv2
import numpy
import sys

textfile=sys.argv[1]
file_list=open(textfile)
files=file_list.read().split('\n')
idx=0
for eachfile in files:
    image=cv2.imread(eachfile)
    idx+=1
    if image is None:
        pass
    outName=eachfile.replace('/data','/changed_data')
    if image.shape[0]==256:
        image1=image[120:170,120:170]
    elif image.shape[0]==50:
        image1=image
    cv2.imwrite(outName,image1)
    print idx,outName

This code took about 38 seconds for 90000 images.
But, using dual core took more time than single process, about 48 seconds for the same 90000 images.
import cv2
import sys
import numpy
from multiprocessing import Pool

def crop(eachfile):
    image=cv2.imread(eachfile)
    idx+=1
    if image is None:
        pass
    outName=eachfile.replace('/data','/changed_data')
    if image.shape[0]==256:
        image1=image[120:170,120:170]
    elif image.shape[0]==50:
        image1=image
    cv2.imwrite(outName,image1)
    print idx,outName

if __name__=='__main__':
    textfile=sys.argv[1]
    file_list=open(textfile)
    files=file_list.read().split('\n')
    pool=Pool(2)
    pool.map(crop,files)

Am I doing the right thing for speeding up the process? Or should I split the list and send each list to the process?
Any comments regard my code would be great!!!
Thanks in advance!!!

A: You should indeed split the task over two cores. Play around with this example code "slightly modified". OP can be found here. Where you see data that is your hook providing your images. The defs don't work under class when using multiprocessing... If your trying to use pathos...you'll get errors from cPickle... some nagging issue with latest 2.7 version. Doesn't occur in 3.5 or something. Enjoy!
import multiprocessing

def mp_worker((inputs, the_time)):
    print " Process %s\tWaiting %s seconds" % (inputs, the_time)
    time.sleep(int(the_time))
    print " Process %s\tDONE" % inputs
    sys.stdout.flush()

def mp_handler():                           # Non tandem pair processing
    p = multiprocessing.Pool(2)
    p.map(mp_worker, data)

def mp_handler_tandem():
    subdata = zip(data[0::2], data[1::2])
#    print subdata
    for task1, task2 in subdata:
        p = multiprocessing.Pool(2)
        p.map(mp_worker, (task1, task2))

#data = (['a', '1'], ['b', '2'], ['c', '3'], ['d', '4'])
data = (['a', '2'], ['b', '3'], ['c', '1'], ['d', '4'],
        ['e', '1'], ['f', '2'], ['g', '3'], ['h', '4'])

if __name__ == '__main__':
    sys.stdout.flush()
#    print 'mp_handler():'
#    mp_handler()
#    print '---'
#    time.sleep(2)

#    print '\nmp_handler_tandem():'
#    mp_handler_tandem()
    print '---'
#    time.sleep(2)

    Multiprocess().qmp_handler()

working within an editor: use sys.stdout.flush() to flush your output to screen while it happens.

But check also here using kernels and splitting jobs.


text:
Q: Error in writing Python functions in Crystal-lang I am trying to write some python function in crystal-lang through the C Python API.
My code follows:
METH_VARARGS  = 0x0001

@[Link("python3.5m")]
lib Python
  alias PyObject = Void*

  struct PyMethodDef
    name  : UInt8*
    func  : Void*
    flags : LibC::Int
    doc   : UInt8*
  end

  fun Py_Initialize
  fun Py_Finalize
  fun PyObject_CallObject(func : PyObject, args : PyObject) : PyObject
  fun PyCFunction_NewEx(method : PyMethodDef*, __self__ : PyObject, ) : PyObject
  fun PyLong_AsLong(n : PyObject) : Int64
  fun PyLong_FromLong(n : Int64) : PyObject

end

def new_method_def(name : String, function, flags : LibC::Int)
  x = Pointer(Python::PyMethodDef).malloc(1)
  x.value.name  = name.to_unsafe
  x.value.func  = function
  x.value.flags = flags
  x.value.doc   = nil
  x
end

Python.Py_Initialize

a = ->(args : Void*) {
                       puts Python.PyLong_AsLong(args)
                       Pointer(Void).null
                     }

name     = "num"
number   = Python.PyLong_FromLong(1)
Python.Py_IncRef(number)
method   = Python.PyCFunction_NewEx(new_method_def(name,a.pointer,METH_VARARGS),number)
Python.PyObject_CallObject(method,Pointer(Void).null)

Python.Py_Finalize

Everything works if I set nil instead of number when in PyCFunction_NewEx, but as the code is, it throws an invalid acces memory exception when Py_Finalize is called.
I can't understand what's causing it.
Can someone help me?

A: The root problem here is that you're calling a C function of three parameters with only two arguments.
Regrettably, PyCFunction_NewEx is missing from the documentation, despite being a public API function. But all of the examples using it pass three arguments. And if you go to the source:
PyObject *
PyCFunction_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module)

That's 3.7, but this is the same in 3.5 and in 2.7, and in every other version since the function was added to the API in 2.3. The whole point of NewEx is to allow you to pass a module.
Presumably, the function is expecting that third argument either in a register or on the stack, and you haven't put anything there, so it's completely arbitrary what you're passing. Slightly different code will leave completely different values in those places, so it's not surprising that you get different results:

*

*If the value happens to be 0, that's fine; you're allowed to pass NULL as the module value.

*If the value happens to be something that points to unmapped memory, like, say, 1 (as in the raw C long/long long, not a PyLongObject), you should get a segfault from the attempt to incref the module.

*If the value happens to be a pointer to some random thing in memory, the incref will work, but will corrupt that random thing. Which could do just about anything, but a mysterious segfault at some arbitrary later point is almost the least surprising thing it could do.

Meanwhile, from a comment:

I am calling PyCFunction_NewEx because PyCFunction_New is a marco in the source code.

If you're using Python 2.3-2.6 or 3.0-3.2, then sure. But in later versions, including the 3.5 you say you're using, CPython goes out of its way to define PyCFunction_New as a function specifically so that it will be present in the API (and even the stable API, for 3.x). See 3.5 for example:
/* undefine macro trampoline to PyCFunction_NewEx */
#undef PyCFunction_New

PyAPI_FUNC(PyObject *)
PyCFunction_New(PyMethodDef *ml, PyObject *self)
{
    return PyCFunction_NewEx(ml, self, NULL);
}

So, you really can just call PyCFunction_New.


text:
Q: How to parametrize different numbers or positions of arguments? For example, say I have two functions:
def func3(a, b, c):
    for var in (a, b, c):
        if var < 0:
            raise ValueError
    pass

def func7(a, b, c, d, e, f, g):
    for var in (a, b, c, d, e, f, g):
        if var < 0:
            raise ValueError
    pass

And in my tests, I want to test a set of invalid values at each parameter.  The only way I know of to do this is to write them all out:
@pytest.mark.parametrize('val', [-2, -3, -4.5])
def test_invalid_param(val):
    with pytest.raises(ValueError):
        func3(val, 0, 0)
    with pytest.raises(ValueError):
        func3(0, val, 0)
    with pytest.raises(ValueError):
        func3(0, 0, val)
    with pytest.raises(ValueError):
        func7(val, 0, 0, 0, 0, 0, 0)
    with pytest.raises(ValueError):
        func7(0, val, 0, 0, 0, 0, 0)
    with pytest.raises(ValueError):
        func7(0, 0, val, 0, 0, 0, 0)
    ...

How can I combine these all into one with pytest.raises case?
If both funcs had the same number of arguments, I could stack this:
@pytest.mark.parametrize('func', [func3, func7])

but they don't.  If they just had different numbers of arguments and I was only testing the first, then I could stack this:
@pytest.mark.parametrize('func, args', [(func3, (0, 0)),
                                        (func7, (0, 0, 0, 0, 0, 0))])

But that won't work for testing the parametrized value in multiple positions.

A: If you don't mind increasing the number of tests you can use the values sets as a parameter to the test. Each set will be a different test
def data_source():
    for val in [-2, -3, -4.5]:
        for values_set in [[val, 0, 0], [0, val, 0], [0, 0, val], [val, 0, 0, 0, 0, 0, 0], [0, val, 0, 0, 0, 0, 0], [0, 0, val, 0, 0, 0, 0]]:
            yield values_set

def func(values):
for var in values:
    if var < 0:
        raise ValueError
pass

@pytest.mark.parametrize('values', data_source())
def test_invalid_param(values):
    with pytest.raises(ValueError):
        func(values)

In case of failure the stack trace will look like
(test_invalid_param[values6])
values = [3, 0, 0]

    @pytest.mark.parametrize('values', data_source())
    def test_invalid_param(values):
        with pytest.raises(ValueError):
>           func(*values)
E           Failed: DID NOT RAISE <class 'ValueError'>

Example_test.py:32: Failed

As a side note, to allow different number of arguments you can use * in the parameter
def func(*values):
    for var in values:
        if var < 0:
            raise ValueError
    pass


text:
Q: "Error: void value not ignored as it ought to be" - Understanding the error and trying to overcome it Following is my code snippet.The error occurs in the display_results() method.
    class results
    {
    public:
        bool majority;
        int major_element = 0;

    void show_results()
        {
            if (majority)
            {
                cout<<"Majority found "<<major_element;
            }

            else
                cout<<"No majority element found";
        }
    };
void display_results(results* p, int number_of_testcases)
    {
        for(int i = 0; i<number_of_testcases;i++)
        {
          //Error occurs in next line
         *p[i].show_results();
        }
    }

Can anyone explain me why is this happening?


text:
Q: Alert modal from sidebar close(X) icon I am using p-sidebar to display a component as a sidebar from another component. Now when the sidebar displays, it has a close(X) icon at the top right corner and clicking on it closes the sidebar. I want to display a alert modal when clicked in close(X) icon.
<p-sidebar [(visible)]="slideBarDisplay"
             [style]="{'height':'75%','overflow':'scroll'}"
             position="bottom">
    <sidebar-component (add)="addNew($event)"
                              (cancelAdd)="slideBarDisplay = false"
                              *ngIf="slideBarDisplay">
    </sidebar-component>
  </p-sidebar>

and I have showClearModal = false; to display the modal in sidebar-component html.
So I want to call
showAlertDisplay() {
this.showClearModal = true
}

when clicked on close(X) button so it will make p-dialog visible.
Appreacite any help


text:
Q: animated .effect() jqueryui fastest click I have a error when fastest click in tabs, see image:

Here's my js:
jQuery.fn.extend({
    showcontent: function () {
        this.each(function () {
            var options = {
                direction: 'vertical'
            };
            setTimeout(function () {
                $(this).siblings('li').hide();
            }, 2000)
            if ($(this).is(':visible')) {
                $(this).siblings('li').hide();
            } else {
                $(this).siblings('li').hide();
                if (!$(this).is(":animated")) {
                    $(this).toggle("clip", options, 400);
                }
            }
        });
        return this;
    }
});

$("#team1").addClass('tab_over');
$("#team1").click(function (e) {
    e.preventDefault();
    $(this).addClass('tab_over').siblings().removeClass('tab_over');
    $('#c1').showcontent();
    return false;
});
$("#team2").click(function (e) {
    e.preventDefault();
    $(this).addClass('tab_over').siblings().removeClass('tab_over');
    $('#c2').showcontent();
    return false;
});

HTML:

Misión

Visión

Content 1

Content 2

In  fiddle: http://jsfiddle.net/Noranterry/Cam2U/
Thank you!

A: You need to stop the animation that is happening on the previous one while doing fast clicks. You can use stop() on the currently animated ones $(':animated', '.y').stop(true, true);: before you animate the current one. You can remove the timeout
 showcontent: function () {
        this.each(function () {

            var options = {
                direction: 'vertical'
            };
            $(':animated', '.y').stop(true, true);  // Here clear up the previous queues.

Demo
Issue is that the previous animation is still in queue when you trigger animations for the new ones and ultimately both finishes up the animates and both of them becomes visible. Using stop with true will clear the queues which has the previous animations accumulated during the fast clicks.

A: If I understand the problem, you could choose to hide the Content that belongs to the respective button. This will prevent the button from sticking.
jQuery.fn.extend({
    showcontent: function () {
        this.each(function () {
            var options = {
                direction: 'vertical'
            };
            setTimeout(function () {
                $(this).siblings('li').hide();
            }, 2000)
            if ($(this).is(':visible')) {
                $(this).siblings('li').hide();
            } else {
                $(this).siblings('li').hide();
                if (!$(this).is(":animated")) {
                    $(this).toggle("clip", options, 400);
                }
            }
        });
        return this;
    }
});

$("#team1").addClass('tab_over');
$("#team1").click(function (e) {
    e.preventDefault();
    $(this).addClass('tab_over').siblings().removeClass('tab_over');
    $('#c1').showcontent();
    $('#c2').hide(0);
    return false;
});
$("#team2").click(function (e) {
    e.preventDefault();
    $(this).addClass('tab_over').siblings().removeClass('tab_over');
    $('#c2').showcontent();
    $('#c1').hide(0);
    return false;
});


text:
Q: Google Bar Chart from MySQL and PHP I am trying to create a simple Google Bar Chart using data pulled from a MySQL Database. Google provides an example which I am trying to structure mine off of. See "A Simple Example".
I would like to be able to show the total number of Males and Females in each school.
Here is my PHP code for retrieving the data from MySQL:
<?php
$pdo=new PDO("mysql:dbname=trek;host=localhost","USERNAME","PASSWORD");
$stmt=$pdo->prepare("SELECT school, gender, count(*) as count from participant group by     school, gender;");
$stmt->execute();
$results=$stmt->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($results);
?>

This returns:
[
{
 school: "School A",
 gender: "F",
 count: "1"
},
{
 school: "School A",
 gender: "M",
 count: "2"
},
{
 school: "School B",
 gender: "M",
 count: "2"
},
{
 school: "School B",
 gender: "F",
 count: "10"
}
]

However I need to to appear in the following format:
[
{
 school: "School A",
 m: "2",
 f: "1"
},
{
 school: "School B",
 m: "2",
 f: "2"
}
]

I am a bit new when it come to working with Google Charts and I am open for any suggestions.
Thanks in advance!

A: Try this:
SELECT
  school,
  sum(if(gender='M',1,0)) as m,
  sum(if(gender='F',1,0)) as f
FROM
  participant
GROUP BY
  school

A: I figured it out. The problem was in my SQL statement
SELECT school,
  sum(case when gender = 'm' then 1 else 0 end) male,
  sum(case when gender = 'f' then 1 else 0 end) female
FROM participant
GROUP BY school;


text:
Q: Implementing a type map with polymorphic retrieval I'm working on an event system that allows triggers to send events to either a single handler or all handlers associated with a given type. The former is basic map functionality, and the latter mostly fits the bill... unless you want polymorphic behavior.
class Parent {};
class Child : public Parent {};

// ...

Parent p; Child c;
Trigger trigger;
Handler h1(&p), h2(&c);

trigger.sendToType<Child>(Event());  // sends the event to h2; OK
trigger.sendToType<Parent>(Event()); // sends the event to h1 only; NO

Handlers are registered based on the type of pointer they're created with. The "type" of h1 is Parent and the "type" of h2 is Child. With the basic type id mapping used in the dispatcher (just some type-associated integer mapped to a vector of Handler*) there's no way to send events to children when sending to parents.
The only solutions I can think of have several downsides:

*

*O(n) search for sending to a type.

*Having to add reflection to the codebase

*High amounts of manual setup

Ideally, I'd like a solution where overhead is reduced to (number of children + 1 for the actual type) lookups per send to type, but that may not be possible. Any advice?

A: The simpliest possible solution is to use dynamic_cast. May be it is not optimal in terms of performance, but should be faster than map/hash
Here is implementation - test online
#include <iostream>
#include <string>
#include <vector>

struct Event
{
    std::string what;
};

class Parent
{
public:
    virtual void process(const Event& e)
    {
        std::cout << e.what << "Parent" << std::endl;
    }
};
class Child : public Parent
{
public:
    virtual void process(const Event& e) override
    {
        std::cout << e.what << "Child" << std::endl;
    }
};

template<typename T>
void handler(Parent* obj, const Event& e)
{
    if (T* tmp = dynamic_cast<T*>(obj))
        tmp->process(e);
}

template<typename T, typename PARENT>
std::vector<T*> select_objects(const std::vector<PARENT*>& objects)
{
    std::vector<T*> res;
    for (auto obj : objects)
    {
        if (T* tmp = dynamic_cast<T*>(obj))
            res.push_back(tmp);
    }
    return res;
}

int main()
{
    std::vector<Parent*> objects = {new Parent, new Child};

    Event e{"Hello from "};
    std::cout << "All objects" << std::endl;
    for (auto p : objects)
        handler<Parent>(p, e);
    std::cout << "Child objects only" << std::endl;
    for (auto p : objects)
        handler<Child>(p, e);

    // here we can build an index to access objects faster
    std::cout << "Child objects only using select" << std::endl;
    std::vector<Child*> children = select_objects<Child>(objects);
    for (auto o : children)
        o->process(e);
}

Output:
All objects
Hello from Parent
Hello from Child
Child objects only
Hello from Child
Child objects only using select
Hello from Child

UPDATE: you can build some index to access objects faster


text:
Q: gtsummary and lmerTest I really appreciate gtsummary, but recently, this "classical" script including lmer() failed :
library(lmerTest) ; library(gtsummary) ; library(dplyr)
lmerTest::lmer(Reaction ~ Days + (1 | Subject), sleepstudy) %>% tbl_regression()

This is the error message :

Error in match.call() : ... used in a situation where it does not exist

I tried to re-install the 3 packages but the problem remains... Do you know why ?
Thank you very much for your help!

A: Welcome to Stackoverflow! For random effects or mixed effects models, I use the lme4 package. There are no issues with the lme4 model. Example Below!
library(gtsummary)
#> #BlackLivesMatter
packageVersion("gtsummary")
#> [1] '1.5.0'

tbl <-
  lme4::lmer(Reaction ~ Days + (1 | Subject), lme4::sleepstudy) %>%
  tbl_regression()

Created on 2021-10-17 by the reprex package (v2.0.1)


text:
Q: How to collapse in the bootstrap nav from right side? Here is the following CSS code which I am adding in the stylesheet to collapse in the bootstrap  nav  form the right side of the webpage. But it's not working out. Please help me if someone know how to do it.
.collapsing{
    position: relative !important;
    height: 0 !important;
    overflow: hidden !important;
    -webkit-transition: width .35s ease !important;
    -o-transition: width .35s ease !important;
    transition: width .35s ease !important;
}

.collapse{
    width:0 !important;
    position: absolute !important;
    right:0 !important;
    display: block;
}

.collapse.in{
    height:initial !important;
    width:100% !important;
    overflow: hidden !important;

}