text:
Q: SQL Server formatting negative values from selected data I am new to stackoverflow but I do search it often.
I am creating a report from data in which I have to format negative numbers like,
-00000010  (9 characters max)

I am getting this,
000000-10
This is what I am attempting now but I'm having issues. Any help would be greatly appreciated.
SELECT 'H'
    + DG.BLOCK
    + LEFT(DG.ZIP,5)
    + RIGHT('000000000'
    + CAST(CAST(SUM(DG.WP)AS INT) AS VARCHAR(9)),9)
    + RIGHT('000000000' + CAST(CAST(SUM(DG.WE)AS INT) AS VARCHAR(9)),9)
    + RIGHT('000000000' + CAST(CAST(SUM(DG.EP)AS INT) AS VARCHAR(9)),9)
    + RIGHT('000000000' + CAST(CAST(SUM(DG.EE)AS INT) AS VARCHAR(9)),9)
    + RIGHT('000000000' + CAST(CAST(COUNT(DGG.CLAIMCONTROL)AS INT) AS VARCHAR(9)),9)
    + RIGHT('000000000' + CAST(CAST(SUM(DGG.INC) AS INT) AS VARCHAR(9)),9)
    + RIGHT('000000000' + CAST(CAST(SUM(DGG.PAID)AS INT) AS VARCHAR(9)),9)
    + RIGHT('000000000' + CAST(CAST(SUM(DGG.ALAE) AS INT) AS VARCHAR(9)),9)
AS [H Record]
FROM TABLE

A: If 2012+, you have the option of Format().
Example
Select replace(format(-1,' 000000000'),'- ','-')

Returns
-000000001  If number was negative
 000000001  If number was positive

Just a word of caution.  Format() has some great functionality, but is not known to be a high performer.

A: The following code demonstrates formatting the data as either 9 digits plus an optional sign or as a fixed 9 characters including the sign.
-- Sample data.
declare @Samples as Table ( Sample Int );
insert into @Samples ( Sample ) values ( 0 ), ( 1 ), ( -10 ), ( 100 ), ( -1000 );

-- Format the data.
select Sample,
  case when Sign( Sample ) = -1 then '-' else '' end +
    Right( Replicate( '0', 8 ) + Cast( Abs( Sample ) as VarChar(9) ), 9 ) as FormattedSample9PlusSign,
  case when Sign( Sample ) = -1 then
    '-' + Right( Replicate( '0', 7 ) + Cast( -Sample as VarChar(8) ), 8 ) else
    Right( Replicate( '0', 8 ) + Cast( Sample as VarChar(9) ), 9 ) end as FormattedSample9
  from @Samples;

Tip: In SSMS use query results to text (Ctrl-T) for more convenient display.

A: You can try this, if you do not have v2012+:
DECLARE @mockup TABLE(SomeNumber INT);
DECLARE @padWidth INT=3;
INSERT INTO @mockup VALUES(-1000),(-500),(-1),(0),(1),(500),(1000);

SELECT CASE WHEN m.SomeNumber < 0 THEN '-' ELSE ' ' END
     + REPLACE(STR(ABS(m.SomeNumber),@padWidth),' ','0')
FROM @mockup AS m;

Numbers, which are to big, will be returned as ***. This is better than other approaches cutting the string with RIGHT or LEFT. They might return a bad result...
This is returned
-***
-500
-001
 000
 001
 500
 ***

A: In DB2 this works to get a number of 15 digits including the sign:
CASE WHEN MYNUMBER < 0 THEN '-'  ||   LPAD(MYNUMBER , 14, 0)
                       ELSE LPAD(MYNUMBER , 15, 0)
END


text:
Q: Implicit differentiation: Describing where a graph is increasing or decreasing Considering $s$ is implicit to function of $p$, given by $s^6 - p^4 = 1$. For what $s$ is it increasing and decreasing?
Well, I answered first like following: Calculating the first derivative using the implicit differentiation is $s'=\large\frac{2p^3}{3s^5}$. $s$ is increasing where $s' > 0$ and decreasing where $s' < 0$.
Obviously, I answered too generally and I'm wondering how I better answer it using the first derivative to support my answer.

A: We are talking here about the solution set
$$S:=\bigl\{(p,s)\>\bigm|\>F(s,p)=0\bigr\}\ ,$$
where
$$F(p,s)=s^6-p^4-1\ .$$
The implicit function theorem says the following: When $(p_0,s_0)\in S$ and the "technical condition"
$${\partial F\over\partial s}\biggr|_{(p_0,s_0)}=6s_0^5\ne0\tag{1}$$
is satisfied then there is a window $$W:=\ ]p_0-h,p_0+h[\ \times\ ]s_0-h', s_0+h'[\ $$ and a $C^1$-function
$$\psi:\quad ]p_0-h,p_0+h[\ \to\ ]s_0-h', s_0+h'[\ ,$$
such that $S\cap W$ equals the graph of $\psi$. Furthermore one has
$$\psi'(p_0)=-{F_p(p_0,s_0)\over F_s(p_0,s_0)}={2p_0^3\over 3s_0^5}\ .$$
Now $S$ contains no points with $s=0$; therefore $(1)$ is satisfied at all points of $S$.
Whether the local function $\psi$ is increasing or decreasing in its window depends on the signs of $p_0$ and $s_0$: When $p_0$ and $s_0$ have the same sign $\psi$ is increasing (for small enough $h>0$), otherwise $\psi$ is decreasing. The points $(0,\pm1)\in S$ are special, since $\psi'(0)=0$ there. Here further analysis is necessary, which I leave to you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: In Android, how can string values and graphic resources be switched with a theme? With an Android theme, it looks like you can change the default colors and appearance with a theme switch. However, I would like string values to change as well. For example, I have a TextView in my layout. If I switch to the Blue Theme, I would like the string to change to "This is the blue theme.". I also want to switch graphic resources as well.
How can I do this without generating the layout programmatically or putting an if-else for every branded string?
Thanks!

A: I found the answer: I took the example from http://www.androidengineer.com/2010/06/using-themes-in-android-applications.html and I modified it so that the android:text string reference is inside the style definition and not inside the layout.xml. The string will then be automatically updated whenever you change themes.


text:
Q: How can Linux VMs detect usb smart cards on Windows laptops? I am trying to set up ssh authentication on Azure/AWS hosted Linux VMs with USB Feitain smart cards. I have ran into a problem because the virtual machines need to be able to read the smart cards on the USB port. Do anyone have any ideas to accomplish this?

A: The VMs in public cloud does not have access to your laptop's USB port. You may use ssh authentication based on the certificate inside your smartcard.
Please have a look at Putty-CAC project.
Here there is a detailed setup tutorial


text:
Q: Create line between sharepoint list items I have a list that I would like to create lines in between a few items in order to separate descriptions from the next field and make them more easy to read. Is there a way to do this?

A: Using JQuery:
$('tr.ms-itmhover td').css('border-bottom','1px solid black');

Using CSS:
tr.ms-itmhover td{
    border-bottom: 1px solid black
}


text:
Q: Handle double quotes in a long text field when generating a CSV file from apex I have a custom object in which I have a long text area field. I am querying it in apex and building a CSV and sending an email with csv as attachment.
The value in the long text area field and which is also expected in CSV is this text has double "quotes"
But in CSV I am getting the value as this text has double quotes""
please let me know if it is possible to handle double quotes when generating a CSV and if so please let me know how to do it.
Adding more info
Query = [Select Id,CreatedDate,owner,Model__c,SerialNumber__c,RepairDetailDescription__c from case Where Id in : caseIds ];

string finalString = 'Created Date,owner,Model,SerialNumber,RepairDetailDescription  \n';

for(case c : Database.query(Query)){
    string recordString = '"'c.CreatedDate+'","'+c.owner+'","'+c.Model__c+'","'+c.SerialNumber__c+'","'+c.RepairDetailDescription__c+'"\n';
    finalString = finalString + recordString;
}

  if(selectedfinalstr!=null){
                Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
                blob csvBlob = Blob.valueOf(finalString);
                string csvname= 'Selected Reco Export.csv';
                csvAttc.setFileName(csvname);
                csvAttc.setBody(csvBlob);
                Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
                OrgWideEmailAddress owe = [SELECT ID,IsAllowAllProfiles,DisplayName,Address FROM OrgWideEmailAddress WHERE IsAllowAllProfiles = TRUE LIMIT 1];
                String userName = UserInfo.getUserName();
                User activeUser = [Select Email From User where Username = : userName limit 1];
                String userEmail = activeUser.Email;
                String[] toAddresses = new list<string> {userEmail};
                String subject ='Recommendation';
                email.setOrgWideEmailAddressId(owe.Id);
                email.setSubject(subject);
                email.setToAddresses( toAddresses );
                email.setHtmlBody('Find the attached Exported recommendation details.');
                email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
                Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
             }

A: When generating CSVs, Use the escapeCsv method on all string cells as you won't know in advance whether any database data might or might not have an embedded " or line-break
String s = 'abc "def" ghi';
System.debug(LoggingLevel.INFO,s.escapeCsv());

|USER_DEBUG|[2]|INFO|"abc ""def"" ghi"

RFC4180 defines valid CSV format

If double-quotes are used to enclose fields, then a double-quote
appearing inside a field must be escaped by preceding it with
another double quote.  For example:
   "aaa","b""bb","ccc"

A: Because in the string recordString = ... line you are surrounding everything by double quotes, then you need to escape any double quotes that exist in your field value.
Assuming that c.RepairDetailDescription__c is the field (potentially) containing double quotes, you could do something like this:
for(case c : Database.query(Query)){
   String doubleQuoteEscapedField = c.RepairDetailDescription__c.replace('"','""');
   string recordString = '"' + c.CreatedDate + '","' + c.owner + '","' + c.Model__c + '","' + c.SerialNumber__c + '","'+ doubleQuoteEscapedField + '"\n';
   finalString = finalString + recordString;
}

Or you could try to reverse the use of your single and double quotes on the line where you build your recordString - but this would work ONLY if the field in question is guaranteed to ABSOLUTELY NEVER contain single quotes.  Because if it did, you would have to do similar to my above answer in order to escape the single quotes.


text:
Q: Cakephp 3.6 paginator is there any way for the paginator in index.ctp to be displayed only if there are more than 20 records?
Now, if in my table there aren't records, the paginator is displayed anyway, and it looks very bad.
I was thinking about using if condition, that if the length of the array is bigger than 20, so the paginator displays, but I would have to give it to every view. Is there any other way?

A: You can check using the following condition
Cake\View\Helper\PaginatorHelper::hasNext(string $model = null)
Returns true if the given result set is not at the last page.

Cake\View\Helper\PaginatorHelper::hasPrev(string $model = null)
Returns true if the given result set is not at the first page.

Cake\View\Helper\PaginatorHelper::hasPage(string $model = null, integer $page = 1)
Returns true if the given result set has the page number given by $page.

Cake\View\Helper\PaginatorHelper::total(string $model = null)
Returns the total number of pages for the provided model.

for more details check this link Checking the Pagination State


text:
Q: Pointers to members have different representations; cannot cast between them cocos2d-x x and new to programming too, i'm making a reversi but some way its give me an error.
can anyone help me?
CCSprite* bg = CCSprite::create("Images/Reversi.png");
addChild(bg, 1);
bg->setAnchorPoint(CCPointZero);

_midArea = CCLayerColor::create(ccc4(255, 0, 0, 0), 600, 600);
addChild(_midArea, 2);
_midArea->setAnchorPoint(CCPointZero);
_midArea->setPosition(ccp(88, 271));

CCMenu* menu = CCMenu::create();
_midArea->addChild(menu, 10);
menu->setAnchorPoint(ccp(0, 0));
menu->setPosition(ccp(0, 0));

_gameOver = CCMenuItem::create();
_gameOver->setTarget(this, menu_selector(GameLayer::startNewGame));
menu->addChild(_gameOver);
_gameOver->setAnchorPoint(ccp(0.5, 0.5));
_gameOver->setPosition(ccp(300, 300));
_gameOver->setContentSize(getContentSize());
CCSprite* overImg = CCSprite::create("Images/GameOver.png");
_gameOver->addChild(overImg);
CCSize layerSize = getContentSize();
overImg->setPosition(ccp(layerSize.width / 2, layerSize.height / 2));
_gameOver->setVisible(false);
_gameOver->setEnabled(false);

float gridSize = 75;

CCTextureCache* textureCache = CCTextureCache::sharedTextureCache();

_whiteTex = textureCache->addImage("Images/ReversiWhitePiece.png");
_blackTex = textureCache->addImage("Images/ReversiBlackPiece.png");
_whiteTex->retain();
_blackTex->retain();

for (int i = 0; i < NUM_ROW; i++) {
    for (int j = 0; j < NUM_COL; j++) {
        CCMenuItem* item = CCMenuItem::create();
        item->setContentSize(CCSizeMake(gridSize, gridSize));
        menu->addChild(item);
        item->setTarget(this, menu_selector(GameLayer::onClickGrid));
        item->setTag(i * NUM_COL + j);
        item->setAnchorPoint(ccp(0, 0));
        item->setPosition(ccp(j * gridSize, i * gridSize));

        _gridSprites[i][j] = CCSprite::createWithTexture(_whiteTex);
        _midArea->addChild(_gridSprites[i][j], 2);
        _gridSprites[i][j]->setVisible(false);
        _gridSprites[i][j]->setAnchorPoint(item->getAnchorPoint());
        _gridSprites[i][j]->setPosition(item->getPosition());

        _grids[i][j] = FLAG_NONE;

        if ((i == 3 && j == 3) || (i == 4 && j == 4)) {
            _grids[i][j] = FLAG_BLACK;
            _blackCount++;
            _gridSprites[i][j]->setTexture(_blackTex);
            _gridSprites[i][j]->setVisible(true);
        }
        else if ((i == 3 && j == 4) || (i == 4 && j == 3)) {
            _grids[i][j] = FLAG_WHITE;
            _whiteCount++;
            _gridSprites[i][j]->setTexture(_whiteTex);
            _gridSprites[i][j]->setVisible(true);
        }
    }
}

_curFlag = FLAG_BLACK;
_curFlagSprite = CCSprite::createWithTexture(_blackTex);
_midArea->addChild(_curFlagSprite, 1);
_curFlagSprite->setAnchorPoint(ccp(0, 0));
_curFlagSprite->setPosition(ccp(7 * 75, 75 * 8 + 25));

setKeypadEnabled(true);

scheduleUpdate();

printf("GameLayer::init whiteCount %d, blackCount %d\n", _whiteCount,
    _blackCount);

return true;

and this is an error
1>e:\games\game maker\cocos2d-x-2.2.6\cocos2d-x-2.2.6\projects\reversi2\classes\gamescene.cpp(48): error C2440: 'type cast' : cannot convert from 'void (__thiscall GameLayer::* )(cocos2d::CCNode *)' to 'cocos2d::SEL_MenuHandler'Pointers to members have different representations; cannot cast between them

and then its give me this too
1>e:\games\game maker\cocos2d-x-2.2.6\cocos2d-x-2.2.6\projects\reversi2\classes\gamescene.cpp(48): error C2660: 'cocos2d::CCMenuItem::setTarget' : function does not take 1 arguments

sorry english is not my mother leanguage so hope you all understand :v

A: I don't remember the solution, i think it was about a typecast :)


text:
Q: How to find out what's executing apt.systemd.daily? In Ubuntu cloud server images, apt update/upgrade is performed from different services, causing locking issues.
How do I find out what is exactly invoking apt-daily?
A ps aux --forest doesn't tell what's the parent:
root      0000  0.0  0.0   0000   000 ?        Ss   00:00   0:00 /bin/sh /usr/lib/apt/apt.systemd.daily install
root      0000  0.0  0.0   0000  0000 ?        S    00:00   0:00  \_ /bin/sh /usr/lib/apt/apt.systemd.daily lock_is_held install
root      0000  0.0 00.0 000000 000000 ?       Sl   00:00   0:00      \_ /usr/bin/python3 /usr/bin/unattended-upgrade

In addition to the difficulty of tracking the parent/invoking process, what puzzles me is that this machine has all the seemingly relevant services disabled:
systemctl disable apt-daily-upgrade.timer
systemctl disable apt-daily.timer
systemctl disable cloud-init
systemctl disable cron
systemctl disable unattended-upgrades

I still get locking issues even rebooting.
How can I find out what's invoking apt-daily? I can change everything at my will for example, I can modify /usr/lib/apt/apt.systemd.daily to perform any operation.
Output of systemctl list-timers:
NEXT                         LEFT        LAST PASSED UNIT                         ACTIVATES
Tue 2020-02-18 11:38:11 UTC  11min left  n/a  n/a    motd-news.timer              motd-news.service
Tue 2020-02-18 11:41:34 UTC  14min left  n/a  n/a    systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service
Wed 2020-02-19 01:08:41 UTC  13h left    n/a  n/a    apt-daily.timer              apt-daily.service
Wed 2020-02-19 06:13:55 UTC  18h left    n/a  n/a    apt-daily-upgrade.timer      apt-daily-upgrade.service
Mon 2020-02-24 00:00:00 UTC  5 days left n/a  n/a    fstrim.timer                 fstrim.service

5 timers listed.
Pass --all to see loaded but inactive timers, too.


text:
Q: Ranking search Results with Keywords in SQL I am having trouble starting this idea. I have an SQL database and an html interface with JAVA/Apache(tomcat). I was trying to make a simple database that sorts names of songs and matches to keywords about the songs.
Example I have entered keywords like "epic , movies , queen , sing" and a song like queen bohemian rhapsody meets most of the criteria it is an "epic" song from a "movie" and preformed by "queen" so this would make a value of 3.
and also in the database a song like queen we are the champion would meet all keywords (epic,movie,queen,sing) -> so this song would be a 4.
I've dabbled with the count functions in sql and some JAVA code but i cant seen to find a way to shift through the keywords, or count them to see which result is better.
Where should I look to learn how to make something like this ?

Thank You very much for the explanation and the links . After hours of reading and re-reading I understand more about databases structure. And have a near functional webpage. I have one last question . The queries give me a result of the song_ID and the count. I have thought of a few ways to get the song name to also display.
1st idea I had was to add the name to the junction table.
2nd was create a temp table (view) and then use that info to seek data from the other tables.
3rd was write a java code to take the orginal results and then only display the song name and count. ....
I think I am missing something easy in SQL abilities to handle the data better (and more efficiently).

A: Let's say your database has two columns: tag and song_id, as such:
CREATE TABLE tags(tag STRING KEY, song_id INT);

Then you could do everything in a SQL query:
SELECT song_id, count(*)
FROM tags
WHERE tag IN ("epic", "movie", "queen", "sing")
GROUP BY song_id
ORDER BY count(*) DESC;

If you want more complicated text search, i.e. if this solution ends up being too slow, you should look into Apache Lucene and/or Solr.

A: Three tables:

*

*songs with a primary key song_id which is an integer

*tags with a primary key of tag which is a string

*songs-tags which is a junction table that links the other two tables. It will have a composite primary key of song_id and tag
So if in songs we had these rows (tuples):

*

*song_id: 1; name: Bohemian Rhapsody

*song_id: 2; name: We Are The Champions

and in tags we had:

*

*tag: epic

*tag: movie

*tag: queen

*tag: sing

then in songs-tags we would have:

*

*song_id: 1; tag: epic

*song_id: 1; tag: movie

*song_id: 1; tag: queen

*song_id: 2; tag: epic

*song_id: 2; tag: movie

*song_id: 2; tag: queen

*song_id: 2; tag: sing

Now to find songs which match particular tags is just a question of selecting the relevant rows from the songs-tags tables.
The problem with your original design is that you are storing multiple tags in a single row. Instead you should have a separate row for each tag that matches a given song. If three tags match then you'll need three rows and so on.
You might want to read a bit about database normalization to understand why your original design doesn't work effectively
(NB in Joe K's earlier answer he basically suggested the same thing and gave you an SQL query to determine which tags match which songs. I've just fleshed things out a bit more)


text:
Q: WhenAnyValue is not getting called by RaisePropertyChanged I am new to ReactiveUI along with DynamicData
Declaration
 ReadOnlyObservableCollection<Employee> itemSource;
     public ReadOnlyObservableCollection<Employee> ItemSource
     {
        get => itemSource;
     }
     SourceList<Employee> Employees = new SourceList<Employee>();

Implementation
Employees
    .Connect()
    .Sort(SortExpressionComparer<Employee>.Ascending(emp => emp.ID))
    .Bind(out itemSource)
    .ObserveOn(RxApp.MainThreadScheduler)
    .Do(_ =>
         {
              this.RaisePropertyChanged(nameof(ItemSource));
         })
    .DisposeMany()
    .Subscribe()
    .DisposeWith(disposable);

  this.WhenAnyValue(x => x.itemSource)
      .Do(_ =>
    {
        Debug.Print("Called");

    });

But whenever I am calling
Employees.Add(new Employee
  {
    Name = "Hello" + DateTime.Now.ToShortDateString(),
    ID = random.Next(1,1000)
 });

I expect it to print "Called" in debug window as this.WhenAnyValue should be called, but apparently this is not the case.
Could you please help me to understand if I am doing any mistake?

A: Thanks Glen. I was able to fix it by using below code
this.WhenAnyValue(x => x.itemSource.Count)
      .Do(_ =>
    {
        Debug.Print("Called");

    });


text:
Q: How can I get rid of the rounded corners on the ListViewItem in a WPF listview? I have a style that I am applying to the ItemContainerStyle of a Listview. It puts a line across the bottom of the row and sets the height of the row.
However for some reason - each row seems to have rounded corners (as seen in the snapshot attached). When I look at the style in Blend - there are no rounded corners.
How can I get rid of the rounded corners?
<Style TargetType="ListViewItem" x:Key="RowStyle">
                <Setter Property="BorderThickness" Value="0,0,0,1" />
                <Setter Property="BorderBrush" Value="{DynamicResource ButtonPressedColor}" />
                <Setter Property="Height" Value="40" />
                <Setter Property="Background" Value="#FFF9EDED"/>

            </Style>

        <ListView x:Name="lvw_FileList" Background="{DynamicResource Watermark}" ItemContainerStyle="{StaticResource RowStyle}" BorderBrush="{DynamicResource GreyBorderColor}" BorderThickness="3" Margin="0" ItemsSource="{Binding Mode=OneWay}" d:DataContext="{d:DesignData /SampleData/SampleListItems.xaml}" Foreground="{DynamicResource TextColor}">
            <ListView.View>
                <GridView AllowsColumnReorder="False">
                    <GridView.ColumnHeaderContainerStyle>
                        <Style>
                            <Setter Property="UIElement.Visibility" Value="Collapsed" />
                        </Style>
                    </GridView.ColumnHeaderContainerStyle>
                    <GridViewColumn Header="Picture" CellTemplate="{DynamicResource PictureCell}" />
                    <GridViewColumn Header="Name" CellTemplate="{DynamicResource CompanyNameCell}" />
                    <GridViewColumn Header="Action" CellTemplate="{DynamicResource ActionCell}" />
                    <!--<GridViewColumn Header="Delete" Width="50"/>-->
                </GridView>
            </ListView.View>
        </ListView>

A: Round conrner is because of this line . you have assigned thickness 1 to the bottom
<Setter Property="BorderThickness" Value="0,0,0,1" />

change this to
 <Setter Property="BorderThickness" Value="0,0,0,0" />

A: I think this has nothing todo with your Style of the ListView, but with the Style of your GridViewColumn inside the ListView. Because that style is missing.
Could you post your sample data xml?


text:
Q: Validated a number with 2 decimal place and less than 1000 I know there are many similar question being asked, but i need help on this
and if possible please provide me a easy to follow and easy to understand tutorial for regex.
Here is some valid scenario
999.99 valid
100.00 valid
1111.00 invalid
111.002 invalid
the code should be written in this pattern

but i dont know how to code the output i want
thank you in advance!

A: You can set this restriction in an XSD document:
<xsd:simpleType name="2dnumber">
    <xsd:restriction base="xsd:token">
        <xsd:pattern value="[0-9]{1,3}\.[0-9]{2}|1000.00"/>
    </xsd:restriction>
</xsd:simpleType>

Or if you just want to use an xs:decimal directly:
<xsd:simpleType name="2dnumber">
    <xsd:restriction base="xsd:decimal">
        <xsd:minExclusive value="0"/>
        <xsd:maxExclusive value="1000"/>
        <xsd:fractionDigits value="2"/>
    </xsd:restriction>
</xsd:simpleType>

A: you can use something like
/^((\d{1,3}\.\d{2})|(1000.00))$/

\d{1,3} between one and three digits
\. a decimal
d{2} 2 digits after the decimal
| or
1000.00 special case for 1000.00
^ start of string
$ end of string
EDIT
if you want less than 1000, try this
/^((\d{1,3}\.\d{2})$/

A: If you need to match 1.00 to 1000.00 you can use the below:
^([1-9]{1,1}[0-9]{0,2}\.[0-9]{2})|(1000\.00)$


text:
Q: Java - Getting array of nouns with Wordnet and JWI I have a pretty easy question regarding WordNet and MIT JWI (Java API for accessing WordNet): I read a file into an array of strings, which I've split into words. How can I get a separate array of strings containing only the nouns using getPOS()? Thanks!
Example of what I've tried:
public class test {
public static void main(String[] args) {

    String sentence1 = "The cat ate the fish";

    String[] s1Split = sentence1.split(" ");

    String wnhome = "C:/Program Files/WordNet/2.1";
    String path = wnhome + File.separator + "dict";
    URL url = new URL("file", null , path);
    IDictionary dict = new Dictionary(url);
    dict.open();

    for (int i = 0; i <s1.length; i++) {
                    //this is where I got confused, wanted to use something like:
                    //Word w = dict.getIndexWord(s1[i], ..) but I need a POS argument,
                    //and I can't find another suitable method
                    //if w.getPOS() is a noun I would add it to a separate vector
    }

}

}
EDIT: Just thought of another one - would it be reliable to use something like w = dict.getIndexWord(s1[i], POS.NOUN), and if a noun doesn't exists, w will be null? Would this be something worth trying?
EDIT2: So my question atm would be if there's any way I can transform a string (word) into a Wordnet object, so I can use getPOS() on it?

A: Your approach isn't going to work as well as it could if you use another library - WordNet is designed as a 'dictionary/thesaurus' on steroids not a parser.  The Stanford Parser is a good place to look for an alternative.
That said, you can perform lookup on each word, but if there are words that are both nouns and, say verbs, you won't be able to distinguish because you're not considering syntax.
This should get you started (see the example on the bottom).  Do the lookup for a noun, if it doesn't come back, discard it.

A: For JWNL it works as the following, don't know if it is the same though.
If I have understood your problem is getting the POS (part of speech tags). To do this you must use another tool such as Stanford Pos Tagger. However in this way you get a string for each word string hence you must convert from the POS in string format to the POS in the POS class of JWNL.


text:
Q: Graph Warmth Defined Intuitively I'm a visual/spatial thinker, which is one of the reasons I heavily drawn to Graph Theory. However, I am struggling to learn about the concept of "warmth", and after checking multiple papers, the most promising definition was found here. It starts off with nice description of random-walk, but then quickly swerves to graph homeomorphisms before I got my bearings.
Specifically, I am unclear how they color this walk, or how this $d-walk$ works on non-regular graphs. I realize that afterwards I'll have to bite the bullet and read the nitty-gritty stuff, but I find that prefacing my learning with an intuitive understanding/context helps me in digesting everything.
Update: I tried skimming the later stuff to see if that would help, and now also want clarify if in the beginning of Section 2, the statement "we must show that $Hom(T^d,K_d)$ is not cold" was a typo, as to my understanding it should be $Hom(T^{d-2},K_d)$ instead.


text:
Q: What will be the new angle between the two 2d points if I rotate one point about another point by a certain angle I have two points $(x_1,y_1)$ and $(x_2,y_2)$. Using dot product I have calculated the angle between the two. Let's call this angle $A$. Now, I want to rotate $(x_2,y2)$ around $(x1,y1)$ such that resulting angle between the $(x_1,y_1)$ and $(x'_2, y'_2)$ becomes $5^\circ$. So, I continue like below.
Find angle of rotation which will $A' =(A -5)$. So new points will be
$$x'_2 = \cos(A')(x_2 - x_1) - \sin(A') (y_2 - y_1) + x_1$$
$$y'_2 = \sin(A')(x_2 - x_1) + \cos(A') (y_2 - y_1) + y_1$$
Is this correct?
if it's correct then the problem is that if I recalculate the angle using dot product between $(x_1,y_1)$ and $(x'_2,y'_2)$ then the resulting angle is not $5^\circ$. How can his be. My understanding of rotation and resulting new angle is wrong?

A: Using the dot product you can calculate the angle between two vectors, not between two points (What is the angle'' between two points''?).
So, if I well understand your problem, you have two vectors:  $\vec p_1=(x_1.y_1)^T$ and $\vec p_2=(x_2.y_2)^T$ and you want a new vector $\vec p=(x,y)$ such that.
$$
\begin{cases}
\frac{\vec p_1 \cdot \vec p}{|\vec p_1| |\vec p|}=\cos 5°\\
|\vec p -\vec p_1|=|\vec p_2-\vec p_1|
\end{cases}
$$
this is a system in the two unknowns $ (x,y)$ and solvin it you find the vector $\vec p$.
Now you can find the rotation angle $\theta$ of $\vec p_1$ around $p_1$ that gives $R_\theta(\vec p_2)=\vec p$ as the angle such that:
$$
\cos \theta =\frac{(\vec p-\vec p_1)\cdot(\vec p_2-\vec p_1)}{|\vec p-\vec p_1|^2}
$$


text:
Q: Deciding the date format in Excel/VBA Could you please help me, how can i decide the date format about this date? : 7/6/2019
Do you know some best practices for this issue? I check the format as MM/dd/yyyy and for example if i send a message from America to Europe the date value might change to 6/7/2019 when i open it.

A: Yes, sometimes, it is quite confusing. So I used to convert the date into text to avoid that.
Here is how I do it. Once it is shown in text, it won't be changed according to the system setting.
Here is how to convert date to text
Hope this helps.


text:
Q: This hermitian operator seems to have complex eigenvalues? It is easy to show that a hermitian operator must have real eigenvalues.
It is also easy to show that the operator $-i\dfrac{\partial}{\partial x}$ is hermitian.
But from a computational perspective, I feel like it is possible to just propose working counter-examples. Specifically, the following eigenvector problem,
$$
-i\dfrac{\partial}{\partial x}f(x) = \lambda f(x)
$$
appears to be solved by $f(x) = e^{-3x}$ with $\lambda = 3i \not\in \mathbb{R}$. We can verify by substitution:
\begin{align}
-i\dfrac{\partial}{\partial x}e^{-3x} &= 3ie^{-3x}\\
\\
3ie^{-3x} &= 3ie^{-3x}
\end{align}
This imaginary eigenvalue contradicts the proofs I linked to. I must be doing something illogical here, or misunderstanding the proofs.

A: What an operator is depends on which space it is defined on. Your link shows that $-i\dfrac{\partial}{\partial x}$ is Hermitian on $L^2$, $e^{-3x}$  is not in $L^2$, so it is not a counterexample. Doing this naively one can find an "eigenvector" of $-i\dfrac{\partial}{\partial x}$ for any complex number as an eigenvalue, namely $e^{ax}$ with a suitable $a$.


text:
Q: which is the right place to call the actions, componentWillMount() or componentDidMount()? componentWillMount() called before dom is rendered. shall I call my action from here or from componentDidMount()?
What is the difference and which one should i prefer?

A: componentWillMount is called before mounting, therefore if your action changes state 'synchronously' this action will not lead to a re-rendering. This would be one of the big differences. The docs suggest you use the constructor instead of this method to initialise your comp.
actions from inside componentDidMount() will lead to re-render which might get expensive if the action changes state for an upstream component (if they are stateful) network calls should be handled at this stage typically.

A: The plan is to deprecate componentWillMount() in React 17, so I wouldn't use that in new code.


text:
Q: Find the longest line starting with specific word(s) In my project I try to find the occurrences with the longest method name.
For example
private function anyVeryLongMethodName($param ...);

public function anyEvenLongerMethodName()

protected function ...()

I already found something like
^.{100,}$

which will not show exactly the longest match but will give a manageable result set when playing around with the count
Unfortunately, it does not consider starting with public/private/protected function
Is there an appropriate regex doing this job?

A: You may use this regex to match function names that are preceded by certain keywords and are 100 or more in length:
\b(?:public|private|protected)\s+function\s+(\w{100,})\s*\(

RegEx Demo
Regex Details:

*

*\b: Word boundary

*(?:public|private|protected): Match one of the 3 words

*\s+: Match 1+ whitespaces

*function: Match text function

*\s+: Match 1+ whitespaces

*(\w{100,}): Match 100 or more word characters in capture group #1

*\s*\(: Match 0+ whitespaces followed by a (


text:
Q: What is the safest way in ColdFusion to delete a folder and it's contents? I am finishing creating a file upload utility for our site, and if the upload is an invalid format (per our specs not worth going over here) I would want to delete the folder the zip file was unzipped to, and all it's contents.
So far I have used a method of creating a dynamic batch file like this:
    <!--- check if folder exists before starting to delete --->
<cfif directoryexists("#file_path_course#")>

    <!--- this can be passed in a varaible or whatever --->
    <cfset tDirectory = "#file_path_course#">

    <!--- This is what we will put in the bat file --->
    <cfset tString ="RMDIR /S /Q " & tDirectory>

    <!--- generate a .BAT file for later execution --->
    <cffile action="WRITE" file="#file_path_course#\delete.bat" output="#tString#">

    <!--- Now execute the file to delete everything (Folder and all sub-folders and files)--->
    <cfexecute name="#file_path_course#\delete.bat" timeout="60"></cfexecute>

    <!--- check if bat file exists --->
    <cfif fileexists("#file_path_course#\delete.bat")>

        <!--- now delete the bat file --->
        <cffile action="DELETE" file="#file_path_course#\delete.bat">

    </cfif>

    <!--- delete course folder --->
    <cfdirectory action="delete" directory="#file_path_course#" recurse="yes">

    <cfset course_files_deleted = "Yes">

</cfif>

But I am admittedly concerned about the allowed usage of the cfexecute tag.
There is another option, which uses the cfdirectory recurse delete option, which will do all I ask, but I want to be very sure it's not going to delete the folders/files outside the folder I point it to.
There is a 3rd way, which involves a cfdirectory and looping around it, but I also like the idea of using less lines of code to do a simple operation.
Which option do you trust the most?
I am running IIS7, Coldfusion 8.

A: Why not just use cfdirectory? You said you were worried that it would delete stuff "outside" the folder you specified. It won't. Simple as that. If it did, then the tag would be broken. :)

A: Instead of writing a batch file and then executing it, I let ColdFusion do all the work.
<cfset targetDirectory = "C:\Websites\site\thisFolder" />
<cfif directoryExists(targetDirectory)>
<cfdirectory action="list" directory="#targetDirectory#" listInfo="" name="theseFiles" recurse="true" type="file" />
    <cfif theseFiles.recordcount gt 0>
    <cfloop query="theseFiles">
        <cffile action="delete" file="#targetDirectory#/#theseFiles.name#" />
    </cfloop>
    </cfif>
<cfdirectory action="delete" directory="#uploadDirectory#/#allFolders.name#" />
</cfif>

A: what i would do is upload the file to a temp directory outside of the webroot. you can use gettempdirectory() to accomplish this which uses your system's temp directory (c:\windows\temp for windows)
then you can unzip the file into a subdirectory off of the temp directory and perform some security checks against the unzipped files and make sure everything is ok, all the while not opening up your site to any attacks. if everything pans out, you can then move the files to their final resting place. if not, just use cfdirectory (as cfjedimaster pointed out) to remove the subdirectory and all the files.


text:
Q: How to split autoencoder model to encoder and decoder in Keras? I have trained an autoencoder and saved it using keras built in save() method. Now I want to split it into two parts: Encoder and decoder. I can successfully load the model and get the encoder part by creating a new model using the old model:
encoder_model = keras.models.Model(inputs=self.model.input,
 outputs=self.model.get_layer(layer_of_activations).get_output_at(0))

However, if I try to do the alternative thing with decoder, I cannot. I tried it using various methods, none of which were correct. Then I found a similar issue here (Keras replacing input layer) and tried using this method using code below:
    for i, l in enumerate(self.model.layers[0:19]):
        self.model.layers.pop(0)
    newInput = Input(batch_shape=(None, None, None, 64))
    newOutputs = self.model(newInput)
    newModel = keras.models.Model(newInput, newOutputs)

The output shape of the last layer I remove is (None, None, None, 64), but this code produces the following error:
ValueError: number of input channels does not match corresponding dimension of filter, 64 != 3

I assume this is because the input dimensions of the model are not updated after popping original layers, which is noted in this question's first answer, second comment: Keras replacing input layer
Simply looping through the layers and recreating them in a new model does not work as my model is not sequential.

A: I resolved this by building a new model with the exact same architecture as the decoder part of the original autoencoder network and then just copied the weights.
Here's the code:
    # Looping through the old model and popping the encoder part + encoded layer
    for i, l in enumerate(self.model.layers[0:19]):
        self.model.layers.pop(0)

    # Building a clean model that is the exact same architecture as the decoder part of the autoencoder
    new_model = nb.build_decoder()

    # Looping through both models and setting the weights on the new decoder
    for i, l in enumerate(self.model.layers):
        new_model.layers[i+1].set_weights(l.get_weights())


text:
Q: Incomplete HTML after Executing `document.write()` After executing document.write(), Google Chrome shows me that the HTML codes is changed from Code A to Code B. It seems that document.write() overwrite the entire page. If yes, how to append the script tag inside head tag?

Code A : Before Executing document.write()

hi

Code B : After Executing document.write()

JavaScript in File .\js\main_CasCode.js
function main() {
    //console.log = function() {};
    loadjQuery();
    //waitjQueryLoaded_and_start();
}

function loadjQuery() {
    console.log("Loading jQuery...");
    var s = '';
    document.write(s);  //<----Problem Here
}

A: That's because document.write erases and rewrites the document when the document has already finished rendering (like after onload). It only appears to append when called during the rendering of the page.
A better way to do this is to dynamically create a script element, add it to the page, and add an src which triggers the loading mechanism.
var script = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(script);
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';

In other news, why are you loading jQuery dynamically when you have control of the page? Why not add it directly as a


text:
Q: Html5 movie insert into html as a background? Now I have a video(mp4,webm) as background of a html-section. But it does not look good on mobile. I would like place the original html file  into the html code, as background. (I have an animated html5  file whit js) Is it possible?
Thank you. enter link description here
<section class="pt-page pt-page-1 section-with-bg section-paddings-0" style="background-image: url(images/home_page_bg_1.jpg);" data-id="home">
            <video autoplay loop muted playsinline id="video-background">
              <source src="images/movie.mp4" type="video/mp4">
              <source src="images/moviewebm.webm" type="video/webm">
            </video>
        </section>

A: You have to implement different sizes of the video player for different screen sizes using CSS that will fill the screen.
I tested the link and it works fine. Just scale it.


text:
Q: Weird issue with simple CoffeeScript and jQuery events The event fires well on a wildcard selector, but fails if I use a specific ID for the selector.
This works:
$("*").click ->
  console.log "entered event."
  $("#tellafriend").dialog
    modal: true
    buttons:
      Ok: ->
        $(this).dialog "close"

Yet, this doesn't:
$("#tell-a-friend").click ->
  console.log "entered event."
  $("#tellafriend").dialog
    modal: true
    buttons:
      Ok: ->
        $(this).dialog "close"

And my relevant HTML:

Home

|

Tell a Friend

Am I missing something in CoffeeScript for this to work? Maybe jQuery selectors are formatted differently in CoffeeScript?
This is the rendered Javascript that my application serves (Rails convert CoffeeScript to JS when serving the pages):
(function() {

  $("#tell-a-friend").click(function() {
    console.log("works");
    return $("#tellafriend").dialog({
      modal: true,
      buttons: {
        Ok: function() {
          return $(this).dialog("close");
        }
      }
    });
  });

}).call(this);

A: Is it possible that the code is being executed before the DOM is completely loaded. Try wrapping it in a document ready handler so that any click handlers are applied after the DOM is completely loaded.  As it is, it may only be executing on the body element because that's the only element available at the time the script is executed.


text:
Q: how do I return list with separate character I have a string s = '10001001'.
When I use:
return [s[i:i+4] for i in range(0, len(s), 4)]

it returns
['1000','1001']

How can I modify my code to get
[1, 0, 0, 0], [1, 0, 0, 1]

A: This should work for you:
s = '10001001'
r = [list(map(int, s[i:i+4])) for i in range(0, len(s), 4)]
print(r) # [[1, 0, 0, 0], [1, 0, 0, 1]]

A: Borrowing from @jdaz suggestion, a list comprehension within a list comprehension is one way:
[[int(v) for v in s[i:i+4]] for i in range(0, len(s), 4)]

The range iterator splits it in chunks of 4 characters. The inner list comprehension loops over each character and passes that as a list.
What you will get is lists within a list:
[[1, 0, 0, 0], [1, 0, 0, 1]]


text:
Q: uwsgi : doesn't detect plugins In Ubuntu i installed uwsgi and then the plugins with the following commands :
$ sudo apt-get install uwsgi
$ sudo apt-get install uwsgi-plugin-python3
$ sudo apt-get install uwsgi-plugin-python

When i kill the process of uwsgi and rerun uwsgi with the following commands in a bash script :
#!/bin/bash
echo '********* kill instance ******************'
sudo kill -HUP `cat /tmp/sup-epa.pid`
uwsgi --reload /tmp/sup-epa.pid
sudo touch /tmp/sup.epa.sock

uwsgi --emperor /etc/uwsgi/vassals/

The output is :
!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!
no request plugin is loaded, you will not be able to manage requests.
you may need to install the package for your language of choice, or simply load it with --plugin.
!!!!!!!!!!! END OF WARNING !!!!!!!!!!

But in fact the uwsgi configuration file has it :
[uwsgi]
plugins-dir=/usr/lib/uwsgi/plugins/
plugin = python3

The best aproach according to the manual is to put the parameters in one ini file and then load it with the ini. Should i run the uwsgi with path of plugin and then put the --plugin parameter ?

A: You can use the ini file with emperor mode without problem.
With the distro packages you have installed you should specify plugin = python. There is no need of plugin-dir here. You may not use plugin = pythonXX unless you want to specify wich version of python you want to use. But you need aditional conf if you want to do this this way. See the quickstart for python chapter "Bonus: multiple Python versions for the same uWSGI binary".
Or you can specify a fixed version with something like: sudo update-alternatives --set uwsgi /usr/bin/uwsgi_python27. Provided that the version you want is installed sudo update-alternatives --list uwsgi


text:
Q: Why is bootstrapping important and what are some of the benefits? I'm curious why bootstrapping is essential to web development and what are some of the benefits? for example, can it help with developing a website for mobile use like aligning things correctly or can it make the process smoother? Can someone explain that and give some examples to where I can understand the importance of the procedure.

A: Bootstrap is not essential to web development! It's popular.
Because it covers HTML, CSS, Javascript-based design in one package. It's a good choice for some projects that need fast development without letting you to make your hands dirty.
Like other stuffs in the market, Bootstrap is not a silver bullet. It has it's advantages and disadvantages too.

can it help with developing a website for mobile use like aligning things correctly or can it make the process smoother?

As Bootstrap is mobile-first framework, your answer is obviously yes. It has a flexible mobile friendly Grid system that makes your work simpler, and prevents you from hard working with @media rules. Whether your clients see your website on mobile, tablet, or desktop.
Excluding grid system, Bootstrap contains many design templates for typography, forms, buttons, navigation and other interface components, that you can use and finish your projects faster. I'm not a fan of Bootstrap, but it's a good choice for small websites, small teams, or personal projects.
Here is a good comparison between its advantages and disadvantages.


text:
Q: Rust tonic Issue error `tonic::request::Request`, which does not implement the `Copy` trait I am using tonic:2.0 for grpc implementation, I have created proto with service  userdetails with message request username and user email as shown in below proto file with rust implementation. I am facing error when I use
request request: Request<userRequest> multiple time. Please help me how I can solve this issue
syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.userDetails";
option java_outer_classname = "providerUserDetails";

package provider;

service Provider {
  // Sends a greeting
  rpc userdetails (userRequest) returns (userResponse) {}

}

// The request message containing the user's name.
message userRequest {
  string username = 1;
  string useremail =2;
}

message userResponse {
  bool message =1;
}

Rust tonic implementation for proto
    async fn create_contract(
        &self,
        request: Request<userRequest>, // Accept request of type userDetails
    ) -> Result<Response<userResponse>, Status> {
        let mut bc = self.bc.lock().unwrap();

        let user_name = request.into_inner().username;
        let user_email = request.into_inner().useremail;

    }

> Error: request.into_inner().useremail;
    |                   ^^^^^^^ value used here after move value used here after move


text:
Q: how minify css files works in mvc4? I'm new in mvc4 i read this article to find what is bundle and minify in mvc4
http://go.microsoft.com/fwlink/?LinkId=254725
i create an new sample project to test css minifing and add tree css file in my theme folder
and
public class BundleConfig
{

    public static void RegisterBundles(BundleCollection bundles)
    {

        bundles.Add(new StyleBundle("~/Content/css").Include(
                    "~/Content/themes/default/public.css",
                    "~/Content/themes/default/home.css",
                    "~/Content/themes/default/footer.css"));
     }

and in my master layout :
 @Styles.Render("~/Content/css")

it works fine but i can not understand minifying because when i look at my net thab on firebug tolls i saw  my page loads that three css files I'm confuse on two things
1-why it load that css file is it normally or browser should load one file with all of my css files contains?
2-i should create minifiyng folder and minify my css an remove comments and.. and use theme
on my project or i use some configs until mvc do it  by itself?

A: First change it to release mode, as it only works in this mode, not Debug.
If you haven't already done so, in your BundleConfig, add:
        BundleTable.EnableOptimizations = true;

A: Run in your application in Release mode:
<compilation debug="false">

and watch what happens.


text: Q: Power function in non-commutative algebras Is there a canonical form of the power function, $a^b=x$, that extends to non-commutative algebras like matrices and hypercomplex numbers? It is known that $a^b=e^{b\log{a}}$ for commutative algebras, but in commutative algebras, $e^{b\log{a}}=e^{\log(a)b}=(e^{\log{a}})^b$, which is not true when you don't have the luxury of commutativity. In other words, is there a standard way to define things like $M_1^{M_2}$ for $M_1,M_2 \in M_{n\times n}$ or $Q_1^{Q_2}$ for $Q_1, Q_2 \in \mathbb{H}$?


text:
Q: C# - Coding a codecave (aobinjection) lately I've been learning how to work with injections and cheat engine to disassemble potential malware and locked programs. I am making fast progress but am stuck on one thing now.
Cheat engine itself has a feature named "AOB Injection" which allows replacing code with a jmp which jumps to new allocated memory, there you can write new opcode and return after executing it. That's called "AOB Injection" or "Code cave".
Now I am struggling to create a code cave for my process.
Using a Memory.dll NuGet creating a code cave shouldn't be that hard as it already has that feature implemented, but it looks like it doesn't work for me as I am probably doing something wrong?
My Code:
m.OpenProcess("Process"); //allocating Process.exe to the Memory NuGet
byte[] freezebytesX = { 0xF3, 0x0F }; //Bytes to add to the code cave

//creating a codecave at "UserAssembly+36652EE2"  with the size of 2 Bytes
UIntPtr codecavebase = m.CreateCodeCave("UserAssembly+36652EE", freezebytesX, 2);

UIntPtr codecaveAllocAddress = UIntPtr.Add(codecavebase, freezebytesX.Length);
int newint = (int)codecaveAllocAddress - 6;

Console.WriteLine("Read Allocated Memory: 0x" + newint.ToString("X") + "\r\n" + codecaveAllocAddress);

So it says that it allocated the opcode in console but if i check the opcode it is still the same and didn't change at all. Shouldn't it change it to a jmp which jumps to the code cave created?
Thanks for any help :)


text:
Q: Using beamer frame title in document text I use beamer to create a set of slides that are used to present the contents of a document. Both the slides and the printable document contents are contained in a single set of source files; I use the \mode commands to switch between presentation and printout mode. In contrast to some of the beamer examples I have seen so far, the printable version does not contain the complete slides as images. The slides and the printable version share some graphics and other contents, and I use a \marginpar to create a kind of link between the slides and the printable version, just to let the audience keep track. Here is a MWE, consisting of three files:
% === printable.tex =======================================
\documentclass{scrartcl}
\usepackage{beamerarticle}

\begin{document}
\input{contents}
\end{document}
% === end of printable.tex ================================

% === slides.tex ==========================================
\documentclass{beamer}

\begin{document}
\input{contents}
\end{document}
% === end of slides.tex ===================================

% === contents.tex =======================================
\mode*

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Fusce laoreet dui vestibulum tortor luctus porttitor.
Aliquam dictum ipsum condimentum, auctor augue in,
consectetur lacus. Morbi auctor posuere scelerisque.
Aenean vel enim sit met orci rutrum fermentum faucibus et
mauris. Pellentesque tempor felis in imperdiet accumsan.
Mauris auctor pretium nulla et tincidunt.

\mode<presentation>
\begin{frame}
  \frametitle{Foo Bar}
  \begin{itemize}
    \item Foo
    \item Bar
    \item Baz
  \end{itemize}
\end{frame}
\mode*

Mauris\marginpar{Foo Bar} malesuada nisl sit amet nisl
eleifend tincidunt. Sed sed libero scelerisque, ultrices
elit a, lacinia mi. Mauris nec semper metus, eget
pellentesque leo. Donec volutpat aliquam aliquam. Nunc
vel neque scelerisque, aliquam augue eget, gravida felis.
Suspendisse vel molestie libero.

% === end of contents.tex =================================

As you can see, I have to manually repeat the frame title Foo Bar in the \marginpar. I tend to forget to do that, and I especially tend to forget to update the repetition when the title changes. Is there a way to specify the title only once and use it for the \frametitle as well for the \marginpar?

A: You just need to define different templates for article and presentation modes. If you include
\setbeamertemplate{frametitle}{\marginnote{\insertframetitle}}

in printable.tex preamble then frame title will appear on the margin if you are also processing frames in article version. (\marginnote is defined in marginnote package)
In your example, all frame contents is skipped because it is preceded by \mode<presentation>. Instead you can use something like:
\begin{frame}
  \frametitle{Foo Bar}
  \only<beamer>{%
     \begin{itemize}
       \item Foo
       \item Bar
       \item Baz
  \end{itemize}%
  } %<- \only<beamer> closing
\end{frame}

This way, only frame contents will be skipped while frametitle is processed and printed as a margin note. You don't need to include any \marginpar{Foo Bar} into next paragraph.
Please, look at Changing \mode in beamer makes a new paragraph. Is it possible to avoid it? and How to better adjust placement of frametitle converted to marginpar in beamerarticle? and you will see why I prefer to use \only and \marginnote.
Your complete example adapted with previous solution is
% === printable.tex =======================================
\documentclass{scrartcl}
\usepackage{beamerarticle}
\usepackage{marginnote}

\setbeamertemplate{frametitle}{\marginnote{\insertframetitle}}

\begin{document}
\input{contents}
\end{document}
% === end of printable.tex ================================
%
% === slides.tex ==========================================
\documentclass{beamer}

\begin{document}
\input{contents}
\end{document}
% === end of slides.tex ===================================
%
% === contents.tex =======================================

\mode*
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Fusce laoreet dui vestibulum tortor luctus porttitor.
Aliquam dictum ipsum condimentum, auctor augue in,
consectetur lacus. Morbi auctor posuere scelerisque.
Aenean vel enim sit met orci rutrum fermentum faucibus et
mauris. Pellentesque tempor felis in imperdiet accumsan.
Mauris auctor pretium nulla et tincidunt.

\begin{frame}
  \frametitle{Foo Bar}
\only<beamer>{\begin{itemize}
    \item Foo
    \item Bar
    \item Baz
  \end{itemize}}
\end{frame}

\mode*
Mauris malesuada nisl sit amet nisl
eleifend tincidunt. Sed sed libero scelerisque, ultrices
elit a, lacinia mi. Mauris nec semper metus, eget
pellentesque leo. Donec volutpat aliquam aliquam. Nunc
vel neque scelerisque, aliquam augue eget, gravida felis.
Suspendisse vel molestie libero.

% === end of contents.tex =================================

Note: A very nice example to understand how to work with beamerarticle to produce presentations and printed version from same sources is a-lecture. It's written by Till Tantau and is part of beamer distribution, so probably it's in your computer. Take a look at it!
Addition by vwegert:
With the help of the package environ, I managed to define an environment that -- in contrast to the open \only<beamer>{ command -- does not wreak havoc with the syntax highlighting, pretty printer and other tools:
% === printable.tex =======================================
\documentclass{scrartcl}
\usepackage{beamerarticle}
\input{preamble}
\setbeamertemplate{frametitle}{\marginpar{\insertframetitle}}

\begin{document}
\input{contents}
\end{document}
% === end of printable.tex ================================

% === slides.tex ==========================================
\documentclass{beamer}
\input{preamble}

\begin{document}
\input{contents}
\end{document}
% === end of slides.tex ===================================

% === preamble.tex =======================================
\usepackage{environ}
\NewEnviron{onlybeamer}{\only<beamer>{\BODY}}
% === end of preamble.tex =================================

% === contents.tex =======================================
\mode*

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Fusce laoreet dui vestibulum tortor luctus porttitor.
Aliquam dictum ipsum condimentum, auctor augue in,
consectetur lacus. Morbi auctor posuere scelerisque.
Aenean vel enim sit met orci rutrum fermentum faucibus et
mauris. Pellentesque tempor felis in imperdiet accumsan.
Mauris auctor pretium nulla et tincidunt.

\begin{frame}
  \frametitle{Foo Bar}
  \begin{onlybeamer}
    \begin{itemize}
      \item Foo
      \item Bar
      \item Baz
    \end{itemize}
  \end{onlybeamer}
\end{frame}
\mode*

Mauris malesuada nisl sit amet nisl
eleifend tincidunt. Sed sed libero scelerisque, ultrices
elit a, lacinia mi. Mauris nec semper metus, eget
pellentesque leo. Donec volutpat aliquam aliquam. Nunc
vel neque scelerisque, aliquam augue eget, gravida felis.
Suspendisse vel molestie libero.

\mode<all>
% === end of contents.tex =================================


text:
Q: auto_increment usage in composite key I am having a table with the composite key
emp_tbl(
companyId int not null,
empId int not null auto_increment,
name varchar2,
....
...
primary key(companyId,empId)
);

In mysql whats happening is while i starts inserting the data
Emp_tbl
companyId    empId
1             1
1             2
1             3
2             1
2             2

Note that when the companyId changes the auto_increament value is resetted to 1 again. I want to disable that. I mean i don't want to reset the auto_increament. I am expecting the result like this.
companyId    empId
1             1
1             2
1             3
2             4
2             5

Is it possible to do it?
Thanks

A: This is what happens with a composite primary key that incorporates a auto_increment. Recreate the primary key so that it's purely your auto_increment field (empId) then create a unique index on companyId and empId
EDIT
Note that this only applies to MyISAM and BDB tables. If you used InnoDB for your tables, then it would also work as you wanted

A: If you do not want empId to reset then just reverse the order of primary definition
primary key(companyId,empId)

note that composite key order matters.


text:
Q: Is there any performance enhancement to passing data to the context object vs using graphQL query on page in Gatsby? I'm wondering if there are any performance enhancements, or any benefits at all, to passing data via the context object for pages built using the createPages function in the gatsby-node file vs using a graphQL query in that template to get the same data.
I haven't noticed any differences, aside from cutting down some redundancy in code when you've already handled some incoming data in the gatsby-node file and you might as well pass it to the page.
But what about when you've made a query in the node file and you haven't done much with the data? Should you pass all that in via the context object? Or is it better to handle that in an explicit query in the page template itself?

A: The main proposal of using gatsby-node.js queries is to create pages dynamically based on query results. The obvious example is a blog; the idea is to query all the articles/posts from a blog, create pages from them via createPages API and pass through context some identifier value to query the parameters from each post (typically the slug). They are under the scope of Gatsby Node API and are not intended to play with data, just interact with them using the Node API. It is based on the server-side.
On the other hand, a standard page query (or staticQuery) is used to gather data based on the query, and use it directly on a page/component.
All kinds of GraphQL queries are triggered by the develop/build. In addition, they have different scopes, different proposals, and different usages so, the comparison isn't fair in this case.
Since Node APIs queries are promise-based, if they manage a humongous amount of data, may overload the build/develop time because they will block the rest of the compilation. So in this case, it will be better to add this load to page queries rather than Node API-based queries.


text:
Q: Including OCR into Android Studio C++ project Using Android Studio, I have written an experimental app that runs OpenCV from within C++ code that is run natively via JNI. Everything that I tried in basic OpenCV works as expected.
Now I want to experiment with the "text" module from OpenCV Contrib. That is, the OCR / Tesseract module. For some reason, I don't get anywhere.
As I understand it there are several versions of this library. One called tess4j, another called tess-two and then opencv-contrib. The last one is the best choice?
Any pointers?
One nice person has made a sample, which I downloaded https://github.com/pethoalpar/AndroidOpenCvTesseractGetTextFromImage
and it does build for me, but doesn't work when running it (on my phone S8+).
I get this:
05-27 17:15:26.371 411-411/? E/Zygote: isWhitelistProcess - Process is Whitelisted
05-27 17:15:26.372 411-411/? E/libpersona: scanKnoxPersonas
    Couldn't open the File - /data/system/users/0/personalist.xml - No such file or directory
05-27 17:15:26.373 411-411/? W/SELinux: SELinux selinux_android_compute_policy_index : Policy Index[2],  Con:u:r:zygote:s0 RAM:SEPF_SM-G955F_8.0.0_0002, [-1 -1 -1 -1 0 1]
05-27 17:15:26.374 411-411/? I/SELinux: SELinux: seapp_context_lookup: seinfo=untrusted, level=s0:c512,c768, pkgname=com.pethoalpar.myapplication
05-27 17:15:26.377 411-411/? I/zygote64: Late-enabling -Xcheck:jni
05-27 17:15:26.406 411-411/? D/TimaKeyStoreProvider: TimaKeyStore is not enabled: cannot add TimaSignature Service and generateKeyPair Service
05-27 17:15:26.407 411-411/? D/ActivityThread: Added TimaKeyStore provider
05-27 17:15:26.588 411-416/com.pethoalpar.myapplication I/zygote64: Do partial code cache collection, code=30KB, data=21KB
    After code cache collection, code=30KB, data=21KB
    Increasing code cache capacity to 128KB
05-27 17:15:26.598 411-434/com.pethoalpar.myapplication I/vndksupport: sphal namespace is not configured for this process. Loading /vendor/lib64/egl/libGLES_mali.so from the current namespace instead.
05-27 17:15:26.601 411-411/com.pethoalpar.myapplication I/InstantRun: starting instant run server: is main process
05-27 17:15:26.622 411-434/com.pethoalpar.myapplication D/libEGL: loaded /vendor/lib64/egl/libGLES_mali.so
05-27 17:15:26.765 411-411/com.pethoalpar.myapplication D/OpenCV/StaticHelper: Trying to get library list
05-27 17:15:26.774 411-411/com.pethoalpar.myapplication E/OpenCV/StaticHelper: OpenCV error: Cannot load info library for OpenCV
05-27 17:15:26.774 411-411/com.pethoalpar.myapplication D/OpenCV/StaticHelper: Library list: ""
    First attempt to load libs
    Trying to init OpenCV libs
    Trying to load library opencv_java3
05-27 17:15:26.775 411-411/com.pethoalpar.myapplication D/OpenCV/StaticHelper: Cannot load library "opencv_java3"
05-27 17:15:26.775 411-411/com.pethoalpar.myapplication W/System.err: java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/base.apk", zip file "/data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_dependencies_apk.apk", zip file "/data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_0_apk.apk", zip file "/data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_1_apk.apk", zip file "/data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_2_apk.apk", zip file "/data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_3_apk.apk", zip file "/data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_4_apk.apk", zip file "/data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_5_apk.apk", zip file "/data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_6_apk.apk", zip file "/data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_7_apk.apk", zip file "/data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_8_apk.apk", zip file "/data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/lib/arm64, /data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/base.apk!/lib/arm64-v8a, /data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_dependencies_apk.apk!/lib/arm64-v8a, /data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_0_apk.apk!/lib/arm64-v8a, /data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_1_apk.apk!/lib/arm64-v8a, /data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_2_apk.apk!/lib/arm64-v8a, /data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_3_apk.apk!/lib/arm64-v8a, /data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_4_apk.apk!/lib/arm64-v8a, /data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_5_apk.apk!/lib/arm64-v8a, /data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_6_apk.apk!/lib/arm64-v8a, /data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_7_apk.apk!/lib/arm64-v8a, /data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_8_apk.apk!/lib/arm64-v8a, /data/app/com.pethoalpar.myapplication-xdmsHX5km2PWImYxDfnyhQ==/split_lib_slice_9_apk.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]] couldn't find "libopencv_java3.so"
05-27 17:15:26.776 411-411/com.pethoalpar.myapplication W/System.err:     at java.lang.Runtime.loadLibrary0(Runtime.java:1011)
        at java.lang.System.loadLibrary(System.java:1657)
        at org.opencv.android.StaticHelper.loadLibrary(StaticHelper.java:64)
        at org.opencv.android.StaticHelper.initOpenCVLibs(StaticHelper.java:95)
        at org.opencv.android.StaticHelper.initOpenCV(StaticHelper.java:39)
        at org.opencv.android.OpenCVLoader.initDebug(OpenCVLoader.java:91)
        at com.pethoalpar.myapplication.MainActivity.onResume(MainActivity.java:80)
        at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1361)
        at android.app.Activity.performResume(Activity.java:7344)
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3763)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3828)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3036)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6938)
05-27 17:15:26.777 411-411/com.pethoalpar.myapplication W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
05-27 17:15:26.777 411-411/com.pethoalpar.myapplication D/OpenCV/StaticHelper: First attempt to load libs fails
05-27 17:15:26.777 411-411/com.pethoalpar.myapplication D/MainActivity: OpenCv problem
05-27 17:15:26.790 411-416/com.pethoalpar.myapplication I/zygote64: Do partial code cache collection, code=61KB, data=37KB
    After code cache collection, code=61KB, data=37KB
    Increasing code cache capacity to 256KB
05-27 17:15:26.797 411-436/com.pethoalpar.myapplication D/OpenGLRenderer: HWUI GL Pipeline
05-27 17:15:26.802 411-411/com.pethoalpar.myapplication D/ViewRootImpl@bd62c20[MainActivity]: setView = DecorView@c62b9d9[MainActivity] TM=true MM=false
05-27 17:15:26.804 411-411/com.pethoalpar.myapplication D/OpenCVManager/Helper: Service connection created
05-27 17:15:26.807 411-411/com.pethoalpar.myapplication D/OpenCVManager/Helper: Trying to get library path
    Trying to get library list
    Library list: "libopencv_java3.so"
    First attempt to load libs
    Trying to init OpenCV libs
    Trying to load libs by dependency list
    Trying to load library /data/app/org.opencv.engine-1/lib/arm64/libopencv_java3.so
05-27 17:15:26.814 411-411/com.pethoalpar.myapplication D/OpenCVManager/Helper: OpenCV libs init was ok!
    First attempt to load libs is OK
05-27 17:15:26.819 411-411/com.pethoalpar.myapplication I/OpenCVManager/Helper: General configuration for OpenCV 3.3.1 =====================================
      Version control:               3.3.1
05-27 17:15:26.820 411-411/com.pethoalpar.myapplication I/OpenCVManager/Helper:   Platform:
        Timestamp:                   2017-10-24T14:00:34Z
        Host:                        Linux 4.8.0-58-generic x86_64
        Target:                      Linux 1 aarch64
        CMake:                       2.8.12.2
        CMake generator:             Ninja
        CMake build tool:            /usr/bin/ninja
        Configuration:               Release
      CPU/HW features:
        Baseline:                    NEON
          requested:                 NEON FP16
          required:                  NEON
          disabled:                  VFPV3
      C/C++:
        Built as dynamic libs?:      NO
        C++ Compiler:                /usr/bin/ccache /opt/android/android-ndk-r10e/toolchains/aarch64-linux-android-4.9/prebuilt/linux-x86_64/bin/aarch64-linux-android-g++ (ver 4.9)
        C++ flags (Release):         -fexceptions -frtti -Wno-psabi --sysroot=/opt/android/android-ndk-r10e/platforms/android-21/arch-arm64 -funwind-tables -fsigned-char -no-canonical-prefixes -fdata-sections -ffunction-sections -Wa,--noexecstack    -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wno-narrowing -Wno-delete-non-virtual-dtor -Wno-comment -fdiagnostics-show-option -fomit-frame-pointer   -fvisibility=hidden -fvisibility-inlines-hidden -fomit-frame-pointer -fstrict-aliasing -funswitch-loops -finline-limit=300 -O3 -DNDEBUG  -DNDEBUG
        C++ flags (Debug):           -fexceptions -frtti -Wno-psabi --sysroot=/opt/android/android-ndk-r10e/platforms/android-21/arch-arm64 -funwind-tables -fsigned-char -no-canonical-prefixes -fdata-sections -ffunction-sections -Wa,--noexecstack    -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wno-narrowing -Wno-delete-non-virtual-dtor -Wno-comment -fdiagnostics-show-option -fomit-frame-pointer   -fvisibility=hidden -fvisibility-inlines-hidden -fno-omit-frame-pointer -fno-strict-aliasing -O0 -g -DDEBUG -D_DEBUG  -DDEBUG -D_DEBUG
        C Compiler:                  /usr/bin/ccache /opt/android/android-ndk-r10e/toolchains/aarch64-linux-android-4.9/prebuilt/linux-x86_64/bin/aarch64-linux-android-gcc
        C flags (Release):           -fexceptions -Wno-psabi --sysroot=/opt/android/android-ndk-r10e/platforms/android-21/arch-arm64 -funwind-tables -fsigned-char -no-canonical-prefixes -fdata-sections -ffunction-sections -Wa,--noexecstack    -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Winit-self -Wno-narrowing -Wno-comment -fdiagnostics-show-option -fomit-frame-pointer   -fvisibility=hidden -fomit-frame-pointer -fstrict-aliasing -funswitch-loops -finline-limit=300 -O3 -DNDEBUG  -DNDEBUG
        C flags (Debug):             -fexceptions -Wno-psabi --sysroot=/opt/android/android-ndk-r10e/platforms/android-21/arch-arm64 -funwind-tables -fsigned-char -no-canonical-prefixes -fdata-sections -ffunction-sections -Wa,--noexecstack    -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Winit-self -Wno-narrowing -Wno-comment -fdiagnostics-show-option -fomit-frame-pointer   -fvisibility=hidden -fno-omit-frame-pointer -fno-strict-aliasing -O0 -g -DDEBUG -D_DEBUG  -DDEBUG -D_DEBUG
        Linker flags (Release):      -Wl,--no-undefined -Wl,--gc-sections -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now
        Linker flags (Debug):        -Wl,--no-undefined -Wl,--gc-sections -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now
        ccache:                      YES
        Precompiled headers:         NO
        Extra dependencies:          z dl m log
        3rdparty dependencies:       libcpufeatures libprotobuf libjpeg libwebp libpng libtiff libjasper IlmImf tegra_hal tbb
      OpenCV modules:
        To be built:                 core flann imgproc ml objdetect photo video dnn imgcodecs shape videoio highgui superres features2d calib3d java stitching videostab
        Disabled:                    js world
        Disabled by dependency:      -
        Unavailable:                 cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev python2 python3 ts viz
      Android:
        Android ABI:                 arm64-v8a
        STL type:                    gnustl_static
        Native API level:            android-21
        SDK target:                  android-21
        Android NDK:                 /opt/android/android-ndk-r10e (toolchain: aarch64-linux-android-4.9)
        android tool:                /opt/android/android-sdk-java7/tools/android (Android SDK Tools, revision 25.2.2.)
        Google Play manager:         NO
        Android examples:            YES
      GUI:
        GTK+:                        NO
        GThread :                    NO
        GtkGlExt:                    NO
        OpenGL support:              NO
        VTK support:                 NO
      Media I/O:
        ZLib:                        z (ver 1.2.3)
        JPEG:                        build (ver 90)
        WEBP:                        build (ver encoder: 0x020e)
        PNG:                         build (ver 1.6.24)
        TIFF:                        build (ver 42 - 4.0.2)
        JPEG 2000:                   build (ver 1.900.1)
        OpenEXR:                     build (ver 1.7.1)
        GDAL:                        NO
        GDCM:                        NO
      Video I/O:
      Parallel framework:            TBB (ver 2018.0 interface 10001)
      Trace:                         YES ()
      Other third-party libraries:
        Use Intel IPP:               NO
        Use Intel IPP IW:            NO
        Use Eigen:                   NO
        Use Cuda:                    NO
        Use OpenCL:                  NO
        Use OpenVX:                  NO
        Use custom HAL:              YES (carotene (ver 0.0.1))
      Python 2:
        Interpreter:                 /usr/bin/python2.7 (ver 2.7.6)
      Python 3:
        Interpreter:                 /usr/bin/python3.4 (ver 3.4.3)
      Python (for build):            /usr/bin/python2.7
      Java:
        ant:                         /usr/bin/ant (ver 1.9.3)
        Java wrappers:               YES
        Java tests:                  NO
      Matlab:                        NO
      Tests and samples:
        Tests:                       NO
        Performance tests:           NO
        C/C++ Examples:              NO
      Install path:                  /build/master_pack-android/build/o4a/install
      cvconfig.h is in:              /build/master_pack-android/build/o4a
    -----------------------------------------------------------------
05-27 17:15:26.821 411-411/com.pethoalpar.myapplication D/OpenCVManager/Helper: Init finished with status 0
    Unbind from service
05-27 17:15:26.823 411-411/com.pethoalpar.myapplication D/OpenCVManager/Helper: Calling using callback
05-27 17:15:26.834 411-411/com.pethoalpar.myapplication D/ViewRootImpl@bd62c20[MainActivity]: dispatchAttachedToWindow
05-27 17:15:26.849 411-411/com.pethoalpar.myapplication V/Surface: sf_framedrop debug : 0x4f4c, game : false, logging : 0
05-27 17:15:26.850 411-411/com.pethoalpar.myapplication D/ViewRootImpl@bd62c20[MainActivity]: Relayout returned: old=[0,0][0,0] new=[0,0][1440,2960] result=0x7 surface={valid=true 507596918784} changed=true
05-27 17:15:26.856 411-436/com.pethoalpar.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
05-27 17:15:26.856 411-436/com.pethoalpar.myapplication D/OpenGLRenderer: Swap behavior 2
05-27 17:15:26.858 411-436/com.pethoalpar.myapplication D/libGLESv1: STS_GLApi : DTS, ODTC are not allowed for Package : com.pethoalpar.myapplication
05-27 17:15:26.862 411-436/com.pethoalpar.myapplication D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000,  [1440x2960]-format:1
05-27 17:15:26.862 411-436/com.pethoalpar.myapplication D/OpenGLRenderer: eglCreateWindowSurface = 0x7640e13e50
05-27 17:15:26.922 411-411/com.pethoalpar.myapplication D/ViewRootImpl@bd62c20[MainActivity]: MSG_RESIZED_REPORT: frame=Rect(0, 0 - 1440, 2960) ci=Rect(0, 96 - 0, 192) vi=Rect(0, 96 - 0, 192) or=1
    MSG_WINDOW_FOCUS_CHANGED 1
05-27 17:15:26.926 411-411/com.pethoalpar.myapplication V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo@9eee7aa nm : com.pethoalpar.myapplication ic=null
05-27 17:15:26.926 411-411/com.pethoalpar.myapplication I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
05-27 17:15:26.944 411-411/com.pethoalpar.myapplication V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo@cca9f9b nm : com.pethoalpar.myapplication ic=null
05-27 17:15:30.789 411-411/com.pethoalpar.myapplication D/ViewRootImpl@bd62c20[MainActivity]: ViewPostIme pointer 0
05-27 17:15:30.837 411-411/com.pethoalpar.myapplication D/ViewRootImpl@bd62c20[MainActivity]: ViewPostIme pointer 1
05-27 17:15:30.852 411-411/com.pethoalpar.myapplication E/MainActivity: file:///storage/emulated/0/Tess/imgs/ocr.jpg exposed beyond app through ClipData.Item.getUri()
05-27 17:15:31.221 411-411/com.pethoalpar.myapplication D/ViewRootImpl@bd62c20[MainActivity]: ViewPostIme pointer 0
05-27 17:15:31.271 411-411/com.pethoalpar.myapplication D/ViewRootImpl@bd62c20[MainActivity]: ViewPostIme pointer 1
05-27 17:15:31.282 411-411/com.pethoalpar.myapplication E/MainActivity: file:///storage/emulated/0/Tess/imgs/ocr.jpg exposed beyond app through ClipData.Item.getUri()
05-27 17:15:31.535 411-411/com.pethoalpar.myapplication D/ViewRootImpl@bd62c20[MainActivity]: ViewPostIme pointer 0
05-27 17:15:31.627 411-411/com.pethoalpar.myapplication D/ViewRootImpl@bd62c20[MainActivity]: ViewPostIme pointer 1
05-27 17:15:31.632 411-411/com.pethoalpar.myapplication E/MainActivity: file:///storage/emulated/0/Tess/imgs/ocr.jpg exposed beyond app through ClipData.Item.getUri()


text:
Q: why this code is not loading pages ajax jquery Guys What I am trying to do is load a page on navigation click with ajax and put some delay in it loading
when nothing is clicked I want load home page following loading animation with jquery and a delay with PHP code
and if something on nav is clicked I want to load that particular file
but this code don't seem to be working
var res = {
    loader: $('<div />', {class: 'loader' } ),
    container: $('.content')
};

$(document).ready(function(){
            $.ajax({
                url: 'templates/delay.php',
                beforeSend, function(){
                    res.container.append(res.loader);
                },
                success, function(){
                    res.container.find(res.loader).remove();
                    $('.content').load('templates/pages/home.php');
                }
            });
            $('ul#nav_a li a').click(function(){
                $.ajax({
                url: 'templates/delay.php',
                beforeSend, function(){
                    res.container.append(res.loader);
                },
                success, function(){
                    res.container.find(res.loader).remove();
                    var page=$(this).attr('href');
                    $('.content').load('templates/pages/'+page+'.php');
                        return false;
                    });
            });
                }
            });

A: I will not discuss the code itself, but just improve it.
Try this code and tell me if you get what you want : ( comments inside the js code )
$(document).ready(function(){
    $.ajax({
        url: 'templates/delay.php',
        // old code : beforeSend,
        beforeSend: function(){
            res.container.append(res.loader);
        },
        // old code : success,
        success: function(){
            res.container.find(res.loader).remove();
            $('.content').load('templates/pages/home.php');
        }
        // beforeSend and success are keys with functions as values that's why we use ":" and not ","
        // the "," comma is used to separate ajax settings
    });
    $('ul#nav_a li a').click(function(){
        var page = $(this).attr('href');
        $.ajax({
            url: 'templates/delay.php',
            // old code : beforeSend,
            beforeSend: function(){
                res.container.append(res.loader);
            },
            // old code : success,
            success: function(){
                res.container.find(res.loader).remove();
                $('.content').load('templates/pages/'+page+'.php');
            // old code
            //  return false;
            //  });

            // we close our ajax.success function
            }
        })
        // old code
        // }

        // return false is used to prevent browser to run the a href that's why we use it in the a.click function and not inside the ajax block
        return false;
    })
})

A: var res = {
    loader: $('<div />', {class: 'loader' } ),
    container: $('.content')
};
$(document).ready(function(){
        res.container.append(res.loader);
        $('.content').load( "templates/pages/home.php", function() {
             res.container.find(res.loader).remove();
        });
        $('ul#nav_a li a').click(function(){
            var page=$(this).attr('href');
            $('.content').load( 'templates/pages/'+page+'.php', function() {
                res.container.find(res.loader).remove();
             });
        });
     }
 });

Just copy and paste it.


text:
Q: Can Javascript prompt() be answered via script? Basically, I need a sanity check.
Assuming this code:
prompt("Yes or no?")
The user must click an answer here.   There isn't a way in Javascript to "answer" the question for the user...  correct?    Everything I know screams impossible...  but wanted to triple check here first.

A: Nope.
prompt() immediately puts up a modal dialog box, and blocks all further script execution until a value is entered. There is no opportunity to intercept or handle at any point, because no code is allowed to run while it's up.
Perhaps you want a different way to put up a dialog box that's less intrusive like jQuery UI Dialog's

Wait, so you seem more concerned that it could be tampered with and you don't want it to be?
If so, my answer stands as true but there are other ways to get around it. For instance, you can override the prompt() function before it runs to do whatever you want. This snippet would prevent any prompt from appearing and hardcode a specific return value.
window.prompt = function() { return 'spoofed' };
var name = prompt("What's your name?"); // no prompt appears
console.log(name); //=> 'spoofed'

Without knowing what you are trying to accomplish, it's hard to advise how to do it instead. But if you want a prompt that will answer the question "are you a human?", it won't be reliable as it's easily bypassed.

A: You are correct, the entire program waits for the user to respond, so code that could programatically 'answer' the prompt wouldn't run anyway.

A: No, you can't answer prompt() from JS code.

A: In general (unmodified desktop browsers only), I guess not (see other answers). However, if you were looking at other applications of JavaScript alerts, this may be possible. For instance, with the Android SDK, you would use the onJsAlert method from WebChromeClient:
public boolean onJsAlert(WebView view, String url, String message,
    final android.webkit.JsResult result) {
        builder.setTitle(ActivityTitle)
            .setMessage(message)
            .setPositiveButton("OK",
                new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                        int which) {
                        result.confirm();
                    }
                }).setCancelable(false).create().show();
    return true;
}

It may be worthwhile to inspect the source code to see how this is accomplished. This may have hooks into the browser, but if you really want to get into it, this may be interesting.
Alternatively
If you need to be able to have a sort of alert-style box which can be controlled using JavaScript, then it should also conform to ARIA specifications, as mentioned in the MDN on the alert role. Doing this would allow similar functionality, allow the alert to be styled, and would also be usable by people with accessibility devices.
One down side I can see to using this is that it wouldn't hook into something like what's talked about above. If an Android developer has chosen to override the alerts, then I don't think it would work as expected.


text:
Q: Group Multiple Objects Based on Type Using lodash I want to group unordered-list-item and ordered-list-item.
Below is the original structure:
{
  data: {
    areas: [{
      sections: [{
        rjf: [
          {
            type: "unordered-list-item",
            text: "Item 1",
          },
          {
            type: "unordered-list-item",
            text: "Item 2",
          },
          {
            type: "paragraph",
            text: "This is text",
          }]
      }]
    }]
  }
}

Now I want to group all list items into a new object.
So the expected structure is:
{
  data: {
    areas: [{
      sections: [{
        rjf: [
          {
            type: "list",
            items: [{
              type: "unordered-list-item",
              text: "Item 1",
            },
            {
              type: "unordered-list-item",
              text: "Item 2",
            }]
          },
          {
            type: "paragraph",
            text: "This is text",
          }]
      }]
    }]
  }
}

So I wanted to move all the unordered-list-item and ordered-list-item to items array and the following object type like paragraph shouldn't be impacted.
I created a solution in TypeScript, but the code was too long:
const areas = data.areas;
      const listItemTypes = ['unordered-list-item', 'ordered-list-item'];
      return areas.map(area => {
        return area.sections.map(section => {
          let lastHeadingIndex = -1;
          return section.rjf.reduce((acc, current, index) => {
            if (!current.type || !listItemTypes.includes(current.type)) {
              lastHeadingIndex = acc.length;
              return [...acc, current];
            }
            let listObject = acc.find((el, i) => i > lastHeadingIndex && i < index && el.type === 'list');
            if (!listObject) {
              listObject = {
                type: 'list',
                items: [current]
              };
              return [...acc, listObject];
            }
            listObject.items = [...listObject.items, current];
            return acc;
          }, []);
        });
      });

How can I achieve the same functionality using lodash?
****UPDATE****
I tried with lodash, but dosen't seems to work.

var content = {
  data: {
    areas: [{
      sections: [{
        rjf: [{
            type: "unordered-list-item",
            text: "Item 1",
          },
          {
            type: "unordered-list-item",
            text: "Item 2",
          },
          {
            type: "paragraph",
            text: "This is text",
          }
        ]
      }]
    }]
  }
};

var result = content.data.areas.map((area => {
    return area.sections.map(section => {
       section.rfj = _.groupBy(section.rfj, 'type');
    });
}));

document.body.innerHTML = '<pre>' + JSON.stringify(result, null, '  ') + '</pre>';
<script src="https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js"></script>

A: return data.areas.map((area => {
    return area.sections.map(section => {
       return section.rfj = _.groupBy(section.rfj, 'type')
    })
})

You may need some more little tweaking on the result if you need a more specific structure, but this should do most of the work

A: You could simplify your code to something like this.

*

*Use nested map on areas and sections.

*You are returrning the arrays from both map. Return objects with sections and rjf property instead (Assuming both structures are objects with just one property)

*When looping through rjf, create 2 arrays: items and others

*Group each object to these 2 arrays based on whether types array includes the current object's type.

*Create an array with one list object ({ type: "list", items }) and remaining objects from others array

const types = ['unordered-list-item', 'ordered-list-item'],
      input = {data:{areas:[{sections:[{rjf:[{type:"unordered-list-item",text:"Item 1",},{type:"unordered-list-item",text:"Item 2",},{type:"paragraph",text:"This is text",}]}]}]}}

const areas = input.data.areas.map(a => {
  return {
    sections: a.sections.map(s => {
      const items = [], others = [];

      s.rjf.forEach(o =>
        types.includes(o.type) ? items.push(o) : others.push(o)
      )

      return { rjf: [{ type: "list", items }, ...others] }
    })
  }
})

console.log({ data: { areas } })
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You could use another approach by copying each object leven and map all arrays and group the last level by using a function for grouping.
This approach uses am iter function which gets all functions for each level and the starting object.
At the end, it returns a new object with the given structure and the grouped items.

function copy(source, fn) {
    return Object.assign({}, ...Object
        .entries(source)
        .map(([k, v]) => ({ [k]: fn(v) }))
    );
}

function map(array, fn) {
    return array.map(fn);
}

function group(array) {
    var items;
    return array.reduce((r, o) => {
        if (listItemTypes.includes(o.type)) {
            if (!items) {
                items = [];
                r.push({ type: 'list', items });
            }
            items.push(o);
        } else {
            items = undefined;
            r.push(o);
        }
        return r;
    }, []);
}

function iter([fn, ...fns], object) {
    return fn ? fn(object, iter.bind(null, fns)) : object;
}

var object = { data: { areas: [{ sections: [{ rjf: [{ type: "unordered-list-item", text: "Item 1" }, { type: "unordered-list-item", text: "Item 2" }, { type: "paragraph", text: "This is text" }] }] }] } },
    listItemTypes = ['unordered-list-item', 'ordered-list-item'],
    result = iter([copy, copy, map, copy, map, copy, group], object);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: JSP file doesn't run in browser with Netbeans 9.0
When I click "Run File", it doesn't run and it's not showing any status bar at the bottom.
The same thing for the HTML file. The file .java and other things are running normally. I'm using Netbeans 9.0.
When I was working with Netbeans 8.0.2, the problem didn't happen.


text:
Q: how to populate async call from inside another I have a script that makes multiple API calls, and the result of one call effects the others.
async function getPlugin(id){
  const fetchCardPlugin = `https://*********..amazonaws.com/*****/cardPlugin?id=${id}`
  const cp = await fetch(fetchCardPlugin)
  let pluginData = await cp.text();
  pluginData = JSON.parse(pluginData);
  if (typeof pluginData[0] != undefined){
    return pluginData[0]['value'].split(':').pop().split('')[0]
  }
  else {
    return ''
  }
}

elm.addEventListener('click',()=>{
    return t.get('board','shared','bid')
        .then(data=>{
            (async function(){
        const sheetId = data;
        const cardList = [];
        const mm = {};

        const fetchCardData = `https://*******.execute-api.******.amazonaws.com/******/cardData?id=${boardId}`

        const cd = await fetch(fetchCardData)
        let cardData = await cd.text();

        cardData = JSON.parse(cardData);

        await cardData.map(x=>{
          const cardDict = {};
          // console.log(getPlugin(x.shortLink));
          cardDict['points'] = getPlugin(x.shortLink);
          cardDict['id'] = x.id;
          cardDict['title'] = x.name;

        })

My first call goes to my fetchCardData.  I then use the data from this return to both create an object, and make another call.
await cardData.map(x=>{
          const cardDict = {};
          // console.log(getPlugin(x.shortLink));
cardDict['points'] = getPlugin(x.shortLink);
          cardDict['id'] = x.id;

My big sticking point is that, I need to use data from the second call to populate the object.  Currently when I do this I am getting a Promise for the objects point value.
comments:0
description:""
id:"6354b75ddared4ba013aa06440"
labels:""
last activity:"Sat Oct 22 2022"
list:"To Do"
members:""
points:Promise
[[Prototype]]:Promise
[[PromiseState]]:"fulfilled"
[[PromiseResult]]:"5"
title:"test"
url:"https://trello.com/c/*******/**"

What I would like is this:
comments:0
description:""
id:"6354b75ddared4ba013aa06440"
labels:""
last activity:"Sat Oct 22 2022"
list:"To Do"
members:""
points:5
title:"test"
url:"https://trello.com/c/*******/**"

A: const cardListPromises = cardData.map(async (x) => {
  const cardDict = {};
  cardDict['points'] = await getPlugin(x.shortLink);
  cardDict['id'] = x.id;
  cardDict['title'] = x.name;

  return cardDict;
})

const cardList = await Promise.all(cardListPromises);

console.log(cardList) // this is the final result you need.


text:
Q: Toggle display the child div once the parent div is validated Straight to the point: I have a parent and a child and they are connected through the onclick=showMe("",this) line. The problem here, is if the parent is validated, it will check the checkbox, but it won't show the corresponding child. Here is an excerp:
    {

    <?php
    //Getting the Category ids
    $ids=$detail['details_category_ids'];

    //Trying to explode into integers
    $cat_array = array_map('intval', explode(' | ',$ids));

    foreach($cat_val as $ids=>$ids_value){
    $cat_array2[$ids_value]=$cat_array[$ids];
    }

    ?>

    Parent1

    <input name="category[]" type="checkbox" id="chb1" value="1" <?php echo ($cat_array2[1]=='1')                 ? 'checked' :''; ?> onclick="showMe('level_2', this)"> Level 1

    Child1

    <input name="category[]" type="checkbox" id="idCheckbox1" value="9" <?php echo         ($cat_array2[1]=='1') ? 'checked' :''; ?> onclick="showMe('pb-counter', this)">Counter

    }

And here is the jQuery file that I was testing out:
    $(document).ready(
    (function(){
    if('input[type=checkbox]:checked').length{
    $('.child_id',this).toggle();
    }
    });

-> Basicly, I want the child to show when the parent is validated. Without clicking the checkbox. And if there is a better way to do it, I'm all ears.

A: Set up .change() listener and validate your form as soon as something gets changed.
When certain requirements are met, show the rest of the form.