text:
Q: How to install rails mac OSX Mountain Lion?
Possible Duplicate:
OS X Mountain Lion: gcc-4.2 No such file or directory

I'm facing a problem to install rails on my MAC.
I'm learning RoR by myself but I can't install rails.
This is what I did:
1 - Installed XCode and downloaded 'Command Line Tools'
2 - Installed RVM with this code:
curl -L https://get.rvm.io | bash -s stable

3 - Installed HomeBrew and libksba:
ruby <(curl -fsSkL raw.github.com/mxcl/homebrew/go)

brew install libksba

4 - Installed Ruby with RVM (RVM command only worked after I restarted the system):
rvm install 1.9.3

5 - Defined Ruby 1.9.3 as default:
rvm --default 1.9.3

6 - Now I'm trying to run this code:
gem install rails

But it returns this error:

Guerreiro:~ rguerreiro$ gem install rails
  Building native extensions.  This could take a while...
  ERROR:  Error installing rails:
      ERROR: Failed to build gem native extension.
   /Users/rguerreiro/.rvm/rubies/ruby-1.9.3-p194/bin/ruby extconf.rb

creating Makefile
make
  compiling generator.c
  make: /usr/bin/gcc-4.2: No such file or directory
  make: *** [generator.o] Error 1
Gem files will remain installed in /Users/rguerreiro/.rvm/gems/ruby-1.9.3-p194/gems/json-1.7.5 for inspection.
  Results logged to /Users/rguerreiro/.rvm/gems/ruby-1.9.3-p194/gems/json-1.7.5/ext/json/ext/generator/gem_make.out

A: RVM supports multiple rubies of different versions and hence is preferred for RoR development.
checkout the installation steps at https://rvm.io/rvm/install/

A: did you read rvm requirements? it will tell you how to get osx-gcc-installer - install it and it should move to next step.


text:
Q: scapy kamene sending SYN packet I tried sending a TCP SYN packet from a remote IP address to my local IP address using the following  code.
from kamene.all import *
print("Send SYN from remote to local")
ip=IP(src=remote_ip,dst=local_ip,frag=0,tos=0x0)
tcp=TCP(sport=remote_port,dport=local_port, flags="S", seq=1111)
SYN_pkt = ip/tcp
SYNACK_pkt = srp(SYN_pkt,verbose=0)
ls(SYNACK_pkt)

But the code is giving the following error.
Send SYN from remote to local
WARNING: DNS RR prematured end (ofs=16116, len=26)
WARNING:kamene.runtime:DNS RR prematured end (ofs=16116, len=26)
WARNING: wrong value: DNS.ancount=51411
WARNING:kamene.runtime:wrong value: DNS.ancount=51411
WARNING: wrong value: DNS.nscount=41893
WARNING:kamene.runtime:wrong value: DNS.nscount=41893
WARNING: more wrong value: DNS.arcount=778
WARNING:kamene.runtime:more wrong value: DNS.arcount=778
Not a packet class. Type 'ls()' to list packet classes.

If I change the srp() to sr1() to send/receive packet, it is giving the below error.
Send SYN from remote to local
WARNING: Mac address to reach destination not found. Using broadcast.
WARNING:kamene.runtime:Mac address to reach destination not found. Using broadcast.
WARNING: DNS RR prematured end (ofs=16116, len=26)
WARNING:kamene.runtime:DNS RR prematured end(ofs=16116, len=26)
WARNING: wrong value: DNS.ancount=51411
WARNING:kamene.runtime:wrong value: DNS.ancount=51411
WARNING: wrong value: DNS.nscount=41893
WARNING:kamene.runtime:wrong value: DNS.nscount=41893
WARNING: more wrong value: DNS.arcount=778
WARNING:kamene.runtime:more wrong value: DNS.arcount=778

A: DNS RR prematured was a DNS bug Scapy had.
It was fixed ages ago, but because you are using kamene instead of Scapy, you still encounter it.
Switch to Scapy.
See https://stackoverflow.com/a/54578802/5459467

redpajama_set_name: RedPajamaStackExchange


text:
Q: Maven - Non-resolvable parent POM I'm trying to build with Maven from Eclipse and it does not work even though it does when I run it from command line. In Eclipse I'm using the same settings.xml, the same Maven and the same JRE.
The log is the following:
[INFO] Scanning for projects...
[INFO] Downloading from central: https://repo.maven.apache.org/maven2/()
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[WARNING] 'version' contains an expression but should be a constant. @ line 8, column 11
[FATAL] Non-resolvable parent POM for (project name): Could not find artifact (artifact name):pom:1.0.3 in central (https://repo.maven.apache.org/maven2) and 'parent.relativePath' points at wrong local POM @ line 18, column 10
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project (project name):${project.version} (My pom.xml's full path) has 1 error
[ERROR]     Non-resolvable parent POM for (project name):${project.version}: Could not find artifact (artifact name):pom:1.0.3 in central (https://repo.maven.apache.org/maven2) and 'parent.relativePath' points at wrong local POM @ line 18, column 10 -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException

It is missing the project's pom.xml's parent pom which is stored in an artifactory. I have access to the artifactory.

*

*The artifactory is declared in the .m2/settings.xml

*I can find it in the .m2/repository directory

*I'm using JRE 1.8

*I'm using Maven 3.6.0
Cleaning the project and updating Maven does not work.

A: The problem is with the settings.xml. In Eclipse Maven uses two settings: global and local settings which can be set at

Preferences -> Maven -> User Settings

The Global Settings should be where Maven is intalled /conf/settings.xml and the User Settings should be the user directory /.m2/settings.xml


text:
Q: Sync extension PHP - shm_open() is not available on this platform I have a problem when I try to install the Sync extension of PHP with the command pecl install sync on my mac.
Here is the error I get from the command :
checking for shm_open in -pthread -lrt... configure: error: shm_open() is not available on this platform
ERROR: `/private/tmp/pear/temp/sync/configure --with-php-config=/usr/local/opt/php/bin/php-config' failed

I have MacOS Catalina 10.15.6.
I really can't find a solution to this problem on the internet. Has anyone ever had this problem and been able to solve it?
Thanks in advance


text:
Q: Swift: Countdown from current time till a certain time I'm trying to calculate the time from now (i.e. Date()) till the next 5pm.
If the current time is 3pm, the output will be 02:00:00. (in HH:MM:SS)
If the current time is 6pm, the output will be 23:00:00. (until the next 5pm!)
How do I do that in Swift 3?
Thanks.

A: You can use Calendar.nextDate to find the Date of the coming 5pm.
let now = Date()
let calendar = Calendar.current
let components = DateComponents(calendar: calendar, hour: 17)  // <- 17:00 = 5pm
let next5pm = calendar.nextDate(after: now, matching: components, matchingPolicy: .nextTime)!

then, just compute the different between next5pm and now using dateComponents(_:from:to:).
let diff = calendar.dateComponents([.hour, .minute, .second], from: now, to: next5pm)
print(diff)
// Example outputs:
//  hour: 2 minute: 21 second: 39 isLeapMonth: false
//  hour: 23 minute: 20 second: 10 isLeapMonth: false

A: func tommorrow5() ->Date {
var todayAt5 = Calendar.current.dateComponents([.year,.month,.day,.hour], from: Date() )
todayAt5.hour = 17
let dateToDisplay = Calendar.current.date(from: todayAt5)
return Calendar.current.date(byAdding: .day , value: 1, to: dateToDisplay!)! }

func showTimeDifference()->DateComponents{
var todayAt5 = Calendar.current.dateComponents([.year,.month,.day,.hour], from: Date() )
todayAt5.hour = 17
let dateToDisplay = Calendar.current.date(from: todayAt5)
let now = Date()
switch now.compare(dateToDisplay!) {

case .orderedAscending : // now is earlier than 5pm

    return Calendar.current.dateComponents([Calendar.Component.hour, Calendar.Component.minute, Calendar.Component.second], from: Date(), to: dateToDisplay!)

case .orderedDescending : // now is later than 5 pm

    return Calendar.current.dateComponents([Calendar.Component.hour, Calendar.Component.minute, Calendar.Component.second], from: Date(), to: tommorrow5())
case .orderedSame : break // now is 5 pm
}

return Calendar.current.dateComponents([Calendar.Component.hour, Calendar.Component.minute, Calendar.Component.second], from: Date(), to: dateToDisplay!)

}
you can use it just like this
it will return time to 5pm today
if its already passed 5pm will return time to 5pm tomorrow
showTimeDifference()


text:
Q: How to use variable in shell command in jenkinsfile I've following code from Jenkinsfile, however the pipeline fails because the shell command remains incomplete as the variable can't be imported into the shell command.
environment{
        S3_URL = "S3://samplebucket/code.zip"
}

steps
{
   script
   {
      withAWS(role: "${AWS_ARN}", externalId: "${EXT_ID}", region: "${AWS_REGION}"){
         sh '''
         export PATH="$PATH:/root/.dotnet/tools"
         cd code
         dotnet lambda deploy-function
         cd bin/Release/net6.0
         aws s3 cp code.zip '''${S3_URL}''' //<----- Here is the problem
         '''
   }
}

I've tried multiple ways to fetch the variable S3_URL in the sh ''' ... ''' block but it always turn out to be blank, consequently an error.

A: The environment value should be in "" like this S3_URL = "S3://samplebucket/code.zip"
I just tried the way you are trying
pipeline {
    agent any
    environment{
      S3_URL = "S3://samplebucket/code.zip"
    }
    stages {
        stage("Test"){
            steps {
                script {
                    sh '''
                    echo ${S3_URL}
                    '''
                }
            }
        }
    }
}

Just remove the '''''' around the '''${S3_URL}''' and use only ${S3_URL} it should be like this
aws s3 cp code.zip ${S3_URL}


text:
Q: Why is Spring R2DBC Kotlin JPA adding dash and random characters when trying to map my data class fields? This is for postgresql r2dbc coroutines etc.
I've got an Entity that looks like this:

@Table("entity_type")
data class EntityType(
    @Id var id: UUID? = null,
    val entityTypeName: Name, // A string value class
    val systemSchemaVersion: SchemaVersion,
)

And a table that looks like this:

    CREATE TABLE IF NOT EXISTS entity_type (
    id                      uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
    entity_type_name                    character varying NOT NULL,
    system_schema_version   character varying NOT NULL,

and accompanying interface:
interface EntityTypeRepository : CoroutineCrudRepository<EntityType, EntityTypeIdType> {
    override suspend fun <S: EntityType> save(entity: S): EntityType
    suspend fun findByEntityTypeName(entityTypeName: Name): EntityType?

I get this:
    No property 'entityTypeName-9XaHgsA' found for type 'EntityType';

Why on EARTH is it appending "9XaHgsA" to the field/column name? It does this appended field stuff across ALL columns except the ID column.
Note that i'm using value classes, but that doesn't seem to cause a problem - they're automatically getting translated to strings as expected.
Related bug ticket:
https://github.com/spring-projects/spring-data-r2dbc/issues/803


text:
Q: Java - Better way then using Ifs and repeating functions - DateRelated I created a function to check my Date string for what month it contains so I can use it for multiple date formats. But I'm using a lot of ifs and repeating the .contains function. Is there a better way of doing this?
Also related my dates are in the format Weekday(String), Month(String) day(int- XX), Year(Int - XXXX). e.g. Sunday, June 27, 1965. I've had no luck so far with the built in functions.
    public static int CheckMonth(String s){
    String month = s.toLowerCase();

    if(month.contains("january")){return 1;}
    else if(month.contains("febuary")){return 2;}
    else if(month.contains("march")){return 3;}
    else if(month.contains("april")){return 4;}
    else if(month.contains("may")){return 5;}
    else if(month.contains("june")){return 6;}
    else if(month.contains("july")){return 7;}
    else if(month.contains("august")){return 8;}
    else if(month.contains("september")){return 9;}
    else if(month.contains("october")){return 10;}
    else if(month.contains("november")){return 11;}
    else if(month.contains("december")){return 12;}
    else {return -1;}
}

A: You could use a loop. For example,
// 'lookup'
static String[] monthNames = {"january", .., "december"};

// in method
for (var i = 0; i < months.length; i++) {
   if (monthName.contains(monthNames[i])) {
      return i + 1; // because 0..11 indices in array
   }
}
// do something if no matching month was found

Although if trying to "NLP" a date, I'm sure there are existing libraries ..

A: For what you want to do, using an enum to store the text and the number could be used. For example:
public enum Month {
    JANUARY("january", 1), FEBRUARY("february", 2) ... DECEMBER("december", 12);

    private final String string;
    private final int number;

    private Month(String string, int number) {
        this.string = string;
        this.number = number;
    }

    public int getMonthNumber(String string) {
        for(Month month : Month.values()) {
            if(string.contains(this.string))
                return month.number
        }
        return -1;
    }

}


text:
Q: How to set input type date's default value to today?using ASP net core 7.0 <input type="date"  id="ngaydk" value="01/02/2023">

<input type="date"  id="ngaydk" value="01/02/2023">

or
ViewData["greeting2"] = "01/01/2023";
<input type="date" class="form-control" id="ngaydk" value=@ViewData["greeting2"]>

resual :

I want show value "01/02/2023" at load page but
not show value "01/02/2023" helpme!

A: Format for a date value is YYYY-MM-DD

<input type="date" value="2023-02-01">

A: I have an asp.net core web application and this is what I have in my index.cshtml

    date:
    <input type="date" id="ngaydk"   />
    <input type="date" id="ngaydk2"   />
    <input type="date" id="mydate"   />
    @Html.TextBox("date1", DateTime.Now.ToString("yyyy-MM-dd"), new { type = "date" })

@section Scripts{

}


text:
Q: Splash screen with version In MAUI I am trying to make a splash screen in .Net MAUI that contains app version. I have looked for many examples but none of them shows how to customize splash screen with version or text. Is it possible in .Net MAUI. If there is an example or a way to add app verion with logo in .Net MAUI please let me know.

A: Yes,you can create a ContentPage that acts as a Splash screen ,just as FreakyAli said.
There is a sample code, you can refer to it.
MySplashScreen.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamSample.MySplashScreen"
                          BackgroundColor="#000">

    <StackLayout HorizontalOptions="Center" VerticalOptions="Center" Padding="10">
        <Image Source="test.png" x:Name="imgLogo" HeightRequest="100" WidthRequest="100"
               Margin="5"/>
        <Label Text="WHATSAPP" FontSize="Large" TextColor="#f7f7f7" Margin="5"/>
    </StackLayout>
</ContentPage>

MySplashScreen.xaml.cs
    public partial class MySplashScreen : ContentPage
      {
            public MySplashScreen ()
            {
                  InitializeComponent ();
            NavigationPage.SetHasNavigationBar(this, false);
            LogoAnimation();
        }

        public async Task LogoAnimation()
        {
            imgLogo.Opacity = 0;
            await imgLogo.FadeTo(1, 3000);
            Application.Current.MainPage = new NavigationPage(new MainPage());
        }
    }

App.xaml.cs
public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        MainPage = new DarkScreen();
    }
}

Note:
1.Here, I used FadeTo function to simulate the time delay. Of course, you can also use a Timer to acheve this.
2.You can add a Label to display the version name to page MySplashScreen  as needed.


text:
Q: Javascript: toString function for custom exception not displaying expected output This page outlines how to create custom exceptions in Javascript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw.
However, the custom exception isn't printing the expected output. The desired output only occurs when invoking console.log(e.toString()) but the goal is to see the desired output with console.log(e).
Desired output with console.log(e):
500: Unexpected error

Actual output with console.log(e):
{
  statusCode: 500,
  statusMessage: "Unexpected error",
  toString: function () {
        return this.statusCode + ': ' + this.statusMessage;
    }
}

Code
function TestException(statusCode, statusMessage) {
    this.statusCode = statusCode;
    this.statusMessage = statusMessage;
    this.toString = function() {
        return this.statusCode + ': ' + this.statusMessage;
    };
}

try {
    throw new TestException(500, 'Unexpected error');
} catch (e) {
    console.log(e);
}

A: you must have an exception that help you:
const TestException = (statusCode, statusMessage) => {
    this.statusCode = statusCode;
    this.statusMessage = statusMessage;
    this.toString = () => {
        return this.statusCode + ': ' + this.statusMessage;
    }

    if(!isNaN(this.statusCode) || this.statusMessage !== null) {
        throw this.toString();
    }
}

try {
    throw TestException("500", 'Unexpected error');
} catch (e) {
    console.log(e);
}


text:
Q: NSDateFormatter only works on simulator? i simple try to reformat a date:
 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
 NSDate *date = [[NSData alloc] init];
 //Mon, 05 Apr 2010 14:27:48 -0700
 [formatter setDateFormat:@"E, dd MMM yyyy HH:mm:ss Z"];
 date = [formatter dateFromString:self.currentItemValue];

 [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
 self.currentItem.pubDate = [formatter stringFromDate:date];
 [formatter release];

It works on the simulator, but on the device i only get (null).
Thanks for your help!
Some more tests:
NSString *string = @"Fri, 12 Dec 2008 18:45:15 -0800";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"];
NSDate *date = [dateFormatter dateFromString:string];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
//here i got (null) on the device but it works on simulator...
NSLog(@"date %@", [dateFormatter stringFromDate:date]);

A: DyingCactus was right!
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"] autorelease]];

solves my issue.... Thanks!!!!


text:
Q: manage several connections with the same traffic light - SUMO I'm new to SUMO, so my question/problem could be trivial, maybe I didn't search enough.
This is my problem :
I have a network that I edited through Netedit and I want to implement a certain traffic light (TL) phase in an intersection
On an edge, there is two lane : bus lane and car lane. There are 3 possible directions (straight for the buses, straight and right for the cars) so Netedit creates (as I understand) 3 different TL. However, the TL phase(or sequence, it depends on how you name it) is the same. It means that, in reality, the two TL in this road give the same information of green and red, no difference between buses and cars.
Since the TL phase is given to me, I need the same amount of TL in the simulation and in the reality in order to implement it almost as a "copy - paste".
So I have a couple of questions :
-is it possible to join several TL as one in order to manage several connections/directions with the same TL ?
The idea behind this is : is it possible to differentiate connections/direction from TL in netedit ?
-What could be another approach to deal with my problem ?
This the edge with the TL index, it could be useful to understand each other.
Thank you for your answers !

A: I think the concept you are refering to is called signal groups in SUMO. You can open up netedit and group the connections you would like to join into a group by choosing "group signals".


text:
Q: PHP mail() goes to junk, possible DNS issue? I am sending a message via PHP's mail() with proper and complete headers. It has everything it is supposed to, and Hotmail likes the email itself.
However, Hotmail is showing this in the source of the message:
X-DKIM-Result: None
X-Message-Status: n:0:n
X-SID-Result: None
X-AUTH-Result: NONE

I tried to get them to Pass but only managed to turn the SID and AUTH to "Fail" causing SmartScreen to see the message as suspicious and delete it after ten days, whereas before it just seemed like spam to the filters.
If I am able to get these to Pass, then the email will not be marked as junk. I know there's something I need to do in DNS. I have Reverse DNS set up on the website.
The email includes boundaries, MIME version, content type, reply-to and return-path, x-mailer etc. The content type is multipart/alternative (for the boundaries) and the subject nor body does not contain any spammy keywords.
Anyone know how to get these things to Pass via PHP or DNS?
Bottom line: If these results are "None" then it will just go to Junk peacefully. If they are "Fail" then it will be "suspicious" and automatically deleted. If they are "Pass" then it will go straight to inbox without a problem, but I don't know how to get them to Pass.
If it helps in any way, I am running Exim 4.77 on a cPanel/WHM (Linux) VPS. My IP address is clean and hasn't been abused in the past. It isn't blocked at any blacklists.

A: Setup the SPF record in your DNS, can be a solution.
EDIT
Googling the message  X-AUTH-Result: FAIL  I found this post, that seem the same problem:
https://serverfault.com/questions/138886/emails-going-to-junk-for-hotmail-recipients

A: Make sure the server the mail is being sent from has a proper rDNS or PTR record back to it's hostname.


text:
Q: Como modificar un array de objeto para que este este en mayusculas Tengo el siguiente array que esta dentro de la siguiente variable totalRecords.issuerImages
Tarjeta: Array(1)
``0: {lastmodifiedts: '2021-10-19T00:00:00Z', createdby: 'DVILLEGAS', Status_id: 'SID_ACTIVE', modifiedby: 'DVILLEGAS', …}

Lo que me gutaria hacer que donde dice tarjeta Tarjeta este en mayusculas ya intente con .toUpperCase()


text:
Q: Errors in definitions in Flex and Lex I am writing a lexical analyser for a toy programming language with toy keywords. I wish to print "keyword" for every keyword the analyser bumps into. To make my code cleaner, I defined the term "keyword" for all keywords above the rule section.
%{
  #include <stdio.h>
%}
keyword program | begin | ... | end

where the ... implies rest of the keywords.
In the rules section, I wrote the following rule:
{keyword} {
   printf("keyword\n");
}

Then finally I wrote the main function and yywrap function.
However, when I compile the generated lex.yy.c file, I get the following error.
use of undeclared identifier 'keyword'
    {keyword} {
     ^

Please help me with this error, I am new to this scanner-generating language.

A: You will get better answers here if you copy and paste the precise text of your program into your question. Otherwise, you force anyone answering to guess what the original text is. This is my guess:
Probably the line that is being complained about was indented in your flex input file. Make sure that all rules start exactly at the left margin. (Any indented text is copied verbatim into the output file, as though it were C code. The most common use for this feature is to add comments to your Flex rules.)
Also, you cannot use unquoted spaces in a macro definition; you would need:
keyword  program|begin|...|end

Otherwise, flex will throw an error when it expands the macro. (It didn't expand the macro in this case, presumably because of the first problem.)


text:
Q: Word (French origin?) for first shot of war? I can't seem to find this word. It defines the opening fire of a battle.

A: One answer could be "opening volley", that has a French root according to OED.

A: So for opening salvo, according to the Oxford Dictionaries:

salvo
NOUN

*

*A simultaneous discharge of artillery or other guns in a battle.
'a deafening salvo of shots rang out'
'another salvo crashed nearer to the German positions'
1.1 A number of weapons released from one or more aircraft in quick succession.
1.2 A sudden, vigorous, or aggressive act or series of acts.
'the pardons provoked a salvo of accusations'
Origin
Late 16th century (earlier as salve): from French salve, Italian salva 'salutation'.

I didn't realize that it was from the French, to be honest, but there ya go.


text:
Q: Want to generate carousel with owl images in it I want a hidden div on owl carousel. Please Help me .
i am calling all css file from owl carousel .
Here is my calling css file
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/owl-carousel/owl.carousel.css">

/owl-carousel/owl.theme.css">
/owl-carousel/owl.transitions.css">
Here is my calling JS file

/owl-carousel/active.js">

and i get up
my HTML source file

A: Html Code Making use of slick.js
<!DOCTYPE html>

     <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.1/slick.min.css"/>

    <link rel="stylesheet" type="text/css" href="http://cdn.jsdelivr.net/jquery.slick/1.3.15/slick.css"/>

Test1

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut.

Test2

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut.

Test3

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut.

Test4

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut.

Test5

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut.

Javascript code
$(document).ready(function(){
     $('#slickslide').slick({
         dots: true,
         infinite: true,
         speed: 300,
         autoplay:true,
         autoplaySpeed: 1000,
         slidesToShow: 1,
         slidesToScroll: 1
     });
 });


text:
Q: Replace page based on screen size I'm trying to redirect pages based on the screen sizes, I have two different index files, one is for a mobile version of the web and the second one is for a web version.
on the web version index file I've included:
<script>
    if (screen.width <= 767) window.location.replace("./m/index.html")
        else window.location.replace("index.html")
</script>

and on the mobile index page I've included:
<script>
    if (screen.width >= 767) window.location.replace("../index.html")
        else window.location.replace("index.html")
</script>

The problem is two of these index pages keeps refreshing, the pages aren't loaded.
what seems to be the problem here, appreciate your help.

A: You can use the resize javascript event, as Tushar said.
window.addEventListener("resize", getTemplate);

CurrentPage = 'DesktopPage';

function getTemplate() {
    if (screen.width >= 767 && CurrentPage != 'DesktopPage') {
        return window.location.replace("desktop.html");
    }

    if (screen.width < 767 && CurrentPage != 'MobilePage') {
        return window.location.replace("mobile.html");
    }
}

getTemplate();

This will check your current page and the screen size, because there is no sense to redirect to the Desktop page if you already are in the Desktop page.

You also can add more versions, like a "SmallerMobilePage".
window.addEventListener("resize", getTemplate);

CurrentPage = 'SmallerMobilePage';

function getTemplate() {
    if (screen.width >= 767 && CurrentPage != 'DesktopPage') {
        return window.location.replace("desktop.html");
    }

    if (screen.width < 767 && CurrentPage != 'MobilePage') {
        return window.location.replace("mobile.html");
    }

    if (screen.width <= 480 && CurrentPage != 'SmallerMobilePage') {
        return window.location.replace("smaller_mobile.html");
    }
}

getTemplate();


text:
Q: Como ler arquivo properties para configurar JPA? Tenho um arquivo .properties para configurar o banco do meu projeto. Porém não consigo ler o arquivo.
Alguem dá uma força?
EntityManagerProducer
@ApplicationScoped
public class EntityManagerProducer {

private EntityManagerFactory factory;

public EntityManagerProducer() throws FileNotFoundException, IOException {
    Properties p = new Properties();

    p.load(new FileInputStream("./conexao.properties"));

    factory = Persistence.createEntityManagerFactory("AlmoxarifadoPU");
}

@Produces @RequestScoped
public EntityManager createEntityManager() {
    return factory.createEntityManager();
}

public void closeEntityManager(@Disposes EntityManager manager) {
    manager.close();
}

Arquivo properties
jdbc.user=root
jdbc.password=
jdbc.url=jdbc:mysql://localhost/almoxarifadome"
jdbc.driver=com.mysql.jdbc.Driver

A: Tente assim:
InputStream is = null;
Properties p = new Properties();

is = EntityManagerProducer.class.getClassLoader().getResourceAsStream('conexao.properties');
p.load(is);

Fonte:
https://www.mkyong.com/java/java-properties-file-examples/


text:
Q: Tkinter : Moving more than one object at once I am still fairly new to tkinter and I am trying to create a network simulator. I have made a simpler version of my program without all of the extra network stuff. I have been stuck on a problem for quite a while now. I can't work out how to make it so when I try and move one of the circles, it moves the text with it. I had an idea to delete the text when I click down so I can then move the object and recreate the text when I drop the object but I am not sure how to do this. Any other ideas are certainly welcome.
This is my library:
from Tkinter import *
import time

#Window class for making different windows

class Window:

#Constructor
def __init__(self, window, colour="black", width=600, height=400):
    #Set variables
    self.width = width
    self.height = height
    self.colour = colour

    #This dictionary is used to keep track of an item being dragged
    self._drag_data = {"x": 0, "y": 0, "item": None}

    #Create canvas
    self.canvas = Canvas(window, bg=self.colour, height=self.height, width=self.width)
    self.canvas.pack()

    #Add bindings for clicking, dragging and releasing over any object with the "circledrag" tag
    self.canvas.tag_bind("circledrag", "<ButtonPress-1>", self.OnCircleButtonPress)
    self.canvas.tag_bind("circledrag", "<ButtonRelease-1>", self.OnCircleButtonRelease)
    self.canvas.tag_bind("circledrag", "<B1-Motion>", self.OnCircleMotion)

#This is used to draw particle objects on the canvas, notice the tag that has been added as an attribute
def _create_circle(self, xcoord, ycoord, color):
    self.canvas.create_oval(xcoord-25, ycoord-25, xcoord+25, ycoord+25, outline=color, fill=color, tags = "circledrag")

#This is used to draw text on top of the object on the canvas
def _create_text(self, xcoord, ycoord, text):
    self.canvas.create_text(xcoord, ycoord, text = text, tags = ("circledrag", "text"))

#This uses the find_closest method to get store the x and y positions of the nearest item into the dictionary
def OnCircleButtonPress(self, event):
    #print self.canvas.find_withtag("Current")
    self.canvas.delete("text")

    '''Begin drag of an object'''
    # record the item and its location
    self._drag_data["item"] = self.canvas.find_closest(event.x, event.y)[0]
    self._drag_data["x"] = event.x
    self._drag_data["y"] = event.y

#This clears the dictionary once the mouse button has been released
def OnCircleButtonRelease(self, event):
    '''End drag of an object'''
    # reset the drag information
    self._drag_data["item"] = None
    self._drag_data["x"] = 0
    self._drag_data["y"] = 0

#This moves the item as it is being dragged around the screen
def OnCircleMotion(self, event):
    '''Handle dragging of an object'''
    # compute how much this object has moved
    delta_x = event.x - self._drag_data["x"]
    delta_y = event.y - self._drag_data["y"]
    # move the object the appropriate amount
    self.canvas.move(self._drag_data["item"], delta_x, delta_y)
    # record the new position
    self._drag_data["x"] = event.x
    self._drag_data["y"] = event.y

class DragCircle:
#Constructor
def __init__(self, window, width=100, height=100, colour="red", text = "test"):
    self.window = window
    self.circle = self.window._create_circle(width, height, colour)
    self.circle_text = self.window._create_text(width, height, text)

and this is the main program:
from Tkinter import *
import my_module2

#Make a window from my own class
window = Tk()
window.title("Drag & Drop")

#Create an instance of the window class
main_window = my_module2.Window(window)

#Create a circle object from the DragCircle class
circle = my_module2.DragCircle(main_window)
circle2 = my_module2.DragCircle(main_window, 200, 200, "green", "hello")

#Start the animation loop
window.mainloop()

I would like to know how to move two objects at once.

A: Each time you create a circle/text pair, create a unique tag and associate the tag with both the circle and the text. You can then use this unique tag to move both objects at once.
For example, modify your DragCircle constructor to look like this:
class DragCircle:
    #Constructor
    def __init__(self, window, width=100, height=100, colour="red", text = "test"):
        self.window = window
        tag = "circle-%d" % id(self)
        self.circle = self.window._create_circle(width, height, colour, tag)
        self.circle_text = self.window._create_text(width, height, text, tag)

Next, modify the _create_circle and _create_text functions to accept the tag:
def _create_circle(self, xcoord, ycoord, color, tag):
    id_=self.canvas.create_oval(xcoord-25, ycoord-25, xcoord+25, ycoord+25, outline=color, fill=color, tags = ("circledrag", tag))

#This is used to draw text on top of the object on the canvas
def _create_text(self, xcoord, ycoord, text, tag):
    self.canvas.create_text(xcoord, ycoord, text = text, tags = ("circledrag", "text", tag))

Finally, modify your OnCircleButtonPress to get the tag and use it for moving the objects around:
def OnCircleButtonPress(self, event):
    ...
    item = self.canvas.find_closest(event.x, event.y)[0]
    tags = self.canvas.gettags(item)
    for tag in tags:
        if tag.startswith("circle-"):
            break
    self._drag_data["item"] = tag
    ...

A: My proposal which may not be the best
In the constructor you define an association table.
self.assoc = {}

add the method:
def _create_circlewt(self, xcoord, ycoord, color, text):
      tc = self.canvas.create_oval(xcoord-25, ycoord-25, xcoord+25, ycoord+25, outline=color, fill=color, tags = "circledrag")
      tx = self.canvas.create_text(xcoord, ycoord, text = text)
      self.assoc[tc] = tx

in the OnCircleMotion: add the line
self.canvas.move(self.assoc[self._drag_data["item"]], delta_x, delta_y)

just after the other move line
in DragCircle class constructor
comment your definition and add the call to _create_circlewt
self.circle_w_text = self.window._create_circlewt(width, height, colour,text)

it works .. I let you enhance the canvas move to enable multiple objects association like
self.assoc[CircleIndex].append(otherobjectIndex)

A: There is a solution from How do I move multiple objects at once on a Tkinter canvas?
import tkinter as tk
import time

root = tk.Tk()

canvas = tk.Canvas(root)
canvas.pack()

canvas.create_oval(100, 105, 150, 150, tags="Bob", fill='light blue', outline='green')
canvas.create_oval(200, 205, 150, 150, tags="Bob", fill='light blue', outline='green')

for _ in range(50):
    canvas.move("Bob", 5, 0)
    canvas.update()
    time.sleep(0.05)

root.mainloop()


text:
Q: Do alternative expressions exist for subgroups of $G/N$, distinct from the correspondence theorem for groups? If $G$ is a group and $N$ is a normal subgroup, then any subgroup $J$ of $G/N$ can be expressed as $J=H/N$ for some subgroup $H$ of $G$ containing $N$ ($N \leq H \leq G$). For proof, see Subgroup of factor/quotient group $G/N$ is of form $H/N$ for $N \subseteq H$. Furthermore, there is a bijetion between subgroups of $G/N$ and subgroups of $G$ containing $N$.
What confuses me is this: might we be able to find a group $W$ not containing $N$ s.t. $W/N \leq G/N$? Of course, we still must have $W/N = H/N$ for some group $H$ satisfying $N \leq H \leq G$ by the correspondence theorem above.
In other words, for subgroup $H/N \leq G/N$, is it possible that $H / N = W/N$, where group $W \neq H$ does not contain $N$?

EDIT: a factor/quotient group $G/N$ is defined when $N$ is a normal subgroup of $G$. So if $N \nsubseteq W$, then $W/N$ does not make sense as a quotient group. The question should be rephrased in terms of sets: is it possible that $H/N=\{hN \mid h \in H \leq G\} = \{wN \mid w \in W \leq G \}$? For example, $nN=N=eN$, so $W$ need not include $n$ if it already contains $e$. Based on that last sentence, it is certainly possible to have $H/N = \{wN \mid w \in W \subseteq G\}$, but $W$ may not be a group.

A: You have fixed $G$, a normal subgroup $N$, and the map $f: G\to G/N$ such that $f(x)=xN$. So you're asking about the equality $f(W)=f(H)$ where $H$ is a subgroup containing $N$, and $W$ is possibly something other than $H$.
You've already noted that this is possible if $W$ is allowed to be a subset. But we can do it with a subgroup too. First maybe we should also assume that $N$ is a proper subgroup of $H$, since otherwise it's a little boring as we can take $W=\{e\}$. So let's assume this from now on.
Observation 1. If $f(W)=f(H)$ then $W\subseteq H$.
Proof. Fix $w\in W$. Then $wN=hN$ for some $h\in H$. So $h^{-1}w\in N$, which means it's in $H$. So $w\in H$.
Observation 2. If $W\subseteq H$ then $f(W)=f(H)$ if and only if $W\cap hN\neq\emptyset$ for all $h\in H$.
Proof. If $f(W)=f(H)$ then for any $h\in H$ there is $w\in W$ such that $wN=hN$ and so $w\in hN$. For the other direction, suppose $W\cap hN\neq\emptyset$ for all $h\in H$. $f(W)\subseteq f(H)$ is obvious. Given $h\in H$, choose $w\in W\cap hN$. Then $wN=hN$ so $f(h)\in f(W)$.
So now we see that to make a counterexample with a subgroup we just need a subgroup that hits all of the $H$-cosets of $N$ but doesn't contain everything in $N$.
Example 3. Probably the simplest example is in $G=\mathbb{Z}_{2}\times\mathbb{Z}_{2}$. Let $H=G$ and $N=\{(0,0),(1,0)\}$. Then take $W=\{(0,0),(0,1)\}$.
Observation 4. If $W\subseteq N$ then $f(W)=f(H)$ if and only if $H=WN$.
Proof. This is really just a different way to write Observation 2.
So we can get examples whenever we have subgroups $W$ and $N$ of $H$ such that $H=WN$ but $W$ does not contain $N$. This happens a lot in finite abelian groups since the whole structure theorem is based off of writing an abelian group $H$ as $H=WN$ where $W\cap N=\{e\}$. For example, if $H=\mathbb{Z}_{m}\times\mathbb{Z}_n$ then take $N=\mathbb{Z}_m\times\{0\}$ and $W=\{0\}\times\mathbb{Z}_n$.
Another example is $G=H=\mathbb{Z}$, $N=3\mathbb{Z}$ and $W=5\mathbb{Z}$. In general take $N=m\mathbb{Z}$ and $W=n\mathbb{Z}$, with $m,n>1$ and relatively prime.
So is it always possible for a given $G$, $H$, and $N$ to find a such a $W$? Well, no. One way to ruin it is by taking $H$ to have the property that its subgroups are linearly ordered by inclusion. In this case, if $W$ does not contain $N$ then $N$ contains $W$, so if $f(H)=f(W)$ then $H=WN=N$. Groups with this property include finite cyclic groups of prime power order and Prufer p-groups.

A: If $G$ is a group, $N$ is a normal subgroup of $G$, then you have two families of subgroups of $G$, and both are connected to subgroups of $G/N$ via the isomorphism theorems:

*

*The subgroups $H$ of $G$ with $N\subseteq H$. The Fourth/Lattice Isomorphism Theorem tells you that these subgroups are in one-to-one, inclusion preserving correspondence with the subgroups of $G/N$.

*The subgroups $H$ of $G$ that do not contain $N$. Here you use the Second Isomorphism Theorem: we know that restricting the map $G\to G/N$ to $H$ will give you a homomorphism with kernel $H\cap N$. And the Second Isomorphism Theorem tells you that its image, which is isomorphic to $H/(N\cap H)$ by the First Isomorphism Theorem, satisfies
$$\frac{H}{N\cap H} \cong \frac{HN}{N}.$$
Note that $HN$ is a subgroup of $G$ that contains $N$, and so is of the first kind.
So the isomorphism theorems tell you exactly what happens to every subgroup of $G$ under the map $G\longmapsto G/N$: those that $H$ contain $N$ are mapped to the subgroups $H/N$ of $G/N$ in the "natural way"; and those $H$ that do not contain $N$ are mapped to subgroups isomorphic their own quotients $H/(N\cap H)$, and to the same thing as $HN$, that is, to $HN/N$. And if you trace the proof of the Second Isomorphism Theorem, you will see that the map is again the "obvious one", $h\longmapsto hN$.


text:
Q: C# Working with delegates (the name does not exist in current context) I have the following code:
using System;
namespace Laboratory_work
{

    public delegate void Delegate ();
    public interface Method1
    {
        string InformationOutput (Person obj);
        int WorkOffer();
    }
    public interface Method2
    {
        int Invitation();
    }

    public abstract class Person: Method1
    {
        public string Name{get; set;}
        public string Surname{get; set;}
        public int Age{get; set;}
        public virtual string InformationOutput(Person obj)
        {
            string info="Some personal information \n_________________________\n\n"+
                "Full name — "+Name+" "+Surname+
                "\nAge — "+Age+" years\n";
            return info;
        }
        public int WorkOffer()
        {
            if (Age>=18)
            {
                Console.WriteLine("\nYou may be offered a job.");
                return 1;
            }
            else
            {
                Console.WriteLine("\nUnfortunately, there is no job for you.");
                return 0;
            }
        }
    }
    public class WhiteCollarWorker: Person, Method1
    {
        public string Occupation{get; set;}
        public bool ComputerAvailable{get; set;}
        public override string InformationOutput(Person obj)
        {
            return base.InformationOutput(obj)+"Occupation — "+Occupation+"\n"+
                "Computer — "+ComputerAvailable+"\n";
        }
        public int WorkOffer()
        {
            if (Age>=21 && Occupation!="\0")
            {
                Console.WriteLine("\nYou may be offered a job.");
                return 1;
            }
            else
            {
                Console.WriteLine("\nUnfortunately, there is no job for you.");
                return 0;
            }
        }
    }
    public class Laborer: Person, Method1
    {
        public string Occupation{get; set;}
        public bool InstrumentsAvailable{get; set;}
        public override string InformationOutput(Person obj)
        {
            return base.InformationOutput(obj)+"Occupation — "+Occupation+"\n"+
                "Instruments — "+InstrumentsAvailable+"\n";
        }
        public int WorkOffer()
        {
            if (Age>=18 && Occupation!="\0")
            {
                Console.WriteLine("\nYou may be offered a job.");
                return 1;
            }
            else
            {
                Console.WriteLine("\nUnfortunately, there is no job for you.");
                return 0;
            }
        }
    }
    public class Engineer: WhiteCollarWorker, Method1, Method2
    {
        public int YearExperience{get; set;}
        public bool BachelorDegree{get; set;}
        public bool MasterDegree{get; set;}
        public override string InformationOutput(Person obj)
        {
            return base.InformationOutput(obj)+"Experience — "+YearExperience+" year(s)\n"+
                "Bachelor Degree — "+BachelorDegree+"\n"+
                "Master Degree — "+MasterDegree+"\n";
        }
        public int WorkOffer()
        {
            if (Age>=25 && YearExperience>=1 && BachelorDegree==true)
            {
                Console.WriteLine("\nYou may be offered a job.");
                return 1;
            }
            else
            {
                Console.WriteLine("\nUnfortunately, there is no job for you.");
                return 0;
            }

        }
        public int Invitation()
        {
            if(WorkOffer()==1)
            {
                Console.WriteLine("Dear "+Name+" "+Surname+", soon you will receive\n"+
                                  "an email with date and time of your interview\n"+
                                  "at out company.Thank you for your CV.");
                return 1;
            }
            else
            {
                Console.WriteLine("Dear "+Name+" "+Surname+", unfortunately, you are\n"+
                                  "not suitable for this position. Than you for your CV.\n");
                return 0;
            }
        }
    }

    public class Builder: Laborer, Method1, Method2
    {
        public int YearExperience {get; set;}
        public bool Education {get; set;}
        public override string InformationOutput(Person obj)
        {
            return base.InformationOutput(obj)+"Experience — "+YearExperience+" year(s)\n"+
                "Education — "+Education+"\n";
        }
        public int WorkOffer()
        {
            if (Age>=18 && (YearExperience>=1 || Education==true))
            {
                Console.WriteLine("\nYou may be offered a job.");
                return 1;
            }
            else
            {
                Console.WriteLine("\nUnfortunately, there is no job for you.");
                return 0;
            }
        }
        public int Invitation()
        {
            if(WorkOffer()==1)
            {
                Console.WriteLine("Dear "+Name+" "+Surname+", soon you will receive\n"+
                                  "an email with date and time of your interview\n"+
                                  "at out company.Thank you for your CV.");
                return 1;
            }
            else
            {
                Console.WriteLine("Dear "+Name+" "+Surname+", unfortunately, you are\n"+
                                  "not suitable for this position. Than you for your CV.\n");
                return 0;
            }
        }

    }
    class Program
    {
    public static void Main()
    {
        Delegate Del_1=new Delegate(WorkOffer);
        Delegate Del_2=new Delegate(Invitation);
        Delegate TwoDels=new Delegate(Del_1+Del_2);

        const int N=10;
        int Count=0;

        var persons1=new Engineer[N];
        for (int i=0; i<10; i++)
        {
            persons1[i] = new Engineer();

            Console.WriteLine("\n\nENGINEERS\n________\n");
            Console.WriteLine("Input information of a person");
            Console.Write("Name: ");
            persons1[i].Name=Console.ReadLine();
            Console.Write("Surname: ");
            persons1[i].Surname=Console.ReadLine();
            Console.Write("Age: ");
            persons1[i].Age=int.Parse(Console.ReadLine());
            Console.Write("Occupation: ");
            persons1[i].Occupation=Console.ReadLine();
            Console.Write("Computer (true or false): ");
            persons1[i].ComputerAvailable=bool.Parse(Console.ReadLine());
            Console.Write("Experience (in years): ");
            persons1[i].YearExperience=int.Parse(Console.ReadLine());
            Console.Write("Bachelor Degree (true or false): ");
            persons1[i].BachelorDegree=bool.Parse(Console.ReadLine());
            Console.Write("Master Degree (true or false): ");
            persons1[i].MasterDegree=bool.Parse(Console.ReadLine());

            Count++;
            Console.WriteLine("Do you want to continue? (Print 'OK' or 'NO'.)");
            string answer;
            answer=Console.ReadLine();
            if (answer=="OK"||answer=="ok") continue;
            else break;
        }
        for(int i=0; i<Count;i++)
        {
            Console.WriteLine("\n\n#"+(i+1));
            Console.WriteLine(persons1[i].InformationOutput(persons1[i]));
        }
        Count=0;
        var persons2=new Builder[N];
        for (int i=0; i<10; i++)
        {
            persons2[i] = new Builder();

            Console.WriteLine("\n\nBUILDERS\n________\n");
            Console.WriteLine("Input information of a person");
            Console.Write("Name: ");
            persons2[i].Name=Console.ReadLine();
            Console.Write("Surname: ");
            persons2[i].Surname=Console.ReadLine();
            Console.Write("Age: ");
            persons2[i].Age=int.Parse(Console.ReadLine());
            Console.Write("Occupation: ");
            persons2[i].Occupation=Console.ReadLine();
            Console.Write("Instruments (true or false): ");
            persons2[i].InstrumentsAvailable=bool.Parse(Console.ReadLine());
            Console.Write("Experience (in years): ");
            persons2[i].YearExperience=int.Parse(Console.ReadLine());
            Console.Write("Education (true or false): ");
            persons2[i].Education=bool.Parse(Console.ReadLine());

            Count++;
            Console.WriteLine("Do you want to continue? (Print 'OK' or 'NO'.)");
            string answer;
            answer=Console.ReadLine();
            if (answer=="OK"||answer=="ok") continue;
            else break;
        }
        for(int i=0; i<Count;i++)
        {
            Console.WriteLine("\n\n#"+(i+1));
            Console.WriteLine(persons2[i].InformationOutput(persons2[i]));
        }
        Console.WriteLine("\nPress any key to continue . . .");
        Console.ReadKey(true);
    }
    }
}

It loos really big, so I want to pay your atention to the lines 176-178:
Delegate Del_1=new Delegate(WorkOffer);
Delegate Del_2=new Delegate(Invitation);
Delegate TwoDels=new Delegate(Del_1+Del_2);

Here I'm trying to create examples of Delegate, bur something goes wrong. Compiler shows errors "The name 'WorkOffer' does not exist in current context" and "The name 'Invitation' does not exist in current context".
I think that's all because I try to use them out of the class where these methods were declare, but what should I do then to use delegates connected to these methods in my program? I need some advice.


text:
Q: Dealing with competing events from a CI perspecrive Suppose I am a company eager to get at the (causal) effect between age and the event of contract termination. However, people can also die instead of actively terminating a contract. This seems like a classic competing events scenario to me. Similar to, e.g., death from cancer vs death from stroke.
As I am no expert on survival analysis, the following may be wrong. To my mind, this scenario looks similar to a mediation case.
Let $A$ be age at baseline, $D_t$ death, and $Y_t$ contract  termination.
The DAG would look like this to me: $A_t \rightarrow D_t \rightarrow Y_t$ and $A_t \rightarrow Y_t$. Then you also have $A \rightarrow D_{t+1} \rightarrow Y_{t+1}$ and $A \rightarrow Y_{t+1}$. Note that I think its safe to assume that there is no arrow between $Y_t$ and $D_t+1$.
Is there any way I could get at the age effect in, say, a classic cox model? I would treat death as censored in this case I suppose (i.e time to event Y, treating death as 0). What are the implications of this?
From a first hunch, this may (let's neglect all parametric assumptions here) correspond to some sort of total effect, potentially masking the (natural) direct effect, right? And perhaps this is not too bad in the case of the company versus the cancer and stroke case?

A: As the R "Multi-state models and competing risks" vignette says in Section 2.2:

A common mistake with competing risks is to use the Kaplan-Meier separately on each event type while treating other event types as censored.

Thus you would not treat death time as a censoring time if you view death (and associated contract termination) and contract termination for other causes as competing risks. Section 3 of the vignette outlines the procedure for successful joint modeling, with a detailed example of 2 competing risks including age as a covariate modeled separately for each risk.


text:
Q: Manage big data structures in python I need for some reason a four dimensional matrix in my python program which has a dimension like 10000x20000x4000x10. As I have tried to implement it using normal arrays in python I have found that it is impossible to do because of my restricted available system resources. What is the best way to manage such big data structures? Is the only way using Database?
Edit: Because it depends on what is my goal I will describe shortly what I am doing. I am trying to expand the 1 dimensional knapsack problem to 4 dimensions. There are 2 matrices keep and solution which have to be accessed. As I try to address the resource allocation problem of routers with this these 2 matrices look like this:
keep = [[[[0 for x in xrange(CORE.cap + 1)*1000]for x in xrange(RAM.cap + 1)*1000]for x in xrange(NIC.cap + 1)*1000]for x in xrange(len(JOBS) + 1)]
solution = [[[[0 for x in xrange(CORE.cap + 1)*1000]for x in xrange(RAM.cap + 1)*1000]for x in xrange(NIC.cap + 1)*1000]for x in xrange(len(JOBS) + 1)]

There are a lot of 0 in these matrices and I have to access each row of the matrices each time.

A: For 1D knapsack, you only need to keep a the last two rows of the matrix in memory. The rest you can store to disk using a run-length encoding, since most of the rows will contain the same value as the previous row. Probably, for 4D knapsack you can do something similar (like only keep a plane?) in memory and store the rest to disk.
Alternatively, you can use a branch-and-bound algorithm for knapsack or use an approximation algorithm, in which you create smaller items and knapsacks.


text:
Q: Can you Recommend me generics name which is used in service of controller? i know this convention of generics
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types

But i don't know it when I named service of generics in spring
For example,this abstract class is used when Datas do select, insert, update, delete in controller
i want to name B body of reqeust and RB to name body of response Is it okay?
Can you Recommend me generics name which is used in service of controller ?
 public abstract class AbstractService<B, RB> {

    public abstract RB doInsert(B entity);
}

Service
@Service
public class FruitInsertService extends AbstractService<FruitEntity, String[]> {

    @Override
    public String[] doInsert(FruitEntity entity) {
        return new String[] {};
    }
}

Controller
@RestController
@RequestMapping("/fruit")
public class FruitInsertController {

    @Autowired
    FruitInsertService fruitInsertService;

    @PostMapping("/insert.do")
    public ResponseEntity<Object> insertFruit(FruitEntity fruitEntity){

        return ResponseEntity.ok(fruitInsertService.doInsert(fruitEntity));
    }
}

A: If you want to go strictly by the book and the common convention, you may go for below. Note in your writeup you have already mentioned that T should be used for Type and S for Second Type etc..
public abstract class AbstractService<T, S>
However, if you want to make it more explicit and avoid any possible confusion with Second Types etc.., you could use convention like below which explains the context of usage as well.
public abstract class AbstractService<ReqT, ResT>
Optionally, you may also want to make these look like classes to depict more specific inputs, and go for something like below.
public abstract class AbstractService<Content, Response>
All options would work, but its usually driven by the convention being followed in your project/enterprise. First one is probably what you are looking for here.
Please note, while Java will not be unhappy with 2nd and 3rd options mentioned here, if you are a stickler for Code Quality and Static Analysis, Sonar will be unhappy with using such names. It expects you to use either S, T convention, or you may also choose T1, T2 to indicate the two types.
public abstract class AbstractService<T1, T2>
Between S, T and T1, T2, you should probably go for the S, T convention. Sonar expects type names to follow the pattern '^[A-Z][0-9]?$'
Hope this helps you decide. If you are confused with options, you can simply go with the 1st one.


text:
Q: Default plugin config to override wp_options? I have a few plugins that I always set the configuration for exactly the same way. Every time I create a new site, the same plugins go in, and the same amount of time is needed to set them up.
Would it be possible to create a config file that overrides whatever wp_options are set per plugin?

A: You could check which options they add (look at the source code) and then simply write a function like this:
/*
Plugin Name:    Mother of all plugins
Plugin URI:  http://wordpress.org/extend/plugins/
Description:    Offers the <code>$all_plugin_options;</code> var to access all predefined plugin options
Author:      Franz Josef Kaiser
Author URI:     http://say-hello-code.com
Version:        0.1
License:        GPL v2 - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*/

// Template Tag
function get_all_plugin_options()
{
    // First we call the class
    $class = new MotherOfAllPlugins;
    $data = $class->predefined_plugin_options()
    return $data;
}

if ( ! class_exists('MotherOfAllPlugins') )
{

class MotherOfAllPlugins
{
    protected $plugin_options;

    public function __construct( $plugin_options )
    {
      // defaults
      $default_options = array(
         'plugin_a' => array(
             'deprecated' => ''
            ,'name'       => 'value'
            ,'key'        => 'value'
          )
        ,'plugin_b' => array(
             'deprecated' => ''
            ,'name'       => 'value'
            ,'key'        => 'value'
          )
      );
      // Now overwrite the
      $this->plugin_options = array_merge( $default_options, $plugin_options );

      add_action( 'init', 'predefined_plugin_options' );
    }

    function predefined_plugin_options()
    {

      // Set the flag if we have already done this
      // _EDIT #1:_ This sets an option in the wp_options table containing TRUE if your plugin predef options are already present in the DB
      if ( !get_option( 'predef_plugins_setup' ) === TRUE )
         add_option( 'predef_plugins_setup', TRUE );

      if ( !get_option( 'predef_plugins_setup' ) === TRUE )
      {
         // Add the options for the plugins
         foreach ( $plugin_options as $plugin => $options )
         {
            add_option( $plugin, $options, $options['deprecated'], 'yes' );
         }
      }

      // _EDIT #2:_ return the initial array for use in a global
      return $plugin_options
    }

} // END Class MotherOfAllPlugins

} // endif;

To get your plugin options inside your theme:
// Now we take the return value & add it into global scope for further useage.
// This way we can access all options easily without a call to the DB.
// You can now access these values from anywhere in your theme.
$all_plugin_options = get_all_plugin_options();

Be careful to really add the options exactly the way the plugins does it. Else stuff won't work.

A: You could put something like this in your theme's function.php.
This way it only runs once (when the theme is activated).
add_option('my_initial_options', false);

if ( get_option('my_initial_options')== false ){
    addmyOptions();
    update_option( 'my_initial_options', true,'','yes' );
}

function addmyOptions(){

update_option("posts_per_page",1);
update_option( 'show_on_front', 'page' );

}

A: Not sure if something like that is possible but a workaround would be to use a dummy database of default WP install configured with all those plugins. Now whenever you need to setup another site, put in this database and edit the home url and site url.


text:
Q: Get multiple lines into a single stream I work on AS400 and have a very large file which I download in .txt using IMAIL.
I need to send this file in a single stream. I get the .txt file having the data
broken up into multiple lines and lots of spaces at the end of each line.
The data which I have in the .txt file doesnt follow any pattern.
How do I get the data in a single stream?
Any help on this would be greatly appreciated.
Regards,
Sohail

A:
I get the .txt file having the data broken up into multiple lines and
  lots of spaces at the end of each line.

To me, it sounds like a program-described or source file member copied to the directory with CPYTOSTMF. The initial fixed-length records are preserving trailing spaces and some combination of newline and carriage return characters is added at the end of each line. That would cause both the excess spaces and the "multiple lines".
It would possibly be best to run your own CPYTOSTMF command to generate the IFS streamfile requesting perhaps only *LF as the record delimiter. Then, after the streamfile is in the target directory, you could run the Qshell tr utility to remove the line-ending newline:
tr -d '\n' < mystmf.txt > NOLF.txt

The output from tr would be NOLF.txt in that example.


text:
Q: How to get Number pattern in specific shape (java)? I want to print number pattern like this..
but, I failed to get this triangle shape,and I am confused how to put spaces to get this shape -->
   1
  212
 32123
4321234

Here's the code i tried so far
public class Ch {

    public static void main(String[] args) {
        int r =Integer.parseInt(args[0]);
        for(int u=1;u<=r;u++)
        {
            for(int i=u;i>=1;i--)
            {
                System.out.print(i);
            }

            for(int i=2;i<=u;i++)
            {
                System.out.print(i);
            }
            System.out.println();
        }
    }
}

output of this code looks-like this
     1
     212
     32123
     4321234

Thanks

A: Just add one more step in you main loop before the other two:
for (int i = u; i < r; i++)
{
    System.out.print(" ");
}

This will print spaces to make up for the "missing" numbers.
In regard to Mateusz' comment, look at this answer on how to pad your numbers with spaces to make them equally wide in case you go beyond 9:
static int padding;

public static void main(String[] args)
{
    int r = Integer.parseInt(args[0]);

    padding = Math.max(1, (int) Math.ceil(Math.log10(r)));

    for (int u = 1; u <= r; u++)
    {
        for (int i = u; i < r; i++)
        {
            print(" ");
        }

        for (int i = u; i >= 1; i--)
        {
            print(i);
        }

        for (int i = 2; i <= u; i++)
        {
            print(i);
        }
        System.out.println();
    }
}
private static void print(Object text)
{
    System.out.print(String.format("%1$" + padding + "s", text));
}

A:
using 2 for loops
package com.stackoverflow;

import java.util.Scanner;

public class Pyramid {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the pyramid limit value: ");
        int limit = in.nextInt();
        in.close();
        for (int i = 0; i < limit; i++) {
            for (int j = 0; j < limit + i; j++) {
                if (j < limit -i-1)
                    System.out.print(" ");
                else{
                    int temp = (limit-j > 0) ? limit-j : j-limit+2;
                    System.out.print(temp);
                }
            }
            System.out.println();
        }
    }

       }
using 4 for loops
package com.stackoverflow;

import java.util.Scanner;

public class Pyramid {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the pyramid limit value: ");
        int limit = in.nextInt();
        in.close();
        for (int i = 0; i < limit; i++) {
            for(int j=0; j<limit-i; j++){
                System.out.print(" ");
            }
            for(int j=0; j<=i; j++){
                System.out.print(i-j+1);
            }
            for(int j=i; j>0; j--){
                System.out.print(i-j+2);
            }
            System.out.println();
        }
    }
}


text:
Q: OAuthWebSecurity doesnt work I develop our application and allows the user to login via Facebook, Microsoft, Google, Twitter and LinkedIn.
In Globas.asax registering services:
protected void Application_Start(object sender, EventArgs e)
        {
            BundleTable.EnableOptimizations = !HttpContext.Current.IsDebuggingEnabled;
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
                new ScriptResourceDefinition
                {
                    Path = "~/Scripts/jquery-1.10.2.min.js",
                    DebugPath = "~/Scripts/jquery-1.10.2.js"
                });

            this.RegisterAuthenticationProviders();
        }

        private void RegisterAuthenticationProviders()
        {
            OAuthWebSecurity.RegisterFacebookClient("key1", "key2", "Facebook");
            OAuthWebSecurity.RegisterGoogleClient("Google");
            OAuthWebSecurity.RegisterLinkedInClient("key1", "key2", "LinkedIn");
            OAuthWebSecurity.RegisterMicrosoftClient("key1", "key2", "Microsoft");
            OAuthWebSecurity.RegisterTwitterClient("key1", "key2", "Twitter");
        }

At the click of a button calls the appropriate method:
OAuthWebSecurity.RequestAuthentication("ServiceName", String.Format("~/Login.ashx"));

serviceNames are:Microsoft, Google, LinkedIn, Facebook or Twitter according to the button that is pressed.
Handler Login.aspx look like:
public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            var result = OAuthWebSecurity.VerifyAuthentication();
            if (result.IsSuccessful)
            {
                var service = (LoginServices)Enum.Parse(typeof(LoginServices), result.Provider, true);
                //Find user in DB, if not find create and login at last
                this.TryLogin(result, context, service);

                this.RedirectRequest(context);
            }
            else
            {
                // Login failed
                DBLogger.WriteLog(LogPriority.Fatal, String.Format("{0}-{1}_1", this.GetType().Name, "ProcessRequest"), result.Error);
                this.RedirectRequest(context, ErrorMessages.LoginFailed);
            }
    }

Facebook: is fine and everything is working correctly
Microsoft: redirect to login is fine, but in return I will return error:
The remote server returned an error: (400) Bad Request.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
 Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.
Source Error:
 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[WebException: The remote server returned an error: (400) Bad Request.]
   System.Net.HttpWebRequest.GetResponse() +6442312
   DotNetOpenAuth.AspNet.Clients.MicrosoftClient.QueryAccessToken(Uri returnUrl, String authorizationCode) +334
   DotNetOpenAuth.AspNet.Clients.OAuth2Client.VerifyAuthentication(HttpContextBase context, Uri returnPageUrl) +142
   DotNetOpenAuth.AspNet.OpenAuthSecurityManager.VerifyAuthentication(String returnUrl) +239
   Microsoft.Web.WebPages.OAuth.OAuthWebSecurity.VerifyAuthenticationCore(HttpContextBase context, String returnUrl) +129
   Microsoft.Web.WebPages.OAuth.OAuthWebSecurity.VerifyAuthentication(String returnUrl) +86
   Login.ProcessRequest(HttpContext context) +18
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +341
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69

Google and LinkedIn: Click on the link I report the javascript error: Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 0
Twitter Click on the link I report the javascript error:
Sys.WebForms.PageRequestManagerServerErrorException: Error occurred while sending a direct message or getting the response.

The buttons are  with register onclick envet in OnInit event in page.
Do you have any idea why my code does not work?
Thanks
Update
Problem solved. It was all that was ImageButtons in UpdatePanel

A: For LinkedIn, just update package, it will work for sure.

update-package DotNetOpenAuth.Core

hit 'Enter' and enjoy.


text:
Q: Rename Selected folder inside directory folder using python i need help to create a code using python to rename specific folder inside many subfolder in side the main folder
Example:
theirs folder name fromDrawing inside many folder subfolder and need to rename it to Drawing
main folder
sub-folders

A: To rename folder using python, you can use the os.rename functionality..
Example:
import os,sys
os.rename("path_to_initial_folder","same_path_with_changed_name")

A: Try using sys/os? I'm not good with sys and os, so I can't give you an example. (I have just never needed it really.)


text:
Q: pthread_cond_signal does not wake up the thread that waits I am writing a program which creates a thread that prints 10 numbers. When it prints 5 of them, it waits and it is notifying the main thread and then it continues for the next 5 numbers
This is test.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>

int rem = 10;
int count = 5;
pthread_mutex_t mtx;
pthread_cond_t cond1;
pthread_cond_t cond2;

void *f(void *arg)
{
  int a;
  srand(time(NULL));
  while (rem > 0) {
      a = rand() % 100;
      printf("%d\n",a);
      rem--;
      count--;
      if (count==0) {
          printf("time to wake main thread up\n");
          pthread_cond_signal(&cond1);
          printf("second thread waits\n");
          pthread_cond_wait(&cond2, &mtx);
          printf("second thread woke up\n");
      }
  }
  pthread_exit(NULL);
}

int main()
{
  pthread_mutex_init(&mtx, 0);
  pthread_cond_init(&cond1, 0);
  pthread_cond_init(&cond2, 0);
  pthread_t tids;
  pthread_create(&tids, NULL, f, NULL);
  while(1) {
    if (count != 0) {
      printf("main: waiting\n");
      pthread_cond_wait(&cond1, &mtx);
      printf("5 numbers are printed\n");
      printf("main: waking up\n");
      pthread_cond_signal(&cond2);
      break;
    }
   pthread_cond_signal(&cond2);
   if (rem == 0) break;

 }
 pthread_join(tids, NULL);
}

The output of the program is:
main: waiting
//5 random numbers
time to wake main thread up
second thread waits
5 numbers are printed
main: waking up

Since I do pthread_cond_signal(&cond2);I thought that the thread will wake up and prints the rest numbers but this is not the case. Any ideas why? Thanks in advance.

A: Summary
The issues have been summarized in comments, or at least most of them.  So as to put an actual answer on record, however:
Pretty much nothing about the program's use of shared variables and synchronization objects is correct.  It's behavior is undefined, and the specific manifestation observed is just one of the more likely in a universe of possible behaviors.
Accessing shared variables
If two different threads access (read or write) the same non-atomic object during their runs, and at least one of the accesses is a write, then all accesses must be properly protected by synchronization actions.
There is a variety of these, too large to cover comprehensively in a StackOverflow answer, but among the most common is to use a mutex to guard access.  In this approach, a mutex is created in the program and designated for protecting access to one or more shared variables. Each thread that wants to access one of those variables locks the mutex before doing so.  At some later point, the thread unlocks the mutex, lest other threads be permanently blocked from locking the mutex themselves.
Example:
pthread_mutex_t mutex;  // must be initialized before use

int shared_variable;

// ...

void *thread_one_function(void *data) {
    int rval;

    // some work ...

    rval = pthread_mutex_lock(&mutex);
    // check for and handle lock failure ...

    shared_variable++;
    // ... maybe other work ...

    rval = pthread_mutex_unlock(&mutex);
    // check for and handle unlock failure ...

    // more work ...
}

In your program, the rem and count variables are both shared between threads, and access to them needs to be synchronized.  You already have a mutex, and using it to protect accesses to these variables looks like it would be appropriate.
Using condition variables
Condition variables have that name because they are designed to support a specific thread interaction pattern: that one thread wants to proceed past a certain point only if a certain condition, which depends on actions performed by other threads, is satisfied.  Such requirements arise fairly frequently.  It is possible to implement this via a busy loop, in which the thread repeatedly tests the condition (with proper synchronization) until it is true, but this is wasteful.  Condition variables allow such a thread to instead suspend operation until a time when it makes sense to check the condition again.
The correct usage pattern for a condition variable should be viewed as a modification and specialization of the busy loop:

*

*the thread locks a mutex guarding the data on which the condition is to be computed;

*the thread tests the condition;

*if the condition is satisfied then this procedure ends;

*otherwise, the thread waits on a designated condition variable, specifying the (same) mutex;

*when the thread resumes after its wait, it loops back to (2).

Example:
pthread_cond_t cv;  // must be initialized before use

void *thread_two_function(void *data) {
    int rval;

    // some work ...

    rval = pthread_mutex_lock(&mutex);
    // check for and handle lock failure ...

    while (shared_variable < 5) {
        rval = pthread_cond_wait(&cv, &mutex);
        // check for and handle wait failure ...
    }

    // ... maybe other work ...

    rval = pthread_mutex_unlock(&mutex);
    // check for and handle unlock failure ...

    // more work ...
}

Note that

*

*the procedure terminates (at (3)) with the thread still holding the mutex locked.  The thread has an obligation to unlock it, but sometimes it will want to perform other work under protection of that mutex first.

*the mutex is automatically released while the thread is waiting on the CV, and reacquired before the thread returns from the wait.  This allows other threads the opportunity to access shared variables protected by the mutex.

*it is required that the thread calling pthread_cond_wait() have the specified mutex locked.  Otherwise, the call provokes undefined behavior.

*this pattern relies on threads to signal or broadcast to the CV at appropriate times to notify any then-waiting other threads that they might want to re-evaluate the condition for which they are waiting.  That is not modeled in the examples above.

*multiple CVs can use the same mutex.

*the same CV can be used in multiple places and with different associated conditions.  It makes sense to do this when all the conditions involved are affected by the same or related actions by other threads.

*condition variables do not store signals.  Only threads that are already blocked waiting for the specified CV are affected by a pthread_cond_signal() or pthread_cond_broadcast() call.

Your program
Your program has multiple problems in this area, among them:

*

*Both threads access shared variables rem and count without synchronization, and some of the accesses are writes.  The behavior of the whole program is therefore undefined.  Among the common manifestations would be that the threads do not observe each other's updates to those variables, though it's also possible that things seem to work as expected.  Or anything else.

*Both threads call pthread_cond_wait() without holding the mutex locked.  The behavior of the whole program is therefore undefined.  "Undefined" means "undefined", but it is plausible that the UB would manifest as, for example, one or both threads failing to return from their wait after the CV is signaled.

*Neither thread employs the standard pattern for CV usage.  There is no clear associated condition for either one, and the threads definitely don't test one.  That leaves an implied condition of "this CV has been signaled", but that is unsafe because it cannot be tested before waiting.  In particular, it leaves open this possible chain of events:

*

*The main thread blocks waiting on cond1.

*The second thread signals cond1.

*The main thread runs all the way at least through signaling cond2 before the second thread proceeds to waiting on cond2.

Once (3) occurs, the program cannot avoid deadlock.  The main thread breaks from the loop and tries to join the second thread, meanwhile the second thread reaches its pthread_cond_wait() call and blocks awaiting a signal that will never arrive.
That chain of events can happen even if the issues called out in the previous points is corrected, and it could manifest exactly the observable behavior you report.


text:
Q: how to remove the numbers before a word on files names i have this files names
dbo-101ar_thumb657.jpg door-27ar_thumb641.jpg ishq-283ar_thumb639.jpg ksm-365ar_thumb599.jpg pkyek-302_thumb604.jpg pun-68ar_thumb694.jpg
what i'm trying to do is remove the numbers after thumb
so must be like this
dbo-101ar_thumb.jpg door-27ar_thumb.jpg ishq-283ar_thumb.jpg ksm-365ar_thumb.jpg pkyek-302_thumb.jpg pun-68ar_thumb.jpg
what command should i use in centos 7 ???

A: You could try this:
for f in *; do
echo $f | sed 's#[0-9]*\.#\.#g'
done

Will output:
dbo-101ar_thumb.jpg
door-27ar_thumb.jpg
ishq-283ar_thumb.jpg
ksm-365ar_thumb.jpg
pkyek-302_thumb.jpg
pun-68ar_thumb.jpg

If will read all the files in the current directory and later by using sed 's#[0-9]*\.#\.#g' it replaces numbers ending with a "." with a "."
You could also use find to prefilter your input, something like this:
find . -iname "*thumb*.jpg" -exec sh -c "echo {} | sed 's#[0-9]*\.#\.#g'" \;

It will match any file with this pattern *thumb*.jpg and later use sed to replace the numbers like explained before.
If you would like to cp or mv the files you could use something like:
find . -iname "*thumb*.jpg" -exec sh -c 'x=`echo {} | sed "s#[0-9]*\.#\.#g"`; mv {} $x' \;

A: Look for thumb followed by 0 or more digits and replace it with thumb.
sed 's/thumb[0-9]*/thumb/g'

Or only replace when you have at least 1 digit (in this case the same result):
sed 's/thumb[0-9]\+/thumb/g'


text:
Q: PowerShell unordered HTML list I'm trying to create a function to generate an unordered HTML list. This works fine when I use it like ConvertTo-HTMLlist $MyArray, but not when I pipe information to it like $MyArray | ConvertTo-HTMLlist.
My function:
Function ConvertTo-HTMLlist {
    [CmdletBinding(SupportsShouldProcess=$True)]
    Param (
        [parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
        [ValidateNotNullOrEmpty()]
        $Array
    )
    Process {
        $Array = @(foreach ($_ in $Array) {"
" + $_ + "

"}) # Add extra space
        $Array = ,"
$($Array | Sort-Object)
"
        $Array = $Array.Replace("

", "

") # Remove last double breaks
        $Array += "
<font size=`"2`">* Native PowerShell errors are displayed in <font color=`"red`">red.
"
        Write-Output $Array
    }
}

Results:
$MyArray = 'Apples', 'Peers', 'Bananas'

ConvertTo-HTMLlist $MyArray

# Correct result:

Apples

Bananas

Peers

* Native PowerShell errors are displayed in red.</f
ont>

$MyArray | ConvertTo-HTMLlist

# Incorrect result:

Apples

* Native PowerShell errors are displayed in red.

Peers

* Native PowerShell errors are displayed in red.

Bananas

* Native PowerShell errors are displayed in red.

There should be a way to collect everything from the pipeline first, and then start handling it.

A: Because everything is possible in PowerShell, I've played a bit more with the Begin, Process and End clauses in a function. And I think I've got it working as desired:
$MyArray = 'Apples', 'Peers', 'Bananas'

Function ConvertTo-HTMLlist {
    [CmdletBinding(SupportsShouldProcess=$True)]
    Param (
        [parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
        [ValidateNotNullOrEmpty()]
        $Array
    )
    Begin {
        $tmpArray = New-Object System.Collections.ArrayList
    }
    Process {
        $Array | ForEach-Object {
            $tmpArray.Add("
" + $_ + "

") | Out-Null
        }
    }
    End {
        $tmpArray = ,"
$($tmpArray | Sort-Object)
"
        $tmpArray = $tmpArray.Replace("

", "

") # Remove last double breaks
        $tmpArray += "
<font size=`"2`">* Native PowerShell errors are displayed in <font color=`"red`">red.
"
        Write-Output $tmpArray
    }
}

Write-Host "Piped result:" -ForegroundColor Yellow
$MyArray | ConvertTo-HTMLlist

Write-Host "Non piped result:" -ForegroundColor Yellow
ConvertTo-HTMLlist $MyArray

Let me know what you think.


text:
Q: Where are docker events stored? Can they be redirected to syslog server? I have a server with docker running. I can use the command docker events to monitor events as they occur. But I can also use the command option --since <timestamp> to list previously occured events.
# docker events --since '2022-03-20'
2022-03-22T23:56:47.734684472Z network connect daee956f7a48538470209a02318f9312)
2022-03-22T23:56:47.975103504Z container start 8245dab2d81075a856594bb164be34ac)
2022-03-25T06:25:07.473690045Z container pause 8245dab2d81075a856594bb164be34ac)
2022-03-25T06:25:18.728654844Z container unpause 8245dab2d81075a856594bb164be34)
2022-03-25T06:25:26.919184476Z container exec_create: /bin/sh  8245dab2d81075a8)
2022-03-25T06:25:29.068042340Z container exec_start: /bin/sh  8245dab2d81075a85)

So the events must be stored somewhere. Where are they stored? I see that there is a <contaniner-id>-json.log but it is empty.
As a follow up question. Can I have these event logs redirected/copied to a syslog server instead?

A: As far as I can tell, since I have the same need, that this was discussed by the docker team and it was decided that this would result in a massive log file and be of little use to anyone. Then the ticket was closed
I cannot see any change in attitude towards this. There are plenty of ways to feed the stream of events into other logging/monitoring/dashboard tools so perhaps the docker world has learned to live with it
Personally I am going to write a systemd service to watch the stream, trim the data and write it to a log and let logrotate deal with it :)


text:
Q: Force shutil copy to continue through list when encountering missing source file I'm using shutil to copy output from an upstream process based on user supplied files. Sometimes those files aren't compatible with the upstream process, and as such the final file I'm attempting to move won't be created.
I'm handing shutil a list of verbose file paths, I want it to continue to move all items in the list even when one or more of the source files are missing.
source = ['/home/Desktop/folder/subfolder/file.ext', '/home/Desktop/folder/subfolder2/file2.ext', '/home/Desktop/folder/subfolder3/file3.ext']
dest = ['/home/Desktop/target/file.ext','/home/Desktop/target/file2.ext', '/home/Desktop/target/file3.ext']
for sou, des in zip(source, dest):
    shutil.copyfile(sou, des)

A: One approach would be to simply add exception handling around the call, for example:
import shutil

source = ['/home/Desktop/folder/subfolder/file.ext', '/home/Desktop/folder/subfolder2/file2.ext', '/home/Desktop/folder/subfolder3/file3.ext']
dest = ['/home/Desktop/target/file.ext','/home/Desktop/target/file2.ext', '/home/Desktop/target/file3.ext']

for sou, des in zip(source, dest):
    try:
        shutil.copyfile(sou, des)
    except IOError as e:
        print e

This would display the following for missing files:
[Errno 2] No such file or directory: '/home/Desktop/folder/subfolder/file.ext'
[Errno 2] No such file or directory: '/home/Desktop/folder/subfolder2/file2.ext'
[Errno 2] No such file or directory: '/home/Desktop/folder/subfolder3/file3.ext'


text:
Q: How to block mouse input from transparent window with Win32 API? I have a main window in a process that is not owned by the program I'm creating. I'm using a Windows Hook to inject a DLL into this process for the purpose of adding a child window to this main window.
My end goal was to create a WS_EX_LAYERED window that allows me to create an internal colored border but allow the center portion to be transparent and allow mouse clicks through. This part works perfectly.
WNDCLASS wndClass = {};
wndClass.style = CS_HREDRAW | CS_VREDRAW;
wndClass.lpfnWndProc = OverlayProc;
wndClass.hInstance = g_TargetInstance;
wndClass.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(0, 255, 255));
wndClass.lpszClassName = "OVERLAY";

RegisterClass(&wndClass);
g_Window = CreateWindowEx(WS_EX_LAYERED | WS_EX_TRANSPARENT, "OVERLAY", nullptr,
    WS_CHILDWINDOW, rect.left, rect.top, rect.right+1, rect.bottom+1, data->hwnd, nullptr, g_TargetInstance, nullptr);

SetLayeredWindowAttributes(g_Window, RGB(0, 255, 255), 0, LWA_COLORKEY);

ShowWindow(g_Window, SW_SHOW);
UpdateWindow(g_Window);

The 2nd part to this is a I wanted to conditionally block all mouse input to the parent window. I couldn't do this with the transparent portion of the WS_EX_LAYERED window so I tried creating a 2nd transparent STATIC control as a child of the main window but this doesn't block mouse input either.
I'm also sending simulated mouse clicks to the parent window through calls to PostMessage, passing WM_LBUTTONDOWN and WM_LBUTTONUP. How could I block all mouse input to the parent window via a transparent window?

A: It appears this is not possible to do with a simple transparent window drawn over sibling controls. What I ended up doing was using SetWindowHookEx to add a WH_GETMESSAGE hook into the process from which I use to replace the main window's WndProc function and intercept mouse messages. I tag my simulated mouse messages with a specific value in the wParam argument so the proc will now it was simulated and removes that value, passing it along to the parent window.
If it does not detect my "tag" value in the click message, it will swallow the mouse message and not pass it along to the original WndProc function.
Injected WndProc replacement
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
    switch (uMsg)
    {
        case WM_LBUTTONDOWN:
            wParam -= 11141008;
            if (wParam != MK_LBUTTON && !g_Paused)
                return 0;
            break;

        case WM_LBUTTONUP:
            wParam -= 11141008;
            if (wParam != 0 && !g_Paused)
                return 0;
            break;

        case WM_MOUSEHOVER:
        case WM_MOUSEMOVE:
            if (!g_Paused)
                return 0;
    }

    return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}

Snippet from Windows Hook function
//...
switch (data->message)
{
    case (WM_USER + 1):
    {
        g_Paused = FALSE;
        //...
        SetWindowSubclass(data->hwnd, WndProc, 1, 0);
        break;
    }

    case (WM_USER + 2):
    {
        RemoveWindowSubclass(data->hwnd, WndProc, 1);
        //...
        break;
    }
}
//...

The code inside the window hook function is used to subclass the main process window and inject my own WndProc function which in turn processes mouse input the way I want.
This is the code used to "simulate" mouse clicks without physically clicking in the window. Note the added value to wParam to identify this click as simulated and not generated by the user.
void Window::LeftClick(DWORD x, DWORD y, DWORD delayMillis)
{
    LPARAM lparam = MAKELPARAM(x, y);

    lock_guard<mutex> lock(this->m_ClickMutex);

    PostMessage(this->m_Window, WM_LBUTTONDOWN, 11141008 + MK_LBUTTON, lparam);
    this_thread::sleep_for(std::chrono::milliseconds(delayMillis));
    PostMessage(this->m_Window, WM_LBUTTONUP, 11141008, lparam);
}

Also, just for the person in the comments who was ridiculing my choice of the word simulated and the added criticism for using PostMessage to simulate keyboard input, here is my keyboard input test method which (for my purposes) works flawlessly and very reliably
void GameWindow::KeyPress(UINT vkCode) const
{
    UINT scanCode = MapVirtualKey(vkCode, MAPVK_VK_TO_VSC);
    LPARAM lparam1 = MAKELPARAM(1, scanCode);
    LPARAM lparam2 = MAKELPARAM(1, 0xC000 | scanCode);

    PostMessage(this->m_Window, WM_KEYDOWN, vkCode, lparam1);
    this_thread::sleep_for(chrono::milliseconds(25));
    PostMessage(this->m_Window, WM_KEYUP, vkCode, lparam2);
}


text:
Q: How to write rspec tests for controllers that assume authentication For controllers that assume a user to be already authenticated, how should I go about writing my tests?
I probably don't need to keep testing the login feature, so is it best to just inject a user or whatever my authentication assumes somehow?
My application_controller includes a module "current_user".
module CurrentUser
  def self.included(base)
    base.send :helper_method, :current_user
  end

  def current_user
    ... # returns a User model instance
  end
end

class ApplicationController < ActionController::Base
  include CurrentUser

Then I have an admin controller which has a before_action method that makes sure the current_user is present.

A: You can easily achieve this by writing a concern, and include to every spec which is a controller, in this concern we support some utility methods to login to the system.
So the code will be like:
spec/support/controller_authentication_helper.rb
module ControllerAuthenticationHelper extend ActiveSupport::Concern
  module ClassMethods
    def login_user
      before do
        # I expect you are using Devise here, if not, just modify below line
        request.env['devise.mapping'] = Devise.mappings[:user]
        @current_user = FactoryGirl.create(:user, :confirmed, :verified)
        sign_in @current_user
      end
    end
  end
end

RSpec.configure do |config|
  config.include ControllerAuthenticationHelper, type: :controller
end

So now the test will be easy like:
require 'rails_helper'

describe MyController, type: :controller do
  # Use this method to login
  login_user
  # Now you can access current_user anywhere in your test
end

Now everything becomes simple! The idea comes from this source code of Devise


text:
Q: Restore Chrome/Safari/Firefox/IE8+ outline on all focus items We are using some JavaScript libraries that include the dreaded :focus {outline: none;}.
I don't want to mess with the libraries because the next time I upgrade the library, my code will be lost.
For example (alas, not the only such library), FlexSlider has the following code:
.flex-container a:hover,
.flex-slider a:hover,
.flex-container a:focus,
.flex-slider a:focus
  { outline: none; }

I see that there is a post Restore Webkit's CSS outline on input field, and we in fact use that code.
:focus
  { outline: auto 5px -webkit-focus-ring-color; }

However, that leaves our Firefox and IE visitors without outlines. How do I do a cross-browser outline restoration in my CSS file?
I'm thinking I could use jQuery to excise the problematic rule, but that's subject to breaking if they change their library, and won't help visitors who have JavaScript disabled.
I was also thinking I could do:
*:focus
  { outline: inherit !important; }

but was wondering if there might be unintended consequences, as in a browser having different outline styles for different tags.
You can see this in action on the San Francisco Municipal Transportation Agency home page in the slider to the right of the dark green area.

A: Found it in Bootstrap
a:focus {
  outline: thin dotted;
  outline: 5px auto -webkit-focus-ring-color;
  outline-offset: -2px;
}

Not sure about the outline-offset one; that may be a stylistic decision.


text:
Q: Replacing FIRST batch file from a CALLed SECOND batch file OK when its running? WinXP, Win7
FIRST.BAT Calls SECOND.BAT.
Can SECOND.BAT safely replace FIRST.BAT?
FIRST.BAT:
@echo Hi, I need to be placed.
CALL SECOND.BAT

SECOND.BAT:
@echo Time to replace FIRST.BAT
copy /y NEWFIRST.BAT FIRST.BAT

Thanks!


text:
Q: How to make seekBar bubble onClick I want the parent view to reset a timeout every time the user touch on the views inside a container view. It works well except for the seekBar View that doesn't bubble any click.
Update:
The listener is set at the parent view like this:
  this.setAddStatesFromChildren(true);//has no effect

  this.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "reset hide timer: ");
            handler.removeCallbacks(hideCallback);
            //playerControls is a compound view
            playerControls.setVisibility(VISIBLE);

            handler.postDelayed(hideCallback, 5000);
        }
    });

This code catch all events from the child views but fail to get events from the seekbar inside the playerControls view. The view have other components that bubble events, just not seekbar.
The parent view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bar">

<android.support.v7.widget.AppCompatImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/show"
    />

<..PlayerControls
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/player_controls"
    android:layout_below="@id/show"
    android:visibility="gone"
    />

</RelativeLayout>

and the child view (PlayerControls):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/player_controls"
    >

    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/duration"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <android.support.v7.widget.AppCompatSeekBar
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:id="@+id/seek_bar"
        />

</RelativeLayout>